PackageManagerService.java revision 5e10e8f1b2126f031b976b853c3f150418f3b342
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_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.ContentResolver;
113import android.content.Context;
114import android.content.IIntentReceiver;
115import android.content.Intent;
116import android.content.IntentFilter;
117import android.content.IntentSender;
118import android.content.IntentSender.SendIntentException;
119import android.content.ServiceConnection;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.AppsQueryHelper;
123import android.content.pm.ComponentInfo;
124import android.content.pm.EphemeralApplicationInfo;
125import android.content.pm.EphemeralIntentFilter;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.PatternMatcher;
183import android.os.Process;
184import android.os.RemoteCallbackList;
185import android.os.RemoteException;
186import android.os.ResultReceiver;
187import android.os.SELinux;
188import android.os.ServiceManager;
189import android.os.ShellCallback;
190import android.os.SystemClock;
191import android.os.SystemProperties;
192import android.os.Trace;
193import android.os.UserHandle;
194import android.os.UserManager;
195import android.os.UserManagerInternal;
196import android.os.storage.IMountService;
197import android.os.storage.MountServiceInternal;
198import android.os.storage.StorageEventListener;
199import android.os.storage.StorageManager;
200import android.os.storage.VolumeInfo;
201import android.os.storage.VolumeRecord;
202import android.provider.Settings.Global;
203import android.provider.Settings.Secure;
204import android.security.KeyStore;
205import android.security.SystemKeyStore;
206import android.system.ErrnoException;
207import android.system.Os;
208import android.text.TextUtils;
209import android.text.format.DateUtils;
210import android.util.ArrayMap;
211import android.util.ArraySet;
212import android.util.Base64;
213import android.util.DisplayMetrics;
214import android.util.EventLog;
215import android.util.ExceptionUtils;
216import android.util.Log;
217import android.util.LogPrinter;
218import android.util.MathUtils;
219import android.util.Pair;
220import android.util.PrintStreamPrinter;
221import android.util.Slog;
222import android.util.SparseArray;
223import android.util.SparseBooleanArray;
224import android.util.SparseIntArray;
225import android.util.Xml;
226import android.util.jar.StrictJarFile;
227import android.view.Display;
228
229import com.android.internal.R;
230import com.android.internal.annotations.GuardedBy;
231import com.android.internal.app.IMediaContainerService;
232import com.android.internal.app.ResolverActivity;
233import com.android.internal.content.NativeLibraryHelper;
234import com.android.internal.content.PackageHelper;
235import com.android.internal.logging.MetricsLogger;
236import com.android.internal.os.IParcelFileDescriptorFactory;
237import com.android.internal.os.InstallerConnection.InstallerException;
238import com.android.internal.os.SomeArgs;
239import com.android.internal.os.Zygote;
240import com.android.internal.telephony.CarrierAppUtils;
241import com.android.internal.util.ArrayUtils;
242import com.android.internal.util.FastPrintWriter;
243import com.android.internal.util.FastXmlSerializer;
244import com.android.internal.util.IndentingPrintWriter;
245import com.android.internal.util.Preconditions;
246import com.android.internal.util.XmlUtils;
247import com.android.server.AttributeCache;
248import com.android.server.EventLogTags;
249import com.android.server.FgThread;
250import com.android.server.IntentResolver;
251import com.android.server.LocalServices;
252import com.android.server.ServiceThread;
253import com.android.server.SystemConfig;
254import com.android.server.Watchdog;
255import com.android.server.net.NetworkPolicyManagerInternal;
256import com.android.server.pm.PermissionsState.PermissionState;
257import com.android.server.pm.Settings.DatabaseVersion;
258import com.android.server.pm.Settings.VersionInfo;
259import com.android.server.storage.DeviceStorageMonitorInternal;
260
261import dalvik.system.CloseGuard;
262import dalvik.system.DexFile;
263import dalvik.system.VMRuntime;
264
265import libcore.io.IoUtils;
266import libcore.util.EmptyArray;
267
268import org.xmlpull.v1.XmlPullParser;
269import org.xmlpull.v1.XmlPullParserException;
270import org.xmlpull.v1.XmlSerializer;
271
272import java.io.BufferedOutputStream;
273import java.io.BufferedReader;
274import java.io.ByteArrayInputStream;
275import java.io.ByteArrayOutputStream;
276import java.io.File;
277import java.io.FileDescriptor;
278import java.io.FileInputStream;
279import java.io.FileNotFoundException;
280import java.io.FileOutputStream;
281import java.io.FileReader;
282import java.io.FilenameFilter;
283import java.io.IOException;
284import java.io.PrintWriter;
285import java.nio.charset.StandardCharsets;
286import java.security.DigestInputStream;
287import java.security.MessageDigest;
288import java.security.NoSuchAlgorithmException;
289import java.security.PublicKey;
290import java.security.SecureRandom;
291import java.security.cert.Certificate;
292import java.security.cert.CertificateEncodingException;
293import java.security.cert.CertificateException;
294import java.text.SimpleDateFormat;
295import java.util.ArrayList;
296import java.util.Arrays;
297import java.util.Collection;
298import java.util.Collections;
299import java.util.Comparator;
300import java.util.Date;
301import java.util.HashSet;
302import java.util.Iterator;
303import java.util.List;
304import java.util.Map;
305import java.util.Objects;
306import java.util.Set;
307import java.util.concurrent.CountDownLatch;
308import java.util.concurrent.TimeUnit;
309import java.util.concurrent.atomic.AtomicBoolean;
310import java.util.concurrent.atomic.AtomicInteger;
311
312/**
313 * Keep track of all those APKs everywhere.
314 * <p>
315 * Internally there are two important locks:
316 * <ul>
317 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
318 * and other related state. It is a fine-grained lock that should only be held
319 * momentarily, as it's one of the most contended locks in the system.
320 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
321 * operations typically involve heavy lifting of application data on disk. Since
322 * {@code installd} is single-threaded, and it's operations can often be slow,
323 * this lock should never be acquired while already holding {@link #mPackages}.
324 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
325 * holding {@link #mInstallLock}.
326 * </ul>
327 * Many internal methods rely on the caller to hold the appropriate locks, and
328 * this contract is expressed through method name suffixes:
329 * <ul>
330 * <li>fooLI(): the caller must hold {@link #mInstallLock}
331 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
332 * being modified must be frozen
333 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
334 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
335 * </ul>
336 * <p>
337 * Because this class is very central to the platform's security; please run all
338 * CTS and unit tests whenever making modifications:
339 *
340 * <pre>
341 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
342 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
343 * </pre>
344 */
345public class PackageManagerService extends IPackageManager.Stub {
346    static final String TAG = "PackageManager";
347    static final boolean DEBUG_SETTINGS = false;
348    static final boolean DEBUG_PREFERRED = false;
349    static final boolean DEBUG_UPGRADE = false;
350    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
351    private static final boolean DEBUG_BACKUP = false;
352    private static final boolean DEBUG_INSTALL = false;
353    private static final boolean DEBUG_REMOVE = false;
354    private static final boolean DEBUG_BROADCASTS = false;
355    private static final boolean DEBUG_SHOW_INFO = false;
356    private static final boolean DEBUG_PACKAGE_INFO = false;
357    private static final boolean DEBUG_INTENT_MATCHING = false;
358    private static final boolean DEBUG_PACKAGE_SCANNING = false;
359    private static final boolean DEBUG_VERIFY = false;
360    private static final boolean DEBUG_FILTERS = false;
361
362    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
363    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
364    // user, but by default initialize to this.
365    static final boolean DEBUG_DEXOPT = false;
366
367    private static final boolean DEBUG_ABI_SELECTION = false;
368    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
369    private static final boolean DEBUG_TRIAGED_MISSING = false;
370    private static final boolean DEBUG_APP_DATA = false;
371
372    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
373    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
374
375    private static final boolean DISABLE_EPHEMERAL_APPS = false;
376    private static final boolean HIDE_EPHEMERAL_APIS = true;
377
378    private static final int RADIO_UID = Process.PHONE_UID;
379    private static final int LOG_UID = Process.LOG_UID;
380    private static final int NFC_UID = Process.NFC_UID;
381    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
382    private static final int SHELL_UID = Process.SHELL_UID;
383
384    // Cap the size of permission trees that 3rd party apps can define
385    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
386
387    // Suffix used during package installation when copying/moving
388    // package apks to install directory.
389    private static final String INSTALL_PACKAGE_SUFFIX = "-";
390
391    static final int SCAN_NO_DEX = 1<<1;
392    static final int SCAN_FORCE_DEX = 1<<2;
393    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
394    static final int SCAN_NEW_INSTALL = 1<<4;
395    static final int SCAN_NO_PATHS = 1<<5;
396    static final int SCAN_UPDATE_TIME = 1<<6;
397    static final int SCAN_DEFER_DEX = 1<<7;
398    static final int SCAN_BOOTING = 1<<8;
399    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
400    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
401    static final int SCAN_REPLACING = 1<<11;
402    static final int SCAN_REQUIRE_KNOWN = 1<<12;
403    static final int SCAN_MOVE = 1<<13;
404    static final int SCAN_INITIAL = 1<<14;
405    static final int SCAN_CHECK_ONLY = 1<<15;
406    static final int SCAN_DONT_KILL_APP = 1<<17;
407    static final int SCAN_IGNORE_FROZEN = 1<<18;
408
409    static final int REMOVE_CHATTY = 1<<16;
410
411    private static final int[] EMPTY_INT_ARRAY = new int[0];
412
413    /**
414     * Timeout (in milliseconds) after which the watchdog should declare that
415     * our handler thread is wedged.  The usual default for such things is one
416     * minute but we sometimes do very lengthy I/O operations on this thread,
417     * such as installing multi-gigabyte applications, so ours needs to be longer.
418     */
419    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
420
421    /**
422     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
423     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
424     * settings entry if available, otherwise we use the hardcoded default.  If it's been
425     * more than this long since the last fstrim, we force one during the boot sequence.
426     *
427     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
428     * one gets run at the next available charging+idle time.  This final mandatory
429     * no-fstrim check kicks in only of the other scheduling criteria is never met.
430     */
431    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
432
433    /**
434     * Whether verification is enabled by default.
435     */
436    private static final boolean DEFAULT_VERIFY_ENABLE = true;
437
438    /**
439     * The default maximum time to wait for the verification agent to return in
440     * milliseconds.
441     */
442    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
443
444    /**
445     * The default response for package verification timeout.
446     *
447     * This can be either PackageManager.VERIFICATION_ALLOW or
448     * PackageManager.VERIFICATION_REJECT.
449     */
450    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
451
452    static final String PLATFORM_PACKAGE_NAME = "android";
453
454    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
455
456    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
457            DEFAULT_CONTAINER_PACKAGE,
458            "com.android.defcontainer.DefaultContainerService");
459
460    private static final String KILL_APP_REASON_GIDS_CHANGED =
461            "permission grant or revoke changed gids";
462
463    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
464            "permissions revoked";
465
466    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
467
468    private static final String PACKAGE_SCHEME = "package";
469
470    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
471    /**
472     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
473     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
474     * VENDOR_OVERLAY_DIR.
475     */
476    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
477    /**
478     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
479     * is in VENDOR_OVERLAY_THEME_PROPERTY.
480     */
481    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
482            = "persist.vendor.overlay.theme";
483
484    /** Permission grant: not grant the permission. */
485    private static final int GRANT_DENIED = 1;
486
487    /** Permission grant: grant the permission as an install permission. */
488    private static final int GRANT_INSTALL = 2;
489
490    /** Permission grant: grant the permission as a runtime one. */
491    private static final int GRANT_RUNTIME = 3;
492
493    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
494    private static final int GRANT_UPGRADE = 4;
495
496    /** Canonical intent used to identify what counts as a "web browser" app */
497    private static final Intent sBrowserIntent;
498    static {
499        sBrowserIntent = new Intent();
500        sBrowserIntent.setAction(Intent.ACTION_VIEW);
501        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
502        sBrowserIntent.setData(Uri.parse("http:"));
503    }
504
505    /**
506     * The set of all protected actions [i.e. those actions for which a high priority
507     * intent filter is disallowed].
508     */
509    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
510    static {
511        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
512        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
513        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
514        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
515    }
516
517    // Compilation reasons.
518    public static final int REASON_FIRST_BOOT = 0;
519    public static final int REASON_BOOT = 1;
520    public static final int REASON_INSTALL = 2;
521    public static final int REASON_BACKGROUND_DEXOPT = 3;
522    public static final int REASON_AB_OTA = 4;
523    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
524    public static final int REASON_SHARED_APK = 6;
525    public static final int REASON_FORCED_DEXOPT = 7;
526    public static final int REASON_CORE_APP = 8;
527
528    public static final int REASON_LAST = REASON_CORE_APP;
529
530    /** Special library name that skips shared libraries check during compilation. */
531    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
532
533    final ServiceThread mHandlerThread;
534
535    final PackageHandler mHandler;
536
537    private final ProcessLoggingHandler mProcessLoggingHandler;
538
539    /**
540     * Messages for {@link #mHandler} that need to wait for system ready before
541     * being dispatched.
542     */
543    private ArrayList<Message> mPostSystemReadyMessages;
544
545    final int mSdkVersion = Build.VERSION.SDK_INT;
546
547    final Context mContext;
548    final boolean mFactoryTest;
549    final boolean mOnlyCore;
550    final DisplayMetrics mMetrics;
551    final int mDefParseFlags;
552    final String[] mSeparateProcesses;
553    final boolean mIsUpgrade;
554    final boolean mIsPreNUpgrade;
555    final boolean mIsPreNMR1Upgrade;
556
557    @GuardedBy("mPackages")
558    private boolean mDexOptDialogShown;
559
560    /** The location for ASEC container files on internal storage. */
561    final String mAsecInternalPath;
562
563    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
564    // LOCK HELD.  Can be called with mInstallLock held.
565    @GuardedBy("mInstallLock")
566    final Installer mInstaller;
567
568    /** Directory where installed third-party apps stored */
569    final File mAppInstallDir;
570    final File mEphemeralInstallDir;
571
572    /**
573     * Directory to which applications installed internally have their
574     * 32 bit native libraries copied.
575     */
576    private File mAppLib32InstallDir;
577
578    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
579    // apps.
580    final File mDrmAppPrivateInstallDir;
581
582    // ----------------------------------------------------------------
583
584    // Lock for state used when installing and doing other long running
585    // operations.  Methods that must be called with this lock held have
586    // the suffix "LI".
587    final Object mInstallLock = new Object();
588
589    // ----------------------------------------------------------------
590
591    // Keys are String (package name), values are Package.  This also serves
592    // as the lock for the global state.  Methods that must be called with
593    // this lock held have the prefix "LP".
594    @GuardedBy("mPackages")
595    final ArrayMap<String, PackageParser.Package> mPackages =
596            new ArrayMap<String, PackageParser.Package>();
597
598    final ArrayMap<String, Set<String>> mKnownCodebase =
599            new ArrayMap<String, Set<String>>();
600
601    // Tracks available target package names -> overlay package paths.
602    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
603        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
604
605    /**
606     * Tracks new system packages [received in an OTA] that we expect to
607     * find updated user-installed versions. Keys are package name, values
608     * are package location.
609     */
610    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
611    /**
612     * Tracks high priority intent filters for protected actions. During boot, certain
613     * filter actions are protected and should never be allowed to have a high priority
614     * intent filter for them. However, there is one, and only one exception -- the
615     * setup wizard. It must be able to define a high priority intent filter for these
616     * actions to ensure there are no escapes from the wizard. We need to delay processing
617     * of these during boot as we need to look at all of the system packages in order
618     * to know which component is the setup wizard.
619     */
620    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
621    /**
622     * Whether or not processing protected filters should be deferred.
623     */
624    private boolean mDeferProtectedFilters = true;
625
626    /**
627     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
628     */
629    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
630    /**
631     * Whether or not system app permissions should be promoted from install to runtime.
632     */
633    boolean mPromoteSystemApps;
634
635    @GuardedBy("mPackages")
636    final Settings mSettings;
637
638    /**
639     * Set of package names that are currently "frozen", which means active
640     * surgery is being done on the code/data for that package. The platform
641     * will refuse to launch frozen packages to avoid race conditions.
642     *
643     * @see PackageFreezer
644     */
645    @GuardedBy("mPackages")
646    final ArraySet<String> mFrozenPackages = new ArraySet<>();
647
648    final ProtectedPackages mProtectedPackages;
649
650    boolean mFirstBoot;
651
652    // System configuration read by SystemConfig.
653    final int[] mGlobalGids;
654    final SparseArray<ArraySet<String>> mSystemPermissions;
655    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
656
657    // If mac_permissions.xml was found for seinfo labeling.
658    boolean mFoundPolicyFile;
659
660    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
661
662    public static final class SharedLibraryEntry {
663        public final String path;
664        public final String apk;
665
666        SharedLibraryEntry(String _path, String _apk) {
667            path = _path;
668            apk = _apk;
669        }
670    }
671
672    // Currently known shared libraries.
673    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
674            new ArrayMap<String, SharedLibraryEntry>();
675
676    // All available activities, for your resolving pleasure.
677    final ActivityIntentResolver mActivities =
678            new ActivityIntentResolver();
679
680    // All available receivers, for your resolving pleasure.
681    final ActivityIntentResolver mReceivers =
682            new ActivityIntentResolver();
683
684    // All available services, for your resolving pleasure.
685    final ServiceIntentResolver mServices = new ServiceIntentResolver();
686
687    // All available providers, for your resolving pleasure.
688    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
689
690    // Mapping from provider base names (first directory in content URI codePath)
691    // to the provider information.
692    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
693            new ArrayMap<String, PackageParser.Provider>();
694
695    // Mapping from instrumentation class names to info about them.
696    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
697            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
698
699    // Mapping from permission names to info about them.
700    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
701            new ArrayMap<String, PackageParser.PermissionGroup>();
702
703    // Packages whose data we have transfered into another package, thus
704    // should no longer exist.
705    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
706
707    // Broadcast actions that are only available to the system.
708    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
709
710    /** List of packages waiting for verification. */
711    final SparseArray<PackageVerificationState> mPendingVerification
712            = new SparseArray<PackageVerificationState>();
713
714    /** Set of packages associated with each app op permission. */
715    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
716
717    final PackageInstallerService mInstallerService;
718
719    private final PackageDexOptimizer mPackageDexOptimizer;
720
721    private AtomicInteger mNextMoveId = new AtomicInteger();
722    private final MoveCallbacks mMoveCallbacks;
723
724    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
725
726    // Cache of users who need badging.
727    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
728
729    /** Token for keys in mPendingVerification. */
730    private int mPendingVerificationToken = 0;
731
732    volatile boolean mSystemReady;
733    volatile boolean mSafeMode;
734    volatile boolean mHasSystemUidErrors;
735
736    ApplicationInfo mAndroidApplication;
737    final ActivityInfo mResolveActivity = new ActivityInfo();
738    final ResolveInfo mResolveInfo = new ResolveInfo();
739    ComponentName mResolveComponentName;
740    PackageParser.Package mPlatformPackage;
741    ComponentName mCustomResolverComponentName;
742
743    boolean mResolverReplaced = false;
744
745    private final @Nullable ComponentName mIntentFilterVerifierComponent;
746    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
747
748    private int mIntentFilterVerificationToken = 0;
749
750    /** Component that knows whether or not an ephemeral application exists */
751    final ComponentName mEphemeralResolverComponent;
752    /** The service connection to the ephemeral resolver */
753    final EphemeralResolverConnection mEphemeralResolverConnection;
754
755    /** Component used to install ephemeral applications */
756    final ComponentName mEphemeralInstallerComponent;
757    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
758    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
759
760    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
761            = new SparseArray<IntentFilterVerificationState>();
762
763    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
764
765    // List of packages names to keep cached, even if they are uninstalled for all users
766    private List<String> mKeepUninstalledPackages;
767
768    private UserManagerInternal mUserManagerInternal;
769
770    private static class IFVerificationParams {
771        PackageParser.Package pkg;
772        boolean replacing;
773        int userId;
774        int verifierUid;
775
776        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
777                int _userId, int _verifierUid) {
778            pkg = _pkg;
779            replacing = _replacing;
780            userId = _userId;
781            replacing = _replacing;
782            verifierUid = _verifierUid;
783        }
784    }
785
786    private interface IntentFilterVerifier<T extends IntentFilter> {
787        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
788                                               T filter, String packageName);
789        void startVerifications(int userId);
790        void receiveVerificationResponse(int verificationId);
791    }
792
793    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
794        private Context mContext;
795        private ComponentName mIntentFilterVerifierComponent;
796        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
797
798        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
799            mContext = context;
800            mIntentFilterVerifierComponent = verifierComponent;
801        }
802
803        private String getDefaultScheme() {
804            return IntentFilter.SCHEME_HTTPS;
805        }
806
807        @Override
808        public void startVerifications(int userId) {
809            // Launch verifications requests
810            int count = mCurrentIntentFilterVerifications.size();
811            for (int n=0; n<count; n++) {
812                int verificationId = mCurrentIntentFilterVerifications.get(n);
813                final IntentFilterVerificationState ivs =
814                        mIntentFilterVerificationStates.get(verificationId);
815
816                String packageName = ivs.getPackageName();
817
818                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
819                final int filterCount = filters.size();
820                ArraySet<String> domainsSet = new ArraySet<>();
821                for (int m=0; m<filterCount; m++) {
822                    PackageParser.ActivityIntentInfo filter = filters.get(m);
823                    domainsSet.addAll(filter.getHostsList());
824                }
825                synchronized (mPackages) {
826                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
827                            packageName, domainsSet) != null) {
828                        scheduleWriteSettingsLocked();
829                    }
830                }
831                sendVerificationRequest(userId, verificationId, ivs);
832            }
833            mCurrentIntentFilterVerifications.clear();
834        }
835
836        private void sendVerificationRequest(int userId, int verificationId,
837                IntentFilterVerificationState ivs) {
838
839            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
840            verificationIntent.putExtra(
841                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
842                    verificationId);
843            verificationIntent.putExtra(
844                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
845                    getDefaultScheme());
846            verificationIntent.putExtra(
847                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
848                    ivs.getHostsString());
849            verificationIntent.putExtra(
850                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
851                    ivs.getPackageName());
852            verificationIntent.setComponent(mIntentFilterVerifierComponent);
853            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
854
855            UserHandle user = new UserHandle(userId);
856            mContext.sendBroadcastAsUser(verificationIntent, user);
857            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
858                    "Sending IntentFilter verification broadcast");
859        }
860
861        public void receiveVerificationResponse(int verificationId) {
862            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
863
864            final boolean verified = ivs.isVerified();
865
866            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
867            final int count = filters.size();
868            if (DEBUG_DOMAIN_VERIFICATION) {
869                Slog.i(TAG, "Received verification response " + verificationId
870                        + " for " + count + " filters, verified=" + verified);
871            }
872            for (int n=0; n<count; n++) {
873                PackageParser.ActivityIntentInfo filter = filters.get(n);
874                filter.setVerified(verified);
875
876                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
877                        + " verified with result:" + verified + " and hosts:"
878                        + ivs.getHostsString());
879            }
880
881            mIntentFilterVerificationStates.remove(verificationId);
882
883            final String packageName = ivs.getPackageName();
884            IntentFilterVerificationInfo ivi = null;
885
886            synchronized (mPackages) {
887                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
888            }
889            if (ivi == null) {
890                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
891                        + verificationId + " packageName:" + packageName);
892                return;
893            }
894            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
895                    "Updating IntentFilterVerificationInfo for package " + packageName
896                            +" verificationId:" + verificationId);
897
898            synchronized (mPackages) {
899                if (verified) {
900                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
901                } else {
902                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
903                }
904                scheduleWriteSettingsLocked();
905
906                final int userId = ivs.getUserId();
907                if (userId != UserHandle.USER_ALL) {
908                    final int userStatus =
909                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
910
911                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
912                    boolean needUpdate = false;
913
914                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
915                    // already been set by the User thru the Disambiguation dialog
916                    switch (userStatus) {
917                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
918                            if (verified) {
919                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
920                            } else {
921                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
922                            }
923                            needUpdate = true;
924                            break;
925
926                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
927                            if (verified) {
928                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
929                                needUpdate = true;
930                            }
931                            break;
932
933                        default:
934                            // Nothing to do
935                    }
936
937                    if (needUpdate) {
938                        mSettings.updateIntentFilterVerificationStatusLPw(
939                                packageName, updatedStatus, userId);
940                        scheduleWritePackageRestrictionsLocked(userId);
941                    }
942                }
943            }
944        }
945
946        @Override
947        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
948                    ActivityIntentInfo filter, String packageName) {
949            if (!hasValidDomains(filter)) {
950                return false;
951            }
952            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
953            if (ivs == null) {
954                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
955                        packageName);
956            }
957            if (DEBUG_DOMAIN_VERIFICATION) {
958                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
959            }
960            ivs.addFilter(filter);
961            return true;
962        }
963
964        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
965                int userId, int verificationId, String packageName) {
966            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
967                    verifierUid, userId, packageName);
968            ivs.setPendingState();
969            synchronized (mPackages) {
970                mIntentFilterVerificationStates.append(verificationId, ivs);
971                mCurrentIntentFilterVerifications.add(verificationId);
972            }
973            return ivs;
974        }
975    }
976
977    private static boolean hasValidDomains(ActivityIntentInfo filter) {
978        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
979                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
980                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
981    }
982
983    // Set of pending broadcasts for aggregating enable/disable of components.
984    static class PendingPackageBroadcasts {
985        // for each user id, a map of <package name -> components within that package>
986        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
987
988        public PendingPackageBroadcasts() {
989            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
990        }
991
992        public ArrayList<String> get(int userId, String packageName) {
993            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
994            return packages.get(packageName);
995        }
996
997        public void put(int userId, String packageName, ArrayList<String> components) {
998            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
999            packages.put(packageName, components);
1000        }
1001
1002        public void remove(int userId, String packageName) {
1003            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1004            if (packages != null) {
1005                packages.remove(packageName);
1006            }
1007        }
1008
1009        public void remove(int userId) {
1010            mUidMap.remove(userId);
1011        }
1012
1013        public int userIdCount() {
1014            return mUidMap.size();
1015        }
1016
1017        public int userIdAt(int n) {
1018            return mUidMap.keyAt(n);
1019        }
1020
1021        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1022            return mUidMap.get(userId);
1023        }
1024
1025        public int size() {
1026            // total number of pending broadcast entries across all userIds
1027            int num = 0;
1028            for (int i = 0; i< mUidMap.size(); i++) {
1029                num += mUidMap.valueAt(i).size();
1030            }
1031            return num;
1032        }
1033
1034        public void clear() {
1035            mUidMap.clear();
1036        }
1037
1038        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1039            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1040            if (map == null) {
1041                map = new ArrayMap<String, ArrayList<String>>();
1042                mUidMap.put(userId, map);
1043            }
1044            return map;
1045        }
1046    }
1047    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1048
1049    // Service Connection to remote media container service to copy
1050    // package uri's from external media onto secure containers
1051    // or internal storage.
1052    private IMediaContainerService mContainerService = null;
1053
1054    static final int SEND_PENDING_BROADCAST = 1;
1055    static final int MCS_BOUND = 3;
1056    static final int END_COPY = 4;
1057    static final int INIT_COPY = 5;
1058    static final int MCS_UNBIND = 6;
1059    static final int START_CLEANING_PACKAGE = 7;
1060    static final int FIND_INSTALL_LOC = 8;
1061    static final int POST_INSTALL = 9;
1062    static final int MCS_RECONNECT = 10;
1063    static final int MCS_GIVE_UP = 11;
1064    static final int UPDATED_MEDIA_STATUS = 12;
1065    static final int WRITE_SETTINGS = 13;
1066    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1067    static final int PACKAGE_VERIFIED = 15;
1068    static final int CHECK_PENDING_VERIFICATION = 16;
1069    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1070    static final int INTENT_FILTER_VERIFIED = 18;
1071    static final int WRITE_PACKAGE_LIST = 19;
1072
1073    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1074
1075    // Delay time in millisecs
1076    static final int BROADCAST_DELAY = 10 * 1000;
1077
1078    static UserManagerService sUserManager;
1079
1080    // Stores a list of users whose package restrictions file needs to be updated
1081    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1082
1083    final private DefaultContainerConnection mDefContainerConn =
1084            new DefaultContainerConnection();
1085    class DefaultContainerConnection implements ServiceConnection {
1086        public void onServiceConnected(ComponentName name, IBinder service) {
1087            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1088            final IMediaContainerService imcs = IMediaContainerService.Stub
1089                    .asInterface(Binder.allowBlocking(service));
1090            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1091        }
1092
1093        public void onServiceDisconnected(ComponentName name) {
1094            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1095        }
1096    }
1097
1098    // Recordkeeping of restore-after-install operations that are currently in flight
1099    // between the Package Manager and the Backup Manager
1100    static class PostInstallData {
1101        public InstallArgs args;
1102        public PackageInstalledInfo res;
1103
1104        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1105            args = _a;
1106            res = _r;
1107        }
1108    }
1109
1110    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1111    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1112
1113    // XML tags for backup/restore of various bits of state
1114    private static final String TAG_PREFERRED_BACKUP = "pa";
1115    private static final String TAG_DEFAULT_APPS = "da";
1116    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1117
1118    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1119    private static final String TAG_ALL_GRANTS = "rt-grants";
1120    private static final String TAG_GRANT = "grant";
1121    private static final String ATTR_PACKAGE_NAME = "pkg";
1122
1123    private static final String TAG_PERMISSION = "perm";
1124    private static final String ATTR_PERMISSION_NAME = "name";
1125    private static final String ATTR_IS_GRANTED = "g";
1126    private static final String ATTR_USER_SET = "set";
1127    private static final String ATTR_USER_FIXED = "fixed";
1128    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1129
1130    // System/policy permission grants are not backed up
1131    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1132            FLAG_PERMISSION_POLICY_FIXED
1133            | FLAG_PERMISSION_SYSTEM_FIXED
1134            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1135
1136    // And we back up these user-adjusted states
1137    private static final int USER_RUNTIME_GRANT_MASK =
1138            FLAG_PERMISSION_USER_SET
1139            | FLAG_PERMISSION_USER_FIXED
1140            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1141
1142    final @Nullable String mRequiredVerifierPackage;
1143    final @NonNull String mRequiredInstallerPackage;
1144    final @NonNull String mRequiredUninstallerPackage;
1145    final @Nullable String mSetupWizardPackage;
1146    final @Nullable String mStorageManagerPackage;
1147    final @NonNull String mServicesSystemSharedLibraryPackageName;
1148    final @NonNull String mSharedSystemSharedLibraryPackageName;
1149
1150    final boolean mPermissionReviewRequired;
1151
1152    private final PackageUsage mPackageUsage = new PackageUsage();
1153    private final CompilerStats mCompilerStats = new CompilerStats();
1154
1155    class PackageHandler extends Handler {
1156        private boolean mBound = false;
1157        final ArrayList<HandlerParams> mPendingInstalls =
1158            new ArrayList<HandlerParams>();
1159
1160        private boolean connectToService() {
1161            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1162                    " DefaultContainerService");
1163            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1164            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1165            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1166                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1167                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1168                mBound = true;
1169                return true;
1170            }
1171            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1172            return false;
1173        }
1174
1175        private void disconnectService() {
1176            mContainerService = null;
1177            mBound = false;
1178            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1179            mContext.unbindService(mDefContainerConn);
1180            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1181        }
1182
1183        PackageHandler(Looper looper) {
1184            super(looper);
1185        }
1186
1187        public void handleMessage(Message msg) {
1188            try {
1189                doHandleMessage(msg);
1190            } finally {
1191                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1192            }
1193        }
1194
1195        void doHandleMessage(Message msg) {
1196            switch (msg.what) {
1197                case INIT_COPY: {
1198                    HandlerParams params = (HandlerParams) msg.obj;
1199                    int idx = mPendingInstalls.size();
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1201                    // If a bind was already initiated we dont really
1202                    // need to do anything. The pending install
1203                    // will be processed later on.
1204                    if (!mBound) {
1205                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1206                                System.identityHashCode(mHandler));
1207                        // If this is the only one pending we might
1208                        // have to bind to the service again.
1209                        if (!connectToService()) {
1210                            Slog.e(TAG, "Failed to bind to media container service");
1211                            params.serviceError();
1212                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1213                                    System.identityHashCode(mHandler));
1214                            if (params.traceMethod != null) {
1215                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1216                                        params.traceCookie);
1217                            }
1218                            return;
1219                        } else {
1220                            // Once we bind to the service, the first
1221                            // pending request will be processed.
1222                            mPendingInstalls.add(idx, params);
1223                        }
1224                    } else {
1225                        mPendingInstalls.add(idx, params);
1226                        // Already bound to the service. Just make
1227                        // sure we trigger off processing the first request.
1228                        if (idx == 0) {
1229                            mHandler.sendEmptyMessage(MCS_BOUND);
1230                        }
1231                    }
1232                    break;
1233                }
1234                case MCS_BOUND: {
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1236                    if (msg.obj != null) {
1237                        mContainerService = (IMediaContainerService) msg.obj;
1238                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1239                                System.identityHashCode(mHandler));
1240                    }
1241                    if (mContainerService == null) {
1242                        if (!mBound) {
1243                            // Something seriously wrong since we are not bound and we are not
1244                            // waiting for connection. Bail out.
1245                            Slog.e(TAG, "Cannot bind to media container service");
1246                            for (HandlerParams params : mPendingInstalls) {
1247                                // Indicate service bind error
1248                                params.serviceError();
1249                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1250                                        System.identityHashCode(params));
1251                                if (params.traceMethod != null) {
1252                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1253                                            params.traceMethod, params.traceCookie);
1254                                }
1255                                return;
1256                            }
1257                            mPendingInstalls.clear();
1258                        } else {
1259                            Slog.w(TAG, "Waiting to connect to media container service");
1260                        }
1261                    } else if (mPendingInstalls.size() > 0) {
1262                        HandlerParams params = mPendingInstalls.get(0);
1263                        if (params != null) {
1264                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1265                                    System.identityHashCode(params));
1266                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1267                            if (params.startCopy()) {
1268                                // We are done...  look for more work or to
1269                                // go idle.
1270                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1271                                        "Checking for more work or unbind...");
1272                                // Delete pending install
1273                                if (mPendingInstalls.size() > 0) {
1274                                    mPendingInstalls.remove(0);
1275                                }
1276                                if (mPendingInstalls.size() == 0) {
1277                                    if (mBound) {
1278                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1279                                                "Posting delayed MCS_UNBIND");
1280                                        removeMessages(MCS_UNBIND);
1281                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1282                                        // Unbind after a little delay, to avoid
1283                                        // continual thrashing.
1284                                        sendMessageDelayed(ubmsg, 10000);
1285                                    }
1286                                } else {
1287                                    // There are more pending requests in queue.
1288                                    // Just post MCS_BOUND message to trigger processing
1289                                    // of next pending install.
1290                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1291                                            "Posting MCS_BOUND for next work");
1292                                    mHandler.sendEmptyMessage(MCS_BOUND);
1293                                }
1294                            }
1295                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1296                        }
1297                    } else {
1298                        // Should never happen ideally.
1299                        Slog.w(TAG, "Empty queue");
1300                    }
1301                    break;
1302                }
1303                case MCS_RECONNECT: {
1304                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1305                    if (mPendingInstalls.size() > 0) {
1306                        if (mBound) {
1307                            disconnectService();
1308                        }
1309                        if (!connectToService()) {
1310                            Slog.e(TAG, "Failed to bind to media container service");
1311                            for (HandlerParams params : mPendingInstalls) {
1312                                // Indicate service bind error
1313                                params.serviceError();
1314                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1315                                        System.identityHashCode(params));
1316                            }
1317                            mPendingInstalls.clear();
1318                        }
1319                    }
1320                    break;
1321                }
1322                case MCS_UNBIND: {
1323                    // If there is no actual work left, then time to unbind.
1324                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1325
1326                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1327                        if (mBound) {
1328                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1329
1330                            disconnectService();
1331                        }
1332                    } else if (mPendingInstalls.size() > 0) {
1333                        // There are more pending requests in queue.
1334                        // Just post MCS_BOUND message to trigger processing
1335                        // of next pending install.
1336                        mHandler.sendEmptyMessage(MCS_BOUND);
1337                    }
1338
1339                    break;
1340                }
1341                case MCS_GIVE_UP: {
1342                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1343                    HandlerParams params = mPendingInstalls.remove(0);
1344                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1345                            System.identityHashCode(params));
1346                    break;
1347                }
1348                case SEND_PENDING_BROADCAST: {
1349                    String packages[];
1350                    ArrayList<String> components[];
1351                    int size = 0;
1352                    int uids[];
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    synchronized (mPackages) {
1355                        if (mPendingBroadcasts == null) {
1356                            return;
1357                        }
1358                        size = mPendingBroadcasts.size();
1359                        if (size <= 0) {
1360                            // Nothing to be done. Just return
1361                            return;
1362                        }
1363                        packages = new String[size];
1364                        components = new ArrayList[size];
1365                        uids = new int[size];
1366                        int i = 0;  // filling out the above arrays
1367
1368                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1369                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1370                            Iterator<Map.Entry<String, ArrayList<String>>> it
1371                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1372                                            .entrySet().iterator();
1373                            while (it.hasNext() && i < size) {
1374                                Map.Entry<String, ArrayList<String>> ent = it.next();
1375                                packages[i] = ent.getKey();
1376                                components[i] = ent.getValue();
1377                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1378                                uids[i] = (ps != null)
1379                                        ? UserHandle.getUid(packageUserId, ps.appId)
1380                                        : -1;
1381                                i++;
1382                            }
1383                        }
1384                        size = i;
1385                        mPendingBroadcasts.clear();
1386                    }
1387                    // Send broadcasts
1388                    for (int i = 0; i < size; i++) {
1389                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1390                    }
1391                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1392                    break;
1393                }
1394                case START_CLEANING_PACKAGE: {
1395                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1396                    final String packageName = (String)msg.obj;
1397                    final int userId = msg.arg1;
1398                    final boolean andCode = msg.arg2 != 0;
1399                    synchronized (mPackages) {
1400                        if (userId == UserHandle.USER_ALL) {
1401                            int[] users = sUserManager.getUserIds();
1402                            for (int user : users) {
1403                                mSettings.addPackageToCleanLPw(
1404                                        new PackageCleanItem(user, packageName, andCode));
1405                            }
1406                        } else {
1407                            mSettings.addPackageToCleanLPw(
1408                                    new PackageCleanItem(userId, packageName, andCode));
1409                        }
1410                    }
1411                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                    startCleaningPackages();
1413                } break;
1414                case POST_INSTALL: {
1415                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1416
1417                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1418                    final boolean didRestore = (msg.arg2 != 0);
1419                    mRunningInstalls.delete(msg.arg1);
1420
1421                    if (data != null) {
1422                        InstallArgs args = data.args;
1423                        PackageInstalledInfo parentRes = data.res;
1424
1425                        final boolean grantPermissions = (args.installFlags
1426                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1427                        final boolean killApp = (args.installFlags
1428                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1429                        final String[] grantedPermissions = args.installGrantPermissions;
1430
1431                        // Handle the parent package
1432                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1433                                grantedPermissions, didRestore, args.installerPackageName,
1434                                args.observer);
1435
1436                        // Handle the child packages
1437                        final int childCount = (parentRes.addedChildPackages != null)
1438                                ? parentRes.addedChildPackages.size() : 0;
1439                        for (int i = 0; i < childCount; i++) {
1440                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1441                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1442                                    grantedPermissions, false, args.installerPackageName,
1443                                    args.observer);
1444                        }
1445
1446                        // Log tracing if needed
1447                        if (args.traceMethod != null) {
1448                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1449                                    args.traceCookie);
1450                        }
1451                    } else {
1452                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1453                    }
1454
1455                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1456                } break;
1457                case UPDATED_MEDIA_STATUS: {
1458                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1459                    boolean reportStatus = msg.arg1 == 1;
1460                    boolean doGc = msg.arg2 == 1;
1461                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1462                    if (doGc) {
1463                        // Force a gc to clear up stale containers.
1464                        Runtime.getRuntime().gc();
1465                    }
1466                    if (msg.obj != null) {
1467                        @SuppressWarnings("unchecked")
1468                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1469                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1470                        // Unload containers
1471                        unloadAllContainers(args);
1472                    }
1473                    if (reportStatus) {
1474                        try {
1475                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1476                            PackageHelper.getMountService().finishMediaUpdate();
1477                        } catch (RemoteException e) {
1478                            Log.e(TAG, "MountService not running?");
1479                        }
1480                    }
1481                } break;
1482                case WRITE_SETTINGS: {
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1484                    synchronized (mPackages) {
1485                        removeMessages(WRITE_SETTINGS);
1486                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1487                        mSettings.writeLPr();
1488                        mDirtyUsers.clear();
1489                    }
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1491                } break;
1492                case WRITE_PACKAGE_RESTRICTIONS: {
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1494                    synchronized (mPackages) {
1495                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1496                        for (int userId : mDirtyUsers) {
1497                            mSettings.writePackageRestrictionsLPr(userId);
1498                        }
1499                        mDirtyUsers.clear();
1500                    }
1501                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1502                } break;
1503                case WRITE_PACKAGE_LIST: {
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1505                    synchronized (mPackages) {
1506                        removeMessages(WRITE_PACKAGE_LIST);
1507                        mSettings.writePackageListLPr(msg.arg1);
1508                    }
1509                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1510                } break;
1511                case CHECK_PENDING_VERIFICATION: {
1512                    final int verificationId = msg.arg1;
1513                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1514
1515                    if ((state != null) && !state.timeoutExtended()) {
1516                        final InstallArgs args = state.getInstallArgs();
1517                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1518
1519                        Slog.i(TAG, "Verification timed out for " + originUri);
1520                        mPendingVerification.remove(verificationId);
1521
1522                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1523
1524                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1525                            Slog.i(TAG, "Continuing with installation of " + originUri);
1526                            state.setVerifierResponse(Binder.getCallingUid(),
1527                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1528                            broadcastPackageVerified(verificationId, originUri,
1529                                    PackageManager.VERIFICATION_ALLOW,
1530                                    state.getInstallArgs().getUser());
1531                            try {
1532                                ret = args.copyApk(mContainerService, true);
1533                            } catch (RemoteException e) {
1534                                Slog.e(TAG, "Could not contact the ContainerService");
1535                            }
1536                        } else {
1537                            broadcastPackageVerified(verificationId, originUri,
1538                                    PackageManager.VERIFICATION_REJECT,
1539                                    state.getInstallArgs().getUser());
1540                        }
1541
1542                        Trace.asyncTraceEnd(
1543                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1544
1545                        processPendingInstall(args, ret);
1546                        mHandler.sendEmptyMessage(MCS_UNBIND);
1547                    }
1548                    break;
1549                }
1550                case PACKAGE_VERIFIED: {
1551                    final int verificationId = msg.arg1;
1552
1553                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1554                    if (state == null) {
1555                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1556                        break;
1557                    }
1558
1559                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1560
1561                    state.setVerifierResponse(response.callerUid, response.code);
1562
1563                    if (state.isVerificationComplete()) {
1564                        mPendingVerification.remove(verificationId);
1565
1566                        final InstallArgs args = state.getInstallArgs();
1567                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1568
1569                        int ret;
1570                        if (state.isInstallAllowed()) {
1571                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1572                            broadcastPackageVerified(verificationId, originUri,
1573                                    response.code, state.getInstallArgs().getUser());
1574                            try {
1575                                ret = args.copyApk(mContainerService, true);
1576                            } catch (RemoteException e) {
1577                                Slog.e(TAG, "Could not contact the ContainerService");
1578                            }
1579                        } else {
1580                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1581                        }
1582
1583                        Trace.asyncTraceEnd(
1584                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1585
1586                        processPendingInstall(args, ret);
1587                        mHandler.sendEmptyMessage(MCS_UNBIND);
1588                    }
1589
1590                    break;
1591                }
1592                case START_INTENT_FILTER_VERIFICATIONS: {
1593                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1594                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1595                            params.replacing, params.pkg);
1596                    break;
1597                }
1598                case INTENT_FILTER_VERIFIED: {
1599                    final int verificationId = msg.arg1;
1600
1601                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1602                            verificationId);
1603                    if (state == null) {
1604                        Slog.w(TAG, "Invalid IntentFilter verification token "
1605                                + verificationId + " received");
1606                        break;
1607                    }
1608
1609                    final int userId = state.getUserId();
1610
1611                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                            "Processing IntentFilter verification with token:"
1613                            + verificationId + " and userId:" + userId);
1614
1615                    final IntentFilterVerificationResponse response =
1616                            (IntentFilterVerificationResponse) msg.obj;
1617
1618                    state.setVerifierResponse(response.callerUid, response.code);
1619
1620                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1621                            "IntentFilter verification with token:" + verificationId
1622                            + " and userId:" + userId
1623                            + " is settings verifier response with response code:"
1624                            + response.code);
1625
1626                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1627                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1628                                + response.getFailedDomainsString());
1629                    }
1630
1631                    if (state.isVerificationComplete()) {
1632                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1633                    } else {
1634                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1635                                "IntentFilter verification with token:" + verificationId
1636                                + " was not said to be complete");
1637                    }
1638
1639                    break;
1640                }
1641            }
1642        }
1643    }
1644
1645    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1646            boolean killApp, String[] grantedPermissions,
1647            boolean launchedForRestore, String installerPackage,
1648            IPackageInstallObserver2 installObserver) {
1649        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1650            // Send the removed broadcasts
1651            if (res.removedInfo != null) {
1652                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1653            }
1654
1655            // Now that we successfully installed the package, grant runtime
1656            // permissions if requested before broadcasting the install.
1657            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1658                    >= Build.VERSION_CODES.M) {
1659                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1660            }
1661
1662            final boolean update = res.removedInfo != null
1663                    && res.removedInfo.removedPackage != null;
1664
1665            // If this is the first time we have child packages for a disabled privileged
1666            // app that had no children, we grant requested runtime permissions to the new
1667            // children if the parent on the system image had them already granted.
1668            if (res.pkg.parentPackage != null) {
1669                synchronized (mPackages) {
1670                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1671                }
1672            }
1673
1674            synchronized (mPackages) {
1675                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1676            }
1677
1678            final String packageName = res.pkg.applicationInfo.packageName;
1679
1680            // Determine the set of users who are adding this package for
1681            // the first time vs. those who are seeing an update.
1682            int[] firstUsers = EMPTY_INT_ARRAY;
1683            int[] updateUsers = EMPTY_INT_ARRAY;
1684            if (res.origUsers == null || res.origUsers.length == 0) {
1685                firstUsers = res.newUsers;
1686            } else {
1687                for (int newUser : res.newUsers) {
1688                    boolean isNew = true;
1689                    for (int origUser : res.origUsers) {
1690                        if (origUser == newUser) {
1691                            isNew = false;
1692                            break;
1693                        }
1694                    }
1695                    if (isNew) {
1696                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1697                    } else {
1698                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1699                    }
1700                }
1701            }
1702
1703            // Send installed broadcasts if the install/update is not ephemeral
1704            if (!isEphemeral(res.pkg)) {
1705                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1706
1707                // Send added for users that see the package for the first time
1708                // sendPackageAddedForNewUsers also deals with system apps
1709                int appId = UserHandle.getAppId(res.uid);
1710                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1711                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1712
1713                // Send added for users that don't see the package for the first time
1714                Bundle extras = new Bundle(1);
1715                extras.putInt(Intent.EXTRA_UID, res.uid);
1716                if (update) {
1717                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1718                }
1719                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1720                        extras, 0 /*flags*/, null /*targetPackage*/,
1721                        null /*finishedReceiver*/, updateUsers);
1722
1723                // Send replaced for users that don't see the package for the first time
1724                if (update) {
1725                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1726                            packageName, extras, 0 /*flags*/,
1727                            null /*targetPackage*/, null /*finishedReceiver*/,
1728                            updateUsers);
1729                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1730                            null /*package*/, null /*extras*/, 0 /*flags*/,
1731                            packageName /*targetPackage*/,
1732                            null /*finishedReceiver*/, updateUsers);
1733                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1734                    // First-install and we did a restore, so we're responsible for the
1735                    // first-launch broadcast.
1736                    if (DEBUG_BACKUP) {
1737                        Slog.i(TAG, "Post-restore of " + packageName
1738                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1739                    }
1740                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1741                }
1742
1743                // Send broadcast package appeared if forward locked/external for all users
1744                // treat asec-hosted packages like removable media on upgrade
1745                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1746                    if (DEBUG_INSTALL) {
1747                        Slog.i(TAG, "upgrading pkg " + res.pkg
1748                                + " is ASEC-hosted -> AVAILABLE");
1749                    }
1750                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1751                    ArrayList<String> pkgList = new ArrayList<>(1);
1752                    pkgList.add(packageName);
1753                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1754                }
1755            }
1756
1757            // Work that needs to happen on first install within each user
1758            if (firstUsers != null && firstUsers.length > 0) {
1759                synchronized (mPackages) {
1760                    for (int userId : firstUsers) {
1761                        // If this app is a browser and it's newly-installed for some
1762                        // users, clear any default-browser state in those users. The
1763                        // app's nature doesn't depend on the user, so we can just check
1764                        // its browser nature in any user and generalize.
1765                        if (packageIsBrowser(packageName, userId)) {
1766                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1767                        }
1768
1769                        // We may also need to apply pending (restored) runtime
1770                        // permission grants within these users.
1771                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1772                    }
1773                }
1774            }
1775
1776            // Log current value of "unknown sources" setting
1777            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1778                    getUnknownSourcesSettings());
1779
1780            // Force a gc to clear up things
1781            Runtime.getRuntime().gc();
1782
1783            // Remove the replaced package's older resources safely now
1784            // We delete after a gc for applications  on sdcard.
1785            if (res.removedInfo != null && res.removedInfo.args != null) {
1786                synchronized (mInstallLock) {
1787                    res.removedInfo.args.doPostDeleteLI(true);
1788                }
1789            }
1790        }
1791
1792        // If someone is watching installs - notify them
1793        if (installObserver != null) {
1794            try {
1795                Bundle extras = extrasForInstallResult(res);
1796                installObserver.onPackageInstalled(res.name, res.returnCode,
1797                        res.returnMsg, extras);
1798            } catch (RemoteException e) {
1799                Slog.i(TAG, "Observer no longer exists.");
1800            }
1801        }
1802    }
1803
1804    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1805            PackageParser.Package pkg) {
1806        if (pkg.parentPackage == null) {
1807            return;
1808        }
1809        if (pkg.requestedPermissions == null) {
1810            return;
1811        }
1812        final PackageSetting disabledSysParentPs = mSettings
1813                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1814        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1815                || !disabledSysParentPs.isPrivileged()
1816                || (disabledSysParentPs.childPackageNames != null
1817                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1818            return;
1819        }
1820        final int[] allUserIds = sUserManager.getUserIds();
1821        final int permCount = pkg.requestedPermissions.size();
1822        for (int i = 0; i < permCount; i++) {
1823            String permission = pkg.requestedPermissions.get(i);
1824            BasePermission bp = mSettings.mPermissions.get(permission);
1825            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1826                continue;
1827            }
1828            for (int userId : allUserIds) {
1829                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1830                        permission, userId)) {
1831                    grantRuntimePermission(pkg.packageName, permission, userId);
1832                }
1833            }
1834        }
1835    }
1836
1837    private StorageEventListener mStorageListener = new StorageEventListener() {
1838        @Override
1839        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1840            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1841                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1842                    final String volumeUuid = vol.getFsUuid();
1843
1844                    // Clean up any users or apps that were removed or recreated
1845                    // while this volume was missing
1846                    reconcileUsers(volumeUuid);
1847                    reconcileApps(volumeUuid);
1848
1849                    // Clean up any install sessions that expired or were
1850                    // cancelled while this volume was missing
1851                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1852
1853                    loadPrivatePackages(vol);
1854
1855                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1856                    unloadPrivatePackages(vol);
1857                }
1858            }
1859
1860            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1861                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1862                    updateExternalMediaStatus(true, false);
1863                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1864                    updateExternalMediaStatus(false, false);
1865                }
1866            }
1867        }
1868
1869        @Override
1870        public void onVolumeForgotten(String fsUuid) {
1871            if (TextUtils.isEmpty(fsUuid)) {
1872                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1873                return;
1874            }
1875
1876            // Remove any apps installed on the forgotten volume
1877            synchronized (mPackages) {
1878                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1879                for (PackageSetting ps : packages) {
1880                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1881                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1882                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1883                }
1884
1885                mSettings.onVolumeForgotten(fsUuid);
1886                mSettings.writeLPr();
1887            }
1888        }
1889    };
1890
1891    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1892            String[] grantedPermissions) {
1893        for (int userId : userIds) {
1894            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1895        }
1896
1897        // We could have touched GID membership, so flush out packages.list
1898        synchronized (mPackages) {
1899            mSettings.writePackageListLPr();
1900        }
1901    }
1902
1903    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1904            String[] grantedPermissions) {
1905        SettingBase sb = (SettingBase) pkg.mExtras;
1906        if (sb == null) {
1907            return;
1908        }
1909
1910        PermissionsState permissionsState = sb.getPermissionsState();
1911
1912        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1913                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1914
1915        for (String permission : pkg.requestedPermissions) {
1916            final BasePermission bp;
1917            synchronized (mPackages) {
1918                bp = mSettings.mPermissions.get(permission);
1919            }
1920            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1921                    && (grantedPermissions == null
1922                           || ArrayUtils.contains(grantedPermissions, permission))) {
1923                final int flags = permissionsState.getPermissionFlags(permission, userId);
1924                // Installer cannot change immutable permissions.
1925                if ((flags & immutableFlags) == 0) {
1926                    grantRuntimePermission(pkg.packageName, permission, userId);
1927                }
1928            }
1929        }
1930    }
1931
1932    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1933        Bundle extras = null;
1934        switch (res.returnCode) {
1935            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1936                extras = new Bundle();
1937                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1938                        res.origPermission);
1939                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1940                        res.origPackage);
1941                break;
1942            }
1943            case PackageManager.INSTALL_SUCCEEDED: {
1944                extras = new Bundle();
1945                extras.putBoolean(Intent.EXTRA_REPLACING,
1946                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1947                break;
1948            }
1949        }
1950        return extras;
1951    }
1952
1953    void scheduleWriteSettingsLocked() {
1954        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1955            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1956        }
1957    }
1958
1959    void scheduleWritePackageListLocked(int userId) {
1960        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1961            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1962            msg.arg1 = userId;
1963            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1964        }
1965    }
1966
1967    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1968        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1969        scheduleWritePackageRestrictionsLocked(userId);
1970    }
1971
1972    void scheduleWritePackageRestrictionsLocked(int userId) {
1973        final int[] userIds = (userId == UserHandle.USER_ALL)
1974                ? sUserManager.getUserIds() : new int[]{userId};
1975        for (int nextUserId : userIds) {
1976            if (!sUserManager.exists(nextUserId)) return;
1977            mDirtyUsers.add(nextUserId);
1978            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1979                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1980            }
1981        }
1982    }
1983
1984    public static PackageManagerService main(Context context, Installer installer,
1985            boolean factoryTest, boolean onlyCore) {
1986        // Self-check for initial settings.
1987        PackageManagerServiceCompilerMapping.checkProperties();
1988
1989        PackageManagerService m = new PackageManagerService(context, installer,
1990                factoryTest, onlyCore);
1991        m.enableSystemUserPackages();
1992        ServiceManager.addService("package", m);
1993        return m;
1994    }
1995
1996    private void enableSystemUserPackages() {
1997        if (!UserManager.isSplitSystemUser()) {
1998            return;
1999        }
2000        // For system user, enable apps based on the following conditions:
2001        // - app is whitelisted or belong to one of these groups:
2002        //   -- system app which has no launcher icons
2003        //   -- system app which has INTERACT_ACROSS_USERS permission
2004        //   -- system IME app
2005        // - app is not in the blacklist
2006        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2007        Set<String> enableApps = new ArraySet<>();
2008        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2009                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2010                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2011        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2012        enableApps.addAll(wlApps);
2013        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2014                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2015        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2016        enableApps.removeAll(blApps);
2017        Log.i(TAG, "Applications installed for system user: " + enableApps);
2018        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2019                UserHandle.SYSTEM);
2020        final int allAppsSize = allAps.size();
2021        synchronized (mPackages) {
2022            for (int i = 0; i < allAppsSize; i++) {
2023                String pName = allAps.get(i);
2024                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2025                // Should not happen, but we shouldn't be failing if it does
2026                if (pkgSetting == null) {
2027                    continue;
2028                }
2029                boolean install = enableApps.contains(pName);
2030                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2031                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2032                            + " for system user");
2033                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2034                }
2035            }
2036        }
2037    }
2038
2039    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2040        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2041                Context.DISPLAY_SERVICE);
2042        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2043    }
2044
2045    /**
2046     * Requests that files preopted on a secondary system partition be copied to the data partition
2047     * if possible.  Note that the actual copying of the files is accomplished by init for security
2048     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2049     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2050     */
2051    private static void requestCopyPreoptedFiles() {
2052        final int WAIT_TIME_MS = 100;
2053        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2054        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2055            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2056            // We will wait for up to 100 seconds.
2057            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2058            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2059                try {
2060                    Thread.sleep(WAIT_TIME_MS);
2061                } catch (InterruptedException e) {
2062                    // Do nothing
2063                }
2064                if (SystemClock.uptimeMillis() > timeEnd) {
2065                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2066                    Slog.wtf(TAG, "cppreopt did not finish!");
2067                    break;
2068                }
2069            }
2070        }
2071    }
2072
2073    public PackageManagerService(Context context, Installer installer,
2074            boolean factoryTest, boolean onlyCore) {
2075        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2076        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2077                SystemClock.uptimeMillis());
2078
2079        if (mSdkVersion <= 0) {
2080            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2081        }
2082
2083        mContext = context;
2084
2085        mPermissionReviewRequired = context.getResources().getBoolean(
2086                R.bool.config_permissionReviewRequired);
2087
2088        mFactoryTest = factoryTest;
2089        mOnlyCore = onlyCore;
2090        mMetrics = new DisplayMetrics();
2091        mSettings = new Settings(mPackages);
2092        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2093                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2095                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2097                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2098        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2099                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2100        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2101                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2103                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2104
2105        String separateProcesses = SystemProperties.get("debug.separate_processes");
2106        if (separateProcesses != null && separateProcesses.length() > 0) {
2107            if ("*".equals(separateProcesses)) {
2108                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2109                mSeparateProcesses = null;
2110                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2111            } else {
2112                mDefParseFlags = 0;
2113                mSeparateProcesses = separateProcesses.split(",");
2114                Slog.w(TAG, "Running with debug.separate_processes: "
2115                        + separateProcesses);
2116            }
2117        } else {
2118            mDefParseFlags = 0;
2119            mSeparateProcesses = null;
2120        }
2121
2122        mInstaller = installer;
2123        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2124                "*dexopt*");
2125        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2126
2127        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2128                FgThread.get().getLooper());
2129
2130        getDefaultDisplayMetrics(context, mMetrics);
2131
2132        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2133        SystemConfig systemConfig = SystemConfig.getInstance();
2134        mGlobalGids = systemConfig.getGlobalGids();
2135        mSystemPermissions = systemConfig.getSystemPermissions();
2136        mAvailableFeatures = systemConfig.getAvailableFeatures();
2137        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2138
2139        mProtectedPackages = new ProtectedPackages(mContext);
2140
2141        synchronized (mInstallLock) {
2142        // writer
2143        synchronized (mPackages) {
2144            mHandlerThread = new ServiceThread(TAG,
2145                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2146            mHandlerThread.start();
2147            mHandler = new PackageHandler(mHandlerThread.getLooper());
2148            mProcessLoggingHandler = new ProcessLoggingHandler();
2149            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2150
2151            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2152
2153            File dataDir = Environment.getDataDirectory();
2154            mAppInstallDir = new File(dataDir, "app");
2155            mAppLib32InstallDir = new File(dataDir, "app-lib");
2156            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2157            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2158            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2159
2160            sUserManager = new UserManagerService(context, this, mPackages);
2161
2162            // Propagate permission configuration in to package manager.
2163            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2164                    = systemConfig.getPermissions();
2165            for (int i=0; i<permConfig.size(); i++) {
2166                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2167                BasePermission bp = mSettings.mPermissions.get(perm.name);
2168                if (bp == null) {
2169                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2170                    mSettings.mPermissions.put(perm.name, bp);
2171                }
2172                if (perm.gids != null) {
2173                    bp.setGids(perm.gids, perm.perUser);
2174                }
2175            }
2176
2177            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2178            for (int i=0; i<libConfig.size(); i++) {
2179                mSharedLibraries.put(libConfig.keyAt(i),
2180                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2181            }
2182
2183            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2184
2185            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2186            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2187            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2188
2189            if (mFirstBoot) {
2190                requestCopyPreoptedFiles();
2191            }
2192
2193            String customResolverActivity = Resources.getSystem().getString(
2194                    R.string.config_customResolverActivity);
2195            if (TextUtils.isEmpty(customResolverActivity)) {
2196                customResolverActivity = null;
2197            } else {
2198                mCustomResolverComponentName = ComponentName.unflattenFromString(
2199                        customResolverActivity);
2200            }
2201
2202            long startTime = SystemClock.uptimeMillis();
2203
2204            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2205                    startTime);
2206
2207            // Set flag to monitor and not change apk file paths when
2208            // scanning install directories.
2209            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2210
2211            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2212            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2213
2214            if (bootClassPath == null) {
2215                Slog.w(TAG, "No BOOTCLASSPATH found!");
2216            }
2217
2218            if (systemServerClassPath == null) {
2219                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2220            }
2221
2222            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2223            final String[] dexCodeInstructionSets =
2224                    getDexCodeInstructionSets(
2225                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2226
2227            /**
2228             * Ensure all external libraries have had dexopt run on them.
2229             */
2230            if (mSharedLibraries.size() > 0) {
2231                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2232                // NOTE: For now, we're compiling these system "shared libraries"
2233                // (and framework jars) into all available architectures. It's possible
2234                // to compile them only when we come across an app that uses them (there's
2235                // already logic for that in scanPackageLI) but that adds some complexity.
2236                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2237                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2238                        final String lib = libEntry.path;
2239                        if (lib == null) {
2240                            continue;
2241                        }
2242
2243                        try {
2244                            // Shared libraries do not have profiles so we perform a full
2245                            // AOT compilation (if needed).
2246                            int dexoptNeeded = DexFile.getDexOptNeeded(
2247                                    lib, dexCodeInstructionSet,
2248                                    getCompilerFilterForReason(REASON_SHARED_APK),
2249                                    false /* newProfile */);
2250                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2251                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2252                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2253                                        getCompilerFilterForReason(REASON_SHARED_APK),
2254                                        StorageManager.UUID_PRIVATE_INTERNAL,
2255                                        SKIP_SHARED_LIBRARY_CHECK);
2256                            }
2257                        } catch (FileNotFoundException e) {
2258                            Slog.w(TAG, "Library not found: " + lib);
2259                        } catch (IOException | InstallerException e) {
2260                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2261                                    + e.getMessage());
2262                        }
2263                    }
2264                }
2265                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2266            }
2267
2268            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2269
2270            final VersionInfo ver = mSettings.getInternalVersion();
2271            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2272
2273            // when upgrading from pre-M, promote system app permissions from install to runtime
2274            mPromoteSystemApps =
2275                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2276
2277            // When upgrading from pre-N, we need to handle package extraction like first boot,
2278            // as there is no profiling data available.
2279            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2280
2281            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2282
2283            // save off the names of pre-existing system packages prior to scanning; we don't
2284            // want to automatically grant runtime permissions for new system apps
2285            if (mPromoteSystemApps) {
2286                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2287                while (pkgSettingIter.hasNext()) {
2288                    PackageSetting ps = pkgSettingIter.next();
2289                    if (isSystemApp(ps)) {
2290                        mExistingSystemPackages.add(ps.name);
2291                    }
2292                }
2293            }
2294
2295            // Collect vendor overlay packages. (Do this before scanning any apps.)
2296            // For security and version matching reason, only consider
2297            // overlay packages if they reside in the right directory.
2298            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2299            if (overlayThemeDir.isEmpty()) {
2300                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2301            }
2302            if (!overlayThemeDir.isEmpty()) {
2303                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2304                        | PackageParser.PARSE_IS_SYSTEM
2305                        | PackageParser.PARSE_IS_SYSTEM_DIR
2306                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2307            }
2308            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2309                    | PackageParser.PARSE_IS_SYSTEM
2310                    | PackageParser.PARSE_IS_SYSTEM_DIR
2311                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2312
2313            // Find base frameworks (resource packages without code).
2314            scanDirTracedLI(frameworkDir, mDefParseFlags
2315                    | PackageParser.PARSE_IS_SYSTEM
2316                    | PackageParser.PARSE_IS_SYSTEM_DIR
2317                    | PackageParser.PARSE_IS_PRIVILEGED,
2318                    scanFlags | SCAN_NO_DEX, 0);
2319
2320            // Collected privileged system packages.
2321            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2322            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2323                    | PackageParser.PARSE_IS_SYSTEM
2324                    | PackageParser.PARSE_IS_SYSTEM_DIR
2325                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2326
2327            // Collect ordinary system packages.
2328            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2329            scanDirTracedLI(systemAppDir, mDefParseFlags
2330                    | PackageParser.PARSE_IS_SYSTEM
2331                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2332
2333            // Collect all vendor packages.
2334            File vendorAppDir = new File("/vendor/app");
2335            try {
2336                vendorAppDir = vendorAppDir.getCanonicalFile();
2337            } catch (IOException e) {
2338                // failed to look up canonical path, continue with original one
2339            }
2340            scanDirTracedLI(vendorAppDir, mDefParseFlags
2341                    | PackageParser.PARSE_IS_SYSTEM
2342                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2343
2344            // Collect all OEM packages.
2345            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2346            scanDirTracedLI(oemAppDir, mDefParseFlags
2347                    | PackageParser.PARSE_IS_SYSTEM
2348                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2349
2350            // Prune any system packages that no longer exist.
2351            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2352            if (!mOnlyCore) {
2353                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2354                while (psit.hasNext()) {
2355                    PackageSetting ps = psit.next();
2356
2357                    /*
2358                     * If this is not a system app, it can't be a
2359                     * disable system app.
2360                     */
2361                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2362                        continue;
2363                    }
2364
2365                    /*
2366                     * If the package is scanned, it's not erased.
2367                     */
2368                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2369                    if (scannedPkg != null) {
2370                        /*
2371                         * If the system app is both scanned and in the
2372                         * disabled packages list, then it must have been
2373                         * added via OTA. Remove it from the currently
2374                         * scanned package so the previously user-installed
2375                         * application can be scanned.
2376                         */
2377                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2378                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2379                                    + ps.name + "; removing system app.  Last known codePath="
2380                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2381                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2382                                    + scannedPkg.mVersionCode);
2383                            removePackageLI(scannedPkg, true);
2384                            mExpectingBetter.put(ps.name, ps.codePath);
2385                        }
2386
2387                        continue;
2388                    }
2389
2390                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2391                        psit.remove();
2392                        logCriticalInfo(Log.WARN, "System package " + ps.name
2393                                + " no longer exists; it's data will be wiped");
2394                        // Actual deletion of code and data will be handled by later
2395                        // reconciliation step
2396                    } else {
2397                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2398                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2399                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2400                        }
2401                    }
2402                }
2403            }
2404
2405            //look for any incomplete package installations
2406            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2407            for (int i = 0; i < deletePkgsList.size(); i++) {
2408                // Actual deletion of code and data will be handled by later
2409                // reconciliation step
2410                final String packageName = deletePkgsList.get(i).name;
2411                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2412                synchronized (mPackages) {
2413                    mSettings.removePackageLPw(packageName);
2414                }
2415            }
2416
2417            //delete tmp files
2418            deleteTempPackageFiles();
2419
2420            // Remove any shared userIDs that have no associated packages
2421            mSettings.pruneSharedUsersLPw();
2422
2423            if (!mOnlyCore) {
2424                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2425                        SystemClock.uptimeMillis());
2426                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2427
2428                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2429                        | PackageParser.PARSE_FORWARD_LOCK,
2430                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2431
2432                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2433                        | PackageParser.PARSE_IS_EPHEMERAL,
2434                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2435
2436                /**
2437                 * Remove disable package settings for any updated system
2438                 * apps that were removed via an OTA. If they're not a
2439                 * previously-updated app, remove them completely.
2440                 * Otherwise, just revoke their system-level permissions.
2441                 */
2442                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2443                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2444                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2445
2446                    String msg;
2447                    if (deletedPkg == null) {
2448                        msg = "Updated system package " + deletedAppName
2449                                + " no longer exists; it's data will be wiped";
2450                        // Actual deletion of code and data will be handled by later
2451                        // reconciliation step
2452                    } else {
2453                        msg = "Updated system app + " + deletedAppName
2454                                + " no longer present; removing system privileges for "
2455                                + deletedAppName;
2456
2457                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2458
2459                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2460                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2461                    }
2462                    logCriticalInfo(Log.WARN, msg);
2463                }
2464
2465                /**
2466                 * Make sure all system apps that we expected to appear on
2467                 * the userdata partition actually showed up. If they never
2468                 * appeared, crawl back and revive the system version.
2469                 */
2470                for (int i = 0; i < mExpectingBetter.size(); i++) {
2471                    final String packageName = mExpectingBetter.keyAt(i);
2472                    if (!mPackages.containsKey(packageName)) {
2473                        final File scanFile = mExpectingBetter.valueAt(i);
2474
2475                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2476                                + " but never showed up; reverting to system");
2477
2478                        int reparseFlags = mDefParseFlags;
2479                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2480                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2481                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2482                                    | PackageParser.PARSE_IS_PRIVILEGED;
2483                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2484                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2485                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2486                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2487                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2488                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2489                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2490                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2491                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2492                        } else {
2493                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2494                            continue;
2495                        }
2496
2497                        mSettings.enableSystemPackageLPw(packageName);
2498
2499                        try {
2500                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2501                        } catch (PackageManagerException e) {
2502                            Slog.e(TAG, "Failed to parse original system package: "
2503                                    + e.getMessage());
2504                        }
2505                    }
2506                }
2507            }
2508            mExpectingBetter.clear();
2509
2510            // Resolve the storage manager.
2511            mStorageManagerPackage = getStorageManagerPackageName();
2512
2513            // Resolve protected action filters. Only the setup wizard is allowed to
2514            // have a high priority filter for these actions.
2515            mSetupWizardPackage = getSetupWizardPackageName();
2516            if (mProtectedFilters.size() > 0) {
2517                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2518                    Slog.i(TAG, "No setup wizard;"
2519                        + " All protected intents capped to priority 0");
2520                }
2521                for (ActivityIntentInfo filter : mProtectedFilters) {
2522                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2523                        if (DEBUG_FILTERS) {
2524                            Slog.i(TAG, "Found setup wizard;"
2525                                + " allow priority " + filter.getPriority() + ";"
2526                                + " package: " + filter.activity.info.packageName
2527                                + " activity: " + filter.activity.className
2528                                + " priority: " + filter.getPriority());
2529                        }
2530                        // skip setup wizard; allow it to keep the high priority filter
2531                        continue;
2532                    }
2533                    Slog.w(TAG, "Protected action; cap priority to 0;"
2534                            + " package: " + filter.activity.info.packageName
2535                            + " activity: " + filter.activity.className
2536                            + " origPrio: " + filter.getPriority());
2537                    filter.setPriority(0);
2538                }
2539            }
2540            mDeferProtectedFilters = false;
2541            mProtectedFilters.clear();
2542
2543            // Now that we know all of the shared libraries, update all clients to have
2544            // the correct library paths.
2545            updateAllSharedLibrariesLPw();
2546
2547            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2548                // NOTE: We ignore potential failures here during a system scan (like
2549                // the rest of the commands above) because there's precious little we
2550                // can do about it. A settings error is reported, though.
2551                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2552            }
2553
2554            // Now that we know all the packages we are keeping,
2555            // read and update their last usage times.
2556            mPackageUsage.read(mPackages);
2557            mCompilerStats.read();
2558
2559            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2560                    SystemClock.uptimeMillis());
2561            Slog.i(TAG, "Time to scan packages: "
2562                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2563                    + " seconds");
2564
2565            // If the platform SDK has changed since the last time we booted,
2566            // we need to re-grant app permission to catch any new ones that
2567            // appear.  This is really a hack, and means that apps can in some
2568            // cases get permissions that the user didn't initially explicitly
2569            // allow...  it would be nice to have some better way to handle
2570            // this situation.
2571            int updateFlags = UPDATE_PERMISSIONS_ALL;
2572            if (ver.sdkVersion != mSdkVersion) {
2573                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2574                        + mSdkVersion + "; regranting permissions for internal storage");
2575                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2576            }
2577            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2578            ver.sdkVersion = mSdkVersion;
2579
2580            // If this is the first boot or an update from pre-M, and it is a normal
2581            // boot, then we need to initialize the default preferred apps across
2582            // all defined users.
2583            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2584                for (UserInfo user : sUserManager.getUsers(true)) {
2585                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2586                    applyFactoryDefaultBrowserLPw(user.id);
2587                    primeDomainVerificationsLPw(user.id);
2588                }
2589            }
2590
2591            // Prepare storage for system user really early during boot,
2592            // since core system apps like SettingsProvider and SystemUI
2593            // can't wait for user to start
2594            final int storageFlags;
2595            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2596                storageFlags = StorageManager.FLAG_STORAGE_DE;
2597            } else {
2598                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2599            }
2600            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2601                    storageFlags, true /* migrateAppData */);
2602
2603            // If this is first boot after an OTA, and a normal boot, then
2604            // we need to clear code cache directories.
2605            // Note that we do *not* clear the application profiles. These remain valid
2606            // across OTAs and are used to drive profile verification (post OTA) and
2607            // profile compilation (without waiting to collect a fresh set of profiles).
2608            if (mIsUpgrade && !onlyCore) {
2609                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2610                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2611                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2612                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2613                        // No apps are running this early, so no need to freeze
2614                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2615                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2616                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2617                    }
2618                }
2619                ver.fingerprint = Build.FINGERPRINT;
2620            }
2621
2622            checkDefaultBrowser();
2623
2624            // clear only after permissions and other defaults have been updated
2625            mExistingSystemPackages.clear();
2626            mPromoteSystemApps = false;
2627
2628            // All the changes are done during package scanning.
2629            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2630
2631            // can downgrade to reader
2632            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2633            mSettings.writeLPr();
2634            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2635
2636            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2637            // early on (before the package manager declares itself as early) because other
2638            // components in the system server might ask for package contexts for these apps.
2639            //
2640            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2641            // (i.e, that the data partition is unavailable).
2642            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2643                long start = System.nanoTime();
2644                List<PackageParser.Package> coreApps = new ArrayList<>();
2645                for (PackageParser.Package pkg : mPackages.values()) {
2646                    if (pkg.coreApp) {
2647                        coreApps.add(pkg);
2648                    }
2649                }
2650
2651                int[] stats = performDexOptUpgrade(coreApps, false,
2652                        getCompilerFilterForReason(REASON_CORE_APP));
2653
2654                final int elapsedTimeSeconds =
2655                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2656                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2657
2658                if (DEBUG_DEXOPT) {
2659                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2660                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2661                }
2662
2663
2664                // TODO: Should we log these stats to tron too ?
2665                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2666                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2667                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2668                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2669            }
2670
2671            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2672                    SystemClock.uptimeMillis());
2673
2674            if (!mOnlyCore) {
2675                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2676                mRequiredInstallerPackage = getRequiredInstallerLPr();
2677                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2678                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2679                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2680                        mIntentFilterVerifierComponent);
2681                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2682                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2683                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2684                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2685            } else {
2686                mRequiredVerifierPackage = null;
2687                mRequiredInstallerPackage = null;
2688                mRequiredUninstallerPackage = null;
2689                mIntentFilterVerifierComponent = null;
2690                mIntentFilterVerifier = null;
2691                mServicesSystemSharedLibraryPackageName = null;
2692                mSharedSystemSharedLibraryPackageName = null;
2693            }
2694
2695            mInstallerService = new PackageInstallerService(context, this);
2696
2697            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2698            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2699            // both the installer and resolver must be present to enable ephemeral
2700            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2701                if (DEBUG_EPHEMERAL) {
2702                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2703                            + " installer:" + ephemeralInstallerComponent);
2704                }
2705                mEphemeralResolverComponent = ephemeralResolverComponent;
2706                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2707                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2708                mEphemeralResolverConnection =
2709                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2710            } else {
2711                if (DEBUG_EPHEMERAL) {
2712                    final String missingComponent =
2713                            (ephemeralResolverComponent == null)
2714                            ? (ephemeralInstallerComponent == null)
2715                                    ? "resolver and installer"
2716                                    : "resolver"
2717                            : "installer";
2718                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2719                }
2720                mEphemeralResolverComponent = null;
2721                mEphemeralInstallerComponent = null;
2722                mEphemeralResolverConnection = null;
2723            }
2724
2725            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2726        } // synchronized (mPackages)
2727        } // synchronized (mInstallLock)
2728
2729        // Now after opening every single application zip, make sure they
2730        // are all flushed.  Not really needed, but keeps things nice and
2731        // tidy.
2732        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2733        Runtime.getRuntime().gc();
2734        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2735
2736        // The initial scanning above does many calls into installd while
2737        // holding the mPackages lock, but we're mostly interested in yelling
2738        // once we have a booted system.
2739        mInstaller.setWarnIfHeld(mPackages);
2740
2741        // Expose private service for system components to use.
2742        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2743        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2744    }
2745
2746    @Override
2747    public boolean isFirstBoot() {
2748        return mFirstBoot;
2749    }
2750
2751    @Override
2752    public boolean isOnlyCoreApps() {
2753        return mOnlyCore;
2754    }
2755
2756    @Override
2757    public boolean isUpgrade() {
2758        return mIsUpgrade;
2759    }
2760
2761    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2762        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2763
2764        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2765                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2766                UserHandle.USER_SYSTEM);
2767        if (matches.size() == 1) {
2768            return matches.get(0).getComponentInfo().packageName;
2769        } else if (matches.size() == 0) {
2770            Log.e(TAG, "There should probably be a verifier, but, none were found");
2771            return null;
2772        }
2773        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2774    }
2775
2776    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2777        synchronized (mPackages) {
2778            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2779            if (libraryEntry == null) {
2780                throw new IllegalStateException("Missing required shared library:" + libraryName);
2781            }
2782            return libraryEntry.apk;
2783        }
2784    }
2785
2786    private @NonNull String getRequiredInstallerLPr() {
2787        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2788        intent.addCategory(Intent.CATEGORY_DEFAULT);
2789        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2790
2791        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2792                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2793                UserHandle.USER_SYSTEM);
2794        if (matches.size() == 1) {
2795            ResolveInfo resolveInfo = matches.get(0);
2796            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2797                throw new RuntimeException("The installer must be a privileged app");
2798            }
2799            return matches.get(0).getComponentInfo().packageName;
2800        } else {
2801            throw new RuntimeException("There must be exactly one installer; found " + matches);
2802        }
2803    }
2804
2805    private @NonNull String getRequiredUninstallerLPr() {
2806        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2807        intent.addCategory(Intent.CATEGORY_DEFAULT);
2808        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2809
2810        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2811                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2812                UserHandle.USER_SYSTEM);
2813        if (resolveInfo == null ||
2814                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2815            throw new RuntimeException("There must be exactly one uninstaller; found "
2816                    + resolveInfo);
2817        }
2818        return resolveInfo.getComponentInfo().packageName;
2819    }
2820
2821    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2822        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2823
2824        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2825                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2826                UserHandle.USER_SYSTEM);
2827        ResolveInfo best = null;
2828        final int N = matches.size();
2829        for (int i = 0; i < N; i++) {
2830            final ResolveInfo cur = matches.get(i);
2831            final String packageName = cur.getComponentInfo().packageName;
2832            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2833                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2834                continue;
2835            }
2836
2837            if (best == null || cur.priority > best.priority) {
2838                best = cur;
2839            }
2840        }
2841
2842        if (best != null) {
2843            return best.getComponentInfo().getComponentName();
2844        } else {
2845            throw new RuntimeException("There must be at least one intent filter verifier");
2846        }
2847    }
2848
2849    private @Nullable ComponentName getEphemeralResolverLPr() {
2850        final String[] packageArray =
2851                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2852        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2853            if (DEBUG_EPHEMERAL) {
2854                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2855            }
2856            return null;
2857        }
2858
2859        final int resolveFlags =
2860                MATCH_DIRECT_BOOT_AWARE
2861                | MATCH_DIRECT_BOOT_UNAWARE
2862                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2863        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2864        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2865                resolveFlags, UserHandle.USER_SYSTEM);
2866
2867        final int N = resolvers.size();
2868        if (N == 0) {
2869            if (DEBUG_EPHEMERAL) {
2870                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2871            }
2872            return null;
2873        }
2874
2875        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2876        for (int i = 0; i < N; i++) {
2877            final ResolveInfo info = resolvers.get(i);
2878
2879            if (info.serviceInfo == null) {
2880                continue;
2881            }
2882
2883            final String packageName = info.serviceInfo.packageName;
2884            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2885                if (DEBUG_EPHEMERAL) {
2886                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2887                            + " pkg: " + packageName + ", info:" + info);
2888                }
2889                continue;
2890            }
2891
2892            if (DEBUG_EPHEMERAL) {
2893                Slog.v(TAG, "Ephemeral resolver found;"
2894                        + " pkg: " + packageName + ", info:" + info);
2895            }
2896            return new ComponentName(packageName, info.serviceInfo.name);
2897        }
2898        if (DEBUG_EPHEMERAL) {
2899            Slog.v(TAG, "Ephemeral resolver NOT found");
2900        }
2901        return null;
2902    }
2903
2904    private @Nullable ComponentName getEphemeralInstallerLPr() {
2905        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2906        intent.addCategory(Intent.CATEGORY_DEFAULT);
2907        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2908
2909        final int resolveFlags =
2910                MATCH_DIRECT_BOOT_AWARE
2911                | MATCH_DIRECT_BOOT_UNAWARE
2912                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2913        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2914                resolveFlags, UserHandle.USER_SYSTEM);
2915        if (matches.size() == 0) {
2916            return null;
2917        } else if (matches.size() == 1) {
2918            return matches.get(0).getComponentInfo().getComponentName();
2919        } else {
2920            throw new RuntimeException(
2921                    "There must be at most one ephemeral installer; found " + matches);
2922        }
2923    }
2924
2925    private void primeDomainVerificationsLPw(int userId) {
2926        if (DEBUG_DOMAIN_VERIFICATION) {
2927            Slog.d(TAG, "Priming domain verifications in user " + userId);
2928        }
2929
2930        SystemConfig systemConfig = SystemConfig.getInstance();
2931        ArraySet<String> packages = systemConfig.getLinkedApps();
2932
2933        for (String packageName : packages) {
2934            PackageParser.Package pkg = mPackages.get(packageName);
2935            if (pkg != null) {
2936                if (!pkg.isSystemApp()) {
2937                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2938                    continue;
2939                }
2940
2941                ArraySet<String> domains = null;
2942                for (PackageParser.Activity a : pkg.activities) {
2943                    for (ActivityIntentInfo filter : a.intents) {
2944                        if (hasValidDomains(filter)) {
2945                            if (domains == null) {
2946                                domains = new ArraySet<String>();
2947                            }
2948                            domains.addAll(filter.getHostsList());
2949                        }
2950                    }
2951                }
2952
2953                if (domains != null && domains.size() > 0) {
2954                    if (DEBUG_DOMAIN_VERIFICATION) {
2955                        Slog.v(TAG, "      + " + packageName);
2956                    }
2957                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2958                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2959                    // and then 'always' in the per-user state actually used for intent resolution.
2960                    final IntentFilterVerificationInfo ivi;
2961                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2962                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2963                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2964                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2965                } else {
2966                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2967                            + "' does not handle web links");
2968                }
2969            } else {
2970                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2971            }
2972        }
2973
2974        scheduleWritePackageRestrictionsLocked(userId);
2975        scheduleWriteSettingsLocked();
2976    }
2977
2978    private void applyFactoryDefaultBrowserLPw(int userId) {
2979        // The default browser app's package name is stored in a string resource,
2980        // with a product-specific overlay used for vendor customization.
2981        String browserPkg = mContext.getResources().getString(
2982                com.android.internal.R.string.default_browser);
2983        if (!TextUtils.isEmpty(browserPkg)) {
2984            // non-empty string => required to be a known package
2985            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2986            if (ps == null) {
2987                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2988                browserPkg = null;
2989            } else {
2990                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2991            }
2992        }
2993
2994        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2995        // default.  If there's more than one, just leave everything alone.
2996        if (browserPkg == null) {
2997            calculateDefaultBrowserLPw(userId);
2998        }
2999    }
3000
3001    private void calculateDefaultBrowserLPw(int userId) {
3002        List<String> allBrowsers = resolveAllBrowserApps(userId);
3003        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3004        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3005    }
3006
3007    private List<String> resolveAllBrowserApps(int userId) {
3008        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3009        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3010                PackageManager.MATCH_ALL, userId);
3011
3012        final int count = list.size();
3013        List<String> result = new ArrayList<String>(count);
3014        for (int i=0; i<count; i++) {
3015            ResolveInfo info = list.get(i);
3016            if (info.activityInfo == null
3017                    || !info.handleAllWebDataURI
3018                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3019                    || result.contains(info.activityInfo.packageName)) {
3020                continue;
3021            }
3022            result.add(info.activityInfo.packageName);
3023        }
3024
3025        return result;
3026    }
3027
3028    private boolean packageIsBrowser(String packageName, int userId) {
3029        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3030                PackageManager.MATCH_ALL, userId);
3031        final int N = list.size();
3032        for (int i = 0; i < N; i++) {
3033            ResolveInfo info = list.get(i);
3034            if (packageName.equals(info.activityInfo.packageName)) {
3035                return true;
3036            }
3037        }
3038        return false;
3039    }
3040
3041    private void checkDefaultBrowser() {
3042        final int myUserId = UserHandle.myUserId();
3043        final String packageName = getDefaultBrowserPackageName(myUserId);
3044        if (packageName != null) {
3045            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3046            if (info == null) {
3047                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3048                synchronized (mPackages) {
3049                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3050                }
3051            }
3052        }
3053    }
3054
3055    @Override
3056    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3057            throws RemoteException {
3058        try {
3059            return super.onTransact(code, data, reply, flags);
3060        } catch (RuntimeException e) {
3061            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3062                Slog.wtf(TAG, "Package Manager Crash", e);
3063            }
3064            throw e;
3065        }
3066    }
3067
3068    static int[] appendInts(int[] cur, int[] add) {
3069        if (add == null) return cur;
3070        if (cur == null) return add;
3071        final int N = add.length;
3072        for (int i=0; i<N; i++) {
3073            cur = appendInt(cur, add[i]);
3074        }
3075        return cur;
3076    }
3077
3078    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3079        if (!sUserManager.exists(userId)) return null;
3080        if (ps == null) {
3081            return null;
3082        }
3083        final PackageParser.Package p = ps.pkg;
3084        if (p == null) {
3085            return null;
3086        }
3087
3088        final PermissionsState permissionsState = ps.getPermissionsState();
3089
3090        // Compute GIDs only if requested
3091        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3092                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3093        // Compute granted permissions only if package has requested permissions
3094        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3095                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3096        final PackageUserState state = ps.readUserState(userId);
3097
3098        return PackageParser.generatePackageInfo(p, gids, flags,
3099                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3100    }
3101
3102    @Override
3103    public void checkPackageStartable(String packageName, int userId) {
3104        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3105
3106        synchronized (mPackages) {
3107            final PackageSetting ps = mSettings.mPackages.get(packageName);
3108            if (ps == null) {
3109                throw new SecurityException("Package " + packageName + " was not found!");
3110            }
3111
3112            if (!ps.getInstalled(userId)) {
3113                throw new SecurityException(
3114                        "Package " + packageName + " was not installed for user " + userId + "!");
3115            }
3116
3117            if (mSafeMode && !ps.isSystem()) {
3118                throw new SecurityException("Package " + packageName + " not a system app!");
3119            }
3120
3121            if (mFrozenPackages.contains(packageName)) {
3122                throw new SecurityException("Package " + packageName + " is currently frozen!");
3123            }
3124
3125            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3126                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3127                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3128            }
3129        }
3130    }
3131
3132    @Override
3133    public boolean isPackageAvailable(String packageName, int userId) {
3134        if (!sUserManager.exists(userId)) return false;
3135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3136                false /* requireFullPermission */, false /* checkShell */, "is package available");
3137        synchronized (mPackages) {
3138            PackageParser.Package p = mPackages.get(packageName);
3139            if (p != null) {
3140                final PackageSetting ps = (PackageSetting) p.mExtras;
3141                if (ps != null) {
3142                    final PackageUserState state = ps.readUserState(userId);
3143                    if (state != null) {
3144                        return PackageParser.isAvailable(state);
3145                    }
3146                }
3147            }
3148        }
3149        return false;
3150    }
3151
3152    @Override
3153    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3154        if (!sUserManager.exists(userId)) return null;
3155        flags = updateFlagsForPackage(flags, userId, packageName);
3156        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3157                false /* requireFullPermission */, false /* checkShell */, "get package info");
3158        // reader
3159        synchronized (mPackages) {
3160            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3161            PackageParser.Package p = null;
3162            if (matchFactoryOnly) {
3163                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3164                if (ps != null) {
3165                    return generatePackageInfo(ps, flags, userId);
3166                }
3167            }
3168            if (p == null) {
3169                p = mPackages.get(packageName);
3170                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3171                    return null;
3172                }
3173            }
3174            if (DEBUG_PACKAGE_INFO)
3175                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3176            if (p != null) {
3177                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3178            }
3179            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3180                final PackageSetting ps = mSettings.mPackages.get(packageName);
3181                return generatePackageInfo(ps, flags, userId);
3182            }
3183        }
3184        return null;
3185    }
3186
3187    @Override
3188    public String[] currentToCanonicalPackageNames(String[] names) {
3189        String[] out = new String[names.length];
3190        // reader
3191        synchronized (mPackages) {
3192            for (int i=names.length-1; i>=0; i--) {
3193                PackageSetting ps = mSettings.mPackages.get(names[i]);
3194                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3195            }
3196        }
3197        return out;
3198    }
3199
3200    @Override
3201    public String[] canonicalToCurrentPackageNames(String[] names) {
3202        String[] out = new String[names.length];
3203        // reader
3204        synchronized (mPackages) {
3205            for (int i=names.length-1; i>=0; i--) {
3206                String cur = mSettings.getRenamedPackageLPr(names[i]);
3207                out[i] = cur != null ? cur : names[i];
3208            }
3209        }
3210        return out;
3211    }
3212
3213    @Override
3214    public int getPackageUid(String packageName, int flags, int userId) {
3215        if (!sUserManager.exists(userId)) return -1;
3216        flags = updateFlagsForPackage(flags, userId, packageName);
3217        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3218                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3219
3220        // reader
3221        synchronized (mPackages) {
3222            final PackageParser.Package p = mPackages.get(packageName);
3223            if (p != null && p.isMatch(flags)) {
3224                return UserHandle.getUid(userId, p.applicationInfo.uid);
3225            }
3226            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3227                final PackageSetting ps = mSettings.mPackages.get(packageName);
3228                if (ps != null && ps.isMatch(flags)) {
3229                    return UserHandle.getUid(userId, ps.appId);
3230                }
3231            }
3232        }
3233
3234        return -1;
3235    }
3236
3237    @Override
3238    public int[] getPackageGids(String packageName, int flags, int userId) {
3239        if (!sUserManager.exists(userId)) return null;
3240        flags = updateFlagsForPackage(flags, userId, packageName);
3241        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3242                false /* requireFullPermission */, false /* checkShell */,
3243                "getPackageGids");
3244
3245        // reader
3246        synchronized (mPackages) {
3247            final PackageParser.Package p = mPackages.get(packageName);
3248            if (p != null && p.isMatch(flags)) {
3249                PackageSetting ps = (PackageSetting) p.mExtras;
3250                return ps.getPermissionsState().computeGids(userId);
3251            }
3252            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3253                final PackageSetting ps = mSettings.mPackages.get(packageName);
3254                if (ps != null && ps.isMatch(flags)) {
3255                    return ps.getPermissionsState().computeGids(userId);
3256                }
3257            }
3258        }
3259
3260        return null;
3261    }
3262
3263    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3264        if (bp.perm != null) {
3265            return PackageParser.generatePermissionInfo(bp.perm, flags);
3266        }
3267        PermissionInfo pi = new PermissionInfo();
3268        pi.name = bp.name;
3269        pi.packageName = bp.sourcePackage;
3270        pi.nonLocalizedLabel = bp.name;
3271        pi.protectionLevel = bp.protectionLevel;
3272        return pi;
3273    }
3274
3275    @Override
3276    public PermissionInfo getPermissionInfo(String name, int flags) {
3277        // reader
3278        synchronized (mPackages) {
3279            final BasePermission p = mSettings.mPermissions.get(name);
3280            if (p != null) {
3281                return generatePermissionInfo(p, flags);
3282            }
3283            return null;
3284        }
3285    }
3286
3287    @Override
3288    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3289            int flags) {
3290        // reader
3291        synchronized (mPackages) {
3292            if (group != null && !mPermissionGroups.containsKey(group)) {
3293                // This is thrown as NameNotFoundException
3294                return null;
3295            }
3296
3297            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3298            for (BasePermission p : mSettings.mPermissions.values()) {
3299                if (group == null) {
3300                    if (p.perm == null || p.perm.info.group == null) {
3301                        out.add(generatePermissionInfo(p, flags));
3302                    }
3303                } else {
3304                    if (p.perm != null && group.equals(p.perm.info.group)) {
3305                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3306                    }
3307                }
3308            }
3309            return new ParceledListSlice<>(out);
3310        }
3311    }
3312
3313    @Override
3314    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3315        // reader
3316        synchronized (mPackages) {
3317            return PackageParser.generatePermissionGroupInfo(
3318                    mPermissionGroups.get(name), flags);
3319        }
3320    }
3321
3322    @Override
3323    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3324        // reader
3325        synchronized (mPackages) {
3326            final int N = mPermissionGroups.size();
3327            ArrayList<PermissionGroupInfo> out
3328                    = new ArrayList<PermissionGroupInfo>(N);
3329            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3330                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3331            }
3332            return new ParceledListSlice<>(out);
3333        }
3334    }
3335
3336    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3337            int userId) {
3338        if (!sUserManager.exists(userId)) return null;
3339        PackageSetting ps = mSettings.mPackages.get(packageName);
3340        if (ps != null) {
3341            if (ps.pkg == null) {
3342                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3343                if (pInfo != null) {
3344                    return pInfo.applicationInfo;
3345                }
3346                return null;
3347            }
3348            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3349                    ps.readUserState(userId), userId);
3350        }
3351        return null;
3352    }
3353
3354    @Override
3355    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3356        if (!sUserManager.exists(userId)) return null;
3357        flags = updateFlagsForApplication(flags, userId, packageName);
3358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3359                false /* requireFullPermission */, false /* checkShell */, "get application info");
3360        // writer
3361        synchronized (mPackages) {
3362            PackageParser.Package p = mPackages.get(packageName);
3363            if (DEBUG_PACKAGE_INFO) Log.v(
3364                    TAG, "getApplicationInfo " + packageName
3365                    + ": " + p);
3366            if (p != null) {
3367                PackageSetting ps = mSettings.mPackages.get(packageName);
3368                if (ps == null) return null;
3369                // Note: isEnabledLP() does not apply here - always return info
3370                return PackageParser.generateApplicationInfo(
3371                        p, flags, ps.readUserState(userId), userId);
3372            }
3373            if ("android".equals(packageName)||"system".equals(packageName)) {
3374                return mAndroidApplication;
3375            }
3376            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3377                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3378            }
3379        }
3380        return null;
3381    }
3382
3383    @Override
3384    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3385            final IPackageDataObserver observer) {
3386        mContext.enforceCallingOrSelfPermission(
3387                android.Manifest.permission.CLEAR_APP_CACHE, null);
3388        // Queue up an async operation since clearing cache may take a little while.
3389        mHandler.post(new Runnable() {
3390            public void run() {
3391                mHandler.removeCallbacks(this);
3392                boolean success = true;
3393                synchronized (mInstallLock) {
3394                    try {
3395                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3396                    } catch (InstallerException e) {
3397                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3398                        success = false;
3399                    }
3400                }
3401                if (observer != null) {
3402                    try {
3403                        observer.onRemoveCompleted(null, success);
3404                    } catch (RemoteException e) {
3405                        Slog.w(TAG, "RemoveException when invoking call back");
3406                    }
3407                }
3408            }
3409        });
3410    }
3411
3412    @Override
3413    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3414            final IntentSender pi) {
3415        mContext.enforceCallingOrSelfPermission(
3416                android.Manifest.permission.CLEAR_APP_CACHE, null);
3417        // Queue up an async operation since clearing cache may take a little while.
3418        mHandler.post(new Runnable() {
3419            public void run() {
3420                mHandler.removeCallbacks(this);
3421                boolean success = true;
3422                synchronized (mInstallLock) {
3423                    try {
3424                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3425                    } catch (InstallerException e) {
3426                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3427                        success = false;
3428                    }
3429                }
3430                if(pi != null) {
3431                    try {
3432                        // Callback via pending intent
3433                        int code = success ? 1 : 0;
3434                        pi.sendIntent(null, code, null,
3435                                null, null);
3436                    } catch (SendIntentException e1) {
3437                        Slog.i(TAG, "Failed to send pending intent");
3438                    }
3439                }
3440            }
3441        });
3442    }
3443
3444    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3445        synchronized (mInstallLock) {
3446            try {
3447                mInstaller.freeCache(volumeUuid, freeStorageSize);
3448            } catch (InstallerException e) {
3449                throw new IOException("Failed to free enough space", e);
3450            }
3451        }
3452    }
3453
3454    /**
3455     * Update given flags based on encryption status of current user.
3456     */
3457    private int updateFlags(int flags, int userId) {
3458        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3459                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3460            // Caller expressed an explicit opinion about what encryption
3461            // aware/unaware components they want to see, so fall through and
3462            // give them what they want
3463        } else {
3464            // Caller expressed no opinion, so match based on user state
3465            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3466                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3467            } else {
3468                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3469            }
3470        }
3471        return flags;
3472    }
3473
3474    private UserManagerInternal getUserManagerInternal() {
3475        if (mUserManagerInternal == null) {
3476            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3477        }
3478        return mUserManagerInternal;
3479    }
3480
3481    /**
3482     * Update given flags when being used to request {@link PackageInfo}.
3483     */
3484    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3485        boolean triaged = true;
3486        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3487                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3488            // Caller is asking for component details, so they'd better be
3489            // asking for specific encryption matching behavior, or be triaged
3490            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3491                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3492                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3493                triaged = false;
3494            }
3495        }
3496        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3497                | PackageManager.MATCH_SYSTEM_ONLY
3498                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3499            triaged = false;
3500        }
3501        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3502            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3503                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3504        }
3505        return updateFlags(flags, userId);
3506    }
3507
3508    /**
3509     * Update given flags when being used to request {@link ApplicationInfo}.
3510     */
3511    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3512        return updateFlagsForPackage(flags, userId, cookie);
3513    }
3514
3515    /**
3516     * Update given flags when being used to request {@link ComponentInfo}.
3517     */
3518    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3519        if (cookie instanceof Intent) {
3520            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3521                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3522            }
3523        }
3524
3525        boolean triaged = true;
3526        // Caller is asking for component details, so they'd better be
3527        // asking for specific encryption matching behavior, or be triaged
3528        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3529                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3530                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3531            triaged = false;
3532        }
3533        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3534            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3535                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3536        }
3537
3538        return updateFlags(flags, userId);
3539    }
3540
3541    /**
3542     * Update given flags when being used to request {@link ResolveInfo}.
3543     */
3544    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3545        // Safe mode means we shouldn't match any third-party components
3546        if (mSafeMode) {
3547            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3548        }
3549
3550        return updateFlagsForComponent(flags, userId, cookie);
3551    }
3552
3553    @Override
3554    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3555        if (!sUserManager.exists(userId)) return null;
3556        flags = updateFlagsForComponent(flags, userId, component);
3557        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3558                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3559        synchronized (mPackages) {
3560            PackageParser.Activity a = mActivities.mActivities.get(component);
3561
3562            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3563            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3564                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3565                if (ps == null) return null;
3566                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3567                        userId);
3568            }
3569            if (mResolveComponentName.equals(component)) {
3570                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3571                        new PackageUserState(), userId);
3572            }
3573        }
3574        return null;
3575    }
3576
3577    @Override
3578    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3579            String resolvedType) {
3580        synchronized (mPackages) {
3581            if (component.equals(mResolveComponentName)) {
3582                // The resolver supports EVERYTHING!
3583                return true;
3584            }
3585            PackageParser.Activity a = mActivities.mActivities.get(component);
3586            if (a == null) {
3587                return false;
3588            }
3589            for (int i=0; i<a.intents.size(); i++) {
3590                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3591                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3592                    return true;
3593                }
3594            }
3595            return false;
3596        }
3597    }
3598
3599    @Override
3600    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3601        if (!sUserManager.exists(userId)) return null;
3602        flags = updateFlagsForComponent(flags, userId, component);
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3604                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3605        synchronized (mPackages) {
3606            PackageParser.Activity a = mReceivers.mActivities.get(component);
3607            if (DEBUG_PACKAGE_INFO) Log.v(
3608                TAG, "getReceiverInfo " + component + ": " + a);
3609            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3610                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3611                if (ps == null) return null;
3612                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3613                        userId);
3614            }
3615        }
3616        return null;
3617    }
3618
3619    @Override
3620    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3621        if (!sUserManager.exists(userId)) return null;
3622        flags = updateFlagsForComponent(flags, userId, component);
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3624                false /* requireFullPermission */, false /* checkShell */, "get service info");
3625        synchronized (mPackages) {
3626            PackageParser.Service s = mServices.mServices.get(component);
3627            if (DEBUG_PACKAGE_INFO) Log.v(
3628                TAG, "getServiceInfo " + component + ": " + s);
3629            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3630                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3631                if (ps == null) return null;
3632                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3633                        userId);
3634            }
3635        }
3636        return null;
3637    }
3638
3639    @Override
3640    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3641        if (!sUserManager.exists(userId)) return null;
3642        flags = updateFlagsForComponent(flags, userId, component);
3643        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3644                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3645        synchronized (mPackages) {
3646            PackageParser.Provider p = mProviders.mProviders.get(component);
3647            if (DEBUG_PACKAGE_INFO) Log.v(
3648                TAG, "getProviderInfo " + component + ": " + p);
3649            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3650                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3651                if (ps == null) return null;
3652                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3653                        userId);
3654            }
3655        }
3656        return null;
3657    }
3658
3659    @Override
3660    public String[] getSystemSharedLibraryNames() {
3661        Set<String> libSet;
3662        synchronized (mPackages) {
3663            libSet = mSharedLibraries.keySet();
3664            int size = libSet.size();
3665            if (size > 0) {
3666                String[] libs = new String[size];
3667                libSet.toArray(libs);
3668                return libs;
3669            }
3670        }
3671        return null;
3672    }
3673
3674    @Override
3675    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3676        synchronized (mPackages) {
3677            return mServicesSystemSharedLibraryPackageName;
3678        }
3679    }
3680
3681    @Override
3682    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3683        synchronized (mPackages) {
3684            return mSharedSystemSharedLibraryPackageName;
3685        }
3686    }
3687
3688    @Override
3689    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3690        synchronized (mPackages) {
3691            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3692
3693            final FeatureInfo fi = new FeatureInfo();
3694            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3695                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3696            res.add(fi);
3697
3698            return new ParceledListSlice<>(res);
3699        }
3700    }
3701
3702    @Override
3703    public boolean hasSystemFeature(String name, int version) {
3704        synchronized (mPackages) {
3705            final FeatureInfo feat = mAvailableFeatures.get(name);
3706            if (feat == null) {
3707                return false;
3708            } else {
3709                return feat.version >= version;
3710            }
3711        }
3712    }
3713
3714    @Override
3715    public int checkPermission(String permName, String pkgName, int userId) {
3716        if (!sUserManager.exists(userId)) {
3717            return PackageManager.PERMISSION_DENIED;
3718        }
3719
3720        synchronized (mPackages) {
3721            final PackageParser.Package p = mPackages.get(pkgName);
3722            if (p != null && p.mExtras != null) {
3723                final PackageSetting ps = (PackageSetting) p.mExtras;
3724                final PermissionsState permissionsState = ps.getPermissionsState();
3725                if (permissionsState.hasPermission(permName, userId)) {
3726                    return PackageManager.PERMISSION_GRANTED;
3727                }
3728                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3729                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3730                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3731                    return PackageManager.PERMISSION_GRANTED;
3732                }
3733            }
3734        }
3735
3736        return PackageManager.PERMISSION_DENIED;
3737    }
3738
3739    @Override
3740    public int checkUidPermission(String permName, int uid) {
3741        final int userId = UserHandle.getUserId(uid);
3742
3743        if (!sUserManager.exists(userId)) {
3744            return PackageManager.PERMISSION_DENIED;
3745        }
3746
3747        synchronized (mPackages) {
3748            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3749            if (obj != null) {
3750                final SettingBase ps = (SettingBase) obj;
3751                final PermissionsState permissionsState = ps.getPermissionsState();
3752                if (permissionsState.hasPermission(permName, userId)) {
3753                    return PackageManager.PERMISSION_GRANTED;
3754                }
3755                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3756                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3757                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3758                    return PackageManager.PERMISSION_GRANTED;
3759                }
3760            } else {
3761                ArraySet<String> perms = mSystemPermissions.get(uid);
3762                if (perms != null) {
3763                    if (perms.contains(permName)) {
3764                        return PackageManager.PERMISSION_GRANTED;
3765                    }
3766                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3767                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3768                        return PackageManager.PERMISSION_GRANTED;
3769                    }
3770                }
3771            }
3772        }
3773
3774        return PackageManager.PERMISSION_DENIED;
3775    }
3776
3777    @Override
3778    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3779        if (UserHandle.getCallingUserId() != userId) {
3780            mContext.enforceCallingPermission(
3781                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3782                    "isPermissionRevokedByPolicy for user " + userId);
3783        }
3784
3785        if (checkPermission(permission, packageName, userId)
3786                == PackageManager.PERMISSION_GRANTED) {
3787            return false;
3788        }
3789
3790        final long identity = Binder.clearCallingIdentity();
3791        try {
3792            final int flags = getPermissionFlags(permission, packageName, userId);
3793            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3794        } finally {
3795            Binder.restoreCallingIdentity(identity);
3796        }
3797    }
3798
3799    @Override
3800    public String getPermissionControllerPackageName() {
3801        synchronized (mPackages) {
3802            return mRequiredInstallerPackage;
3803        }
3804    }
3805
3806    /**
3807     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3808     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3809     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3810     * @param message the message to log on security exception
3811     */
3812    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3813            boolean checkShell, String message) {
3814        if (userId < 0) {
3815            throw new IllegalArgumentException("Invalid userId " + userId);
3816        }
3817        if (checkShell) {
3818            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3819        }
3820        if (userId == UserHandle.getUserId(callingUid)) return;
3821        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3822            if (requireFullPermission) {
3823                mContext.enforceCallingOrSelfPermission(
3824                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3825            } else {
3826                try {
3827                    mContext.enforceCallingOrSelfPermission(
3828                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3829                } catch (SecurityException se) {
3830                    mContext.enforceCallingOrSelfPermission(
3831                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3832                }
3833            }
3834        }
3835    }
3836
3837    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3838        if (callingUid == Process.SHELL_UID) {
3839            if (userHandle >= 0
3840                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3841                throw new SecurityException("Shell does not have permission to access user "
3842                        + userHandle);
3843            } else if (userHandle < 0) {
3844                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3845                        + Debug.getCallers(3));
3846            }
3847        }
3848    }
3849
3850    private BasePermission findPermissionTreeLP(String permName) {
3851        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3852            if (permName.startsWith(bp.name) &&
3853                    permName.length() > bp.name.length() &&
3854                    permName.charAt(bp.name.length()) == '.') {
3855                return bp;
3856            }
3857        }
3858        return null;
3859    }
3860
3861    private BasePermission checkPermissionTreeLP(String permName) {
3862        if (permName != null) {
3863            BasePermission bp = findPermissionTreeLP(permName);
3864            if (bp != null) {
3865                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3866                    return bp;
3867                }
3868                throw new SecurityException("Calling uid "
3869                        + Binder.getCallingUid()
3870                        + " is not allowed to add to permission tree "
3871                        + bp.name + " owned by uid " + bp.uid);
3872            }
3873        }
3874        throw new SecurityException("No permission tree found for " + permName);
3875    }
3876
3877    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3878        if (s1 == null) {
3879            return s2 == null;
3880        }
3881        if (s2 == null) {
3882            return false;
3883        }
3884        if (s1.getClass() != s2.getClass()) {
3885            return false;
3886        }
3887        return s1.equals(s2);
3888    }
3889
3890    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3891        if (pi1.icon != pi2.icon) return false;
3892        if (pi1.logo != pi2.logo) return false;
3893        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3894        if (!compareStrings(pi1.name, pi2.name)) return false;
3895        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3896        // We'll take care of setting this one.
3897        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3898        // These are not currently stored in settings.
3899        //if (!compareStrings(pi1.group, pi2.group)) return false;
3900        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3901        //if (pi1.labelRes != pi2.labelRes) return false;
3902        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3903        return true;
3904    }
3905
3906    int permissionInfoFootprint(PermissionInfo info) {
3907        int size = info.name.length();
3908        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3909        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3910        return size;
3911    }
3912
3913    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3914        int size = 0;
3915        for (BasePermission perm : mSettings.mPermissions.values()) {
3916            if (perm.uid == tree.uid) {
3917                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3918            }
3919        }
3920        return size;
3921    }
3922
3923    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3924        // We calculate the max size of permissions defined by this uid and throw
3925        // if that plus the size of 'info' would exceed our stated maximum.
3926        if (tree.uid != Process.SYSTEM_UID) {
3927            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3928            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3929                throw new SecurityException("Permission tree size cap exceeded");
3930            }
3931        }
3932    }
3933
3934    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3935        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3936            throw new SecurityException("Label must be specified in permission");
3937        }
3938        BasePermission tree = checkPermissionTreeLP(info.name);
3939        BasePermission bp = mSettings.mPermissions.get(info.name);
3940        boolean added = bp == null;
3941        boolean changed = true;
3942        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3943        if (added) {
3944            enforcePermissionCapLocked(info, tree);
3945            bp = new BasePermission(info.name, tree.sourcePackage,
3946                    BasePermission.TYPE_DYNAMIC);
3947        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3948            throw new SecurityException(
3949                    "Not allowed to modify non-dynamic permission "
3950                    + info.name);
3951        } else {
3952            if (bp.protectionLevel == fixedLevel
3953                    && bp.perm.owner.equals(tree.perm.owner)
3954                    && bp.uid == tree.uid
3955                    && comparePermissionInfos(bp.perm.info, info)) {
3956                changed = false;
3957            }
3958        }
3959        bp.protectionLevel = fixedLevel;
3960        info = new PermissionInfo(info);
3961        info.protectionLevel = fixedLevel;
3962        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3963        bp.perm.info.packageName = tree.perm.info.packageName;
3964        bp.uid = tree.uid;
3965        if (added) {
3966            mSettings.mPermissions.put(info.name, bp);
3967        }
3968        if (changed) {
3969            if (!async) {
3970                mSettings.writeLPr();
3971            } else {
3972                scheduleWriteSettingsLocked();
3973            }
3974        }
3975        return added;
3976    }
3977
3978    @Override
3979    public boolean addPermission(PermissionInfo info) {
3980        synchronized (mPackages) {
3981            return addPermissionLocked(info, false);
3982        }
3983    }
3984
3985    @Override
3986    public boolean addPermissionAsync(PermissionInfo info) {
3987        synchronized (mPackages) {
3988            return addPermissionLocked(info, true);
3989        }
3990    }
3991
3992    @Override
3993    public void removePermission(String name) {
3994        synchronized (mPackages) {
3995            checkPermissionTreeLP(name);
3996            BasePermission bp = mSettings.mPermissions.get(name);
3997            if (bp != null) {
3998                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3999                    throw new SecurityException(
4000                            "Not allowed to modify non-dynamic permission "
4001                            + name);
4002                }
4003                mSettings.mPermissions.remove(name);
4004                mSettings.writeLPr();
4005            }
4006        }
4007    }
4008
4009    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4010            BasePermission bp) {
4011        int index = pkg.requestedPermissions.indexOf(bp.name);
4012        if (index == -1) {
4013            throw new SecurityException("Package " + pkg.packageName
4014                    + " has not requested permission " + bp.name);
4015        }
4016        if (!bp.isRuntime() && !bp.isDevelopment()) {
4017            throw new SecurityException("Permission " + bp.name
4018                    + " is not a changeable permission type");
4019        }
4020    }
4021
4022    @Override
4023    public void grantRuntimePermission(String packageName, String name, final int userId) {
4024        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4025    }
4026
4027    private void grantRuntimePermission(String packageName, String name, final int userId,
4028            boolean overridePolicy) {
4029        if (!sUserManager.exists(userId)) {
4030            Log.e(TAG, "No such user:" + userId);
4031            return;
4032        }
4033
4034        mContext.enforceCallingOrSelfPermission(
4035                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4036                "grantRuntimePermission");
4037
4038        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4039                true /* requireFullPermission */, true /* checkShell */,
4040                "grantRuntimePermission");
4041
4042        final int uid;
4043        final SettingBase sb;
4044
4045        synchronized (mPackages) {
4046            final PackageParser.Package pkg = mPackages.get(packageName);
4047            if (pkg == null) {
4048                throw new IllegalArgumentException("Unknown package: " + packageName);
4049            }
4050
4051            final BasePermission bp = mSettings.mPermissions.get(name);
4052            if (bp == null) {
4053                throw new IllegalArgumentException("Unknown permission: " + name);
4054            }
4055
4056            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4057
4058            // If a permission review is required for legacy apps we represent
4059            // their permissions as always granted runtime ones since we need
4060            // to keep the review required permission flag per user while an
4061            // install permission's state is shared across all users.
4062            if (mPermissionReviewRequired
4063                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4064                    && bp.isRuntime()) {
4065                return;
4066            }
4067
4068            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4069            sb = (SettingBase) pkg.mExtras;
4070            if (sb == null) {
4071                throw new IllegalArgumentException("Unknown package: " + packageName);
4072            }
4073
4074            final PermissionsState permissionsState = sb.getPermissionsState();
4075
4076            final int flags = permissionsState.getPermissionFlags(name, userId);
4077            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4078                throw new SecurityException("Cannot grant system fixed permission "
4079                        + name + " for package " + packageName);
4080            }
4081            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4082                throw new SecurityException("Cannot grant policy fixed permission "
4083                        + name + " for package " + packageName);
4084            }
4085
4086            if (bp.isDevelopment()) {
4087                // Development permissions must be handled specially, since they are not
4088                // normal runtime permissions.  For now they apply to all users.
4089                if (permissionsState.grantInstallPermission(bp) !=
4090                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4091                    scheduleWriteSettingsLocked();
4092                }
4093                return;
4094            }
4095
4096            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4097                throw new SecurityException("Cannot grant non-ephemeral permission"
4098                        + name + " for package " + packageName);
4099            }
4100
4101            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4102                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4103                return;
4104            }
4105
4106            final int result = permissionsState.grantRuntimePermission(bp, userId);
4107            switch (result) {
4108                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4109                    return;
4110                }
4111
4112                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4113                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4114                    mHandler.post(new Runnable() {
4115                        @Override
4116                        public void run() {
4117                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4118                        }
4119                    });
4120                }
4121                break;
4122            }
4123
4124            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4125
4126            // Not critical if that is lost - app has to request again.
4127            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4128        }
4129
4130        // Only need to do this if user is initialized. Otherwise it's a new user
4131        // and there are no processes running as the user yet and there's no need
4132        // to make an expensive call to remount processes for the changed permissions.
4133        if (READ_EXTERNAL_STORAGE.equals(name)
4134                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4135            final long token = Binder.clearCallingIdentity();
4136            try {
4137                if (sUserManager.isInitialized(userId)) {
4138                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4139                            MountServiceInternal.class);
4140                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4141                }
4142            } finally {
4143                Binder.restoreCallingIdentity(token);
4144            }
4145        }
4146    }
4147
4148    @Override
4149    public void revokeRuntimePermission(String packageName, String name, int userId) {
4150        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4151    }
4152
4153    private void revokeRuntimePermission(String packageName, String name, int userId,
4154            boolean overridePolicy) {
4155        if (!sUserManager.exists(userId)) {
4156            Log.e(TAG, "No such user:" + userId);
4157            return;
4158        }
4159
4160        mContext.enforceCallingOrSelfPermission(
4161                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4162                "revokeRuntimePermission");
4163
4164        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165                true /* requireFullPermission */, true /* checkShell */,
4166                "revokeRuntimePermission");
4167
4168        final int appId;
4169
4170        synchronized (mPackages) {
4171            final PackageParser.Package pkg = mPackages.get(packageName);
4172            if (pkg == null) {
4173                throw new IllegalArgumentException("Unknown package: " + packageName);
4174            }
4175
4176            final BasePermission bp = mSettings.mPermissions.get(name);
4177            if (bp == null) {
4178                throw new IllegalArgumentException("Unknown permission: " + name);
4179            }
4180
4181            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4182
4183            // If a permission review is required for legacy apps we represent
4184            // their permissions as always granted runtime ones since we need
4185            // to keep the review required permission flag per user while an
4186            // install permission's state is shared across all users.
4187            if (mPermissionReviewRequired
4188                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4189                    && bp.isRuntime()) {
4190                return;
4191            }
4192
4193            SettingBase sb = (SettingBase) pkg.mExtras;
4194            if (sb == null) {
4195                throw new IllegalArgumentException("Unknown package: " + packageName);
4196            }
4197
4198            final PermissionsState permissionsState = sb.getPermissionsState();
4199
4200            final int flags = permissionsState.getPermissionFlags(name, userId);
4201            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4202                throw new SecurityException("Cannot revoke system fixed permission "
4203                        + name + " for package " + packageName);
4204            }
4205            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4206                throw new SecurityException("Cannot revoke policy fixed permission "
4207                        + name + " for package " + packageName);
4208            }
4209
4210            if (bp.isDevelopment()) {
4211                // Development permissions must be handled specially, since they are not
4212                // normal runtime permissions.  For now they apply to all users.
4213                if (permissionsState.revokeInstallPermission(bp) !=
4214                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4215                    scheduleWriteSettingsLocked();
4216                }
4217                return;
4218            }
4219
4220            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4221                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4222                return;
4223            }
4224
4225            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4226
4227            // Critical, after this call app should never have the permission.
4228            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4229
4230            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4231        }
4232
4233        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4234    }
4235
4236    @Override
4237    public void resetRuntimePermissions() {
4238        mContext.enforceCallingOrSelfPermission(
4239                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4240                "revokeRuntimePermission");
4241
4242        int callingUid = Binder.getCallingUid();
4243        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4244            mContext.enforceCallingOrSelfPermission(
4245                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4246                    "resetRuntimePermissions");
4247        }
4248
4249        synchronized (mPackages) {
4250            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4251            for (int userId : UserManagerService.getInstance().getUserIds()) {
4252                final int packageCount = mPackages.size();
4253                for (int i = 0; i < packageCount; i++) {
4254                    PackageParser.Package pkg = mPackages.valueAt(i);
4255                    if (!(pkg.mExtras instanceof PackageSetting)) {
4256                        continue;
4257                    }
4258                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4259                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4260                }
4261            }
4262        }
4263    }
4264
4265    @Override
4266    public int getPermissionFlags(String name, String packageName, int userId) {
4267        if (!sUserManager.exists(userId)) {
4268            return 0;
4269        }
4270
4271        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4272
4273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4274                true /* requireFullPermission */, false /* checkShell */,
4275                "getPermissionFlags");
4276
4277        synchronized (mPackages) {
4278            final PackageParser.Package pkg = mPackages.get(packageName);
4279            if (pkg == null) {
4280                return 0;
4281            }
4282
4283            final BasePermission bp = mSettings.mPermissions.get(name);
4284            if (bp == null) {
4285                return 0;
4286            }
4287
4288            SettingBase sb = (SettingBase) pkg.mExtras;
4289            if (sb == null) {
4290                return 0;
4291            }
4292
4293            PermissionsState permissionsState = sb.getPermissionsState();
4294            return permissionsState.getPermissionFlags(name, userId);
4295        }
4296    }
4297
4298    @Override
4299    public void updatePermissionFlags(String name, String packageName, int flagMask,
4300            int flagValues, int userId) {
4301        if (!sUserManager.exists(userId)) {
4302            return;
4303        }
4304
4305        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4306
4307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4308                true /* requireFullPermission */, true /* checkShell */,
4309                "updatePermissionFlags");
4310
4311        // Only the system can change these flags and nothing else.
4312        if (getCallingUid() != Process.SYSTEM_UID) {
4313            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4314            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4315            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4316            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4317            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4318        }
4319
4320        synchronized (mPackages) {
4321            final PackageParser.Package pkg = mPackages.get(packageName);
4322            if (pkg == null) {
4323                throw new IllegalArgumentException("Unknown package: " + packageName);
4324            }
4325
4326            final BasePermission bp = mSettings.mPermissions.get(name);
4327            if (bp == null) {
4328                throw new IllegalArgumentException("Unknown permission: " + name);
4329            }
4330
4331            SettingBase sb = (SettingBase) pkg.mExtras;
4332            if (sb == null) {
4333                throw new IllegalArgumentException("Unknown package: " + packageName);
4334            }
4335
4336            PermissionsState permissionsState = sb.getPermissionsState();
4337
4338            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4339
4340            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4341                // Install and runtime permissions are stored in different places,
4342                // so figure out what permission changed and persist the change.
4343                if (permissionsState.getInstallPermissionState(name) != null) {
4344                    scheduleWriteSettingsLocked();
4345                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4346                        || hadState) {
4347                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4348                }
4349            }
4350        }
4351    }
4352
4353    /**
4354     * Update the permission flags for all packages and runtime permissions of a user in order
4355     * to allow device or profile owner to remove POLICY_FIXED.
4356     */
4357    @Override
4358    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4359        if (!sUserManager.exists(userId)) {
4360            return;
4361        }
4362
4363        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4364
4365        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4366                true /* requireFullPermission */, true /* checkShell */,
4367                "updatePermissionFlagsForAllApps");
4368
4369        // Only the system can change system fixed flags.
4370        if (getCallingUid() != Process.SYSTEM_UID) {
4371            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4372            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4373        }
4374
4375        synchronized (mPackages) {
4376            boolean changed = false;
4377            final int packageCount = mPackages.size();
4378            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4379                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4380                SettingBase sb = (SettingBase) pkg.mExtras;
4381                if (sb == null) {
4382                    continue;
4383                }
4384                PermissionsState permissionsState = sb.getPermissionsState();
4385                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4386                        userId, flagMask, flagValues);
4387            }
4388            if (changed) {
4389                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4390            }
4391        }
4392    }
4393
4394    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4395        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4396                != PackageManager.PERMISSION_GRANTED
4397            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4398                != PackageManager.PERMISSION_GRANTED) {
4399            throw new SecurityException(message + " requires "
4400                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4401                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4402        }
4403    }
4404
4405    @Override
4406    public boolean shouldShowRequestPermissionRationale(String permissionName,
4407            String packageName, int userId) {
4408        if (UserHandle.getCallingUserId() != userId) {
4409            mContext.enforceCallingPermission(
4410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4411                    "canShowRequestPermissionRationale for user " + userId);
4412        }
4413
4414        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4415        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4416            return false;
4417        }
4418
4419        if (checkPermission(permissionName, packageName, userId)
4420                == PackageManager.PERMISSION_GRANTED) {
4421            return false;
4422        }
4423
4424        final int flags;
4425
4426        final long identity = Binder.clearCallingIdentity();
4427        try {
4428            flags = getPermissionFlags(permissionName,
4429                    packageName, userId);
4430        } finally {
4431            Binder.restoreCallingIdentity(identity);
4432        }
4433
4434        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4435                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4436                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4437
4438        if ((flags & fixedFlags) != 0) {
4439            return false;
4440        }
4441
4442        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4443    }
4444
4445    @Override
4446    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4447        mContext.enforceCallingOrSelfPermission(
4448                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4449                "addOnPermissionsChangeListener");
4450
4451        synchronized (mPackages) {
4452            mOnPermissionChangeListeners.addListenerLocked(listener);
4453        }
4454    }
4455
4456    @Override
4457    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4458        synchronized (mPackages) {
4459            mOnPermissionChangeListeners.removeListenerLocked(listener);
4460        }
4461    }
4462
4463    @Override
4464    public boolean isProtectedBroadcast(String actionName) {
4465        synchronized (mPackages) {
4466            if (mProtectedBroadcasts.contains(actionName)) {
4467                return true;
4468            } else if (actionName != null) {
4469                // TODO: remove these terrible hacks
4470                if (actionName.startsWith("android.net.netmon.lingerExpired")
4471                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4472                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4473                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4474                    return true;
4475                }
4476            }
4477        }
4478        return false;
4479    }
4480
4481    @Override
4482    public int checkSignatures(String pkg1, String pkg2) {
4483        synchronized (mPackages) {
4484            final PackageParser.Package p1 = mPackages.get(pkg1);
4485            final PackageParser.Package p2 = mPackages.get(pkg2);
4486            if (p1 == null || p1.mExtras == null
4487                    || p2 == null || p2.mExtras == null) {
4488                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4489            }
4490            return compareSignatures(p1.mSignatures, p2.mSignatures);
4491        }
4492    }
4493
4494    @Override
4495    public int checkUidSignatures(int uid1, int uid2) {
4496        // Map to base uids.
4497        uid1 = UserHandle.getAppId(uid1);
4498        uid2 = UserHandle.getAppId(uid2);
4499        // reader
4500        synchronized (mPackages) {
4501            Signature[] s1;
4502            Signature[] s2;
4503            Object obj = mSettings.getUserIdLPr(uid1);
4504            if (obj != null) {
4505                if (obj instanceof SharedUserSetting) {
4506                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4507                } else if (obj instanceof PackageSetting) {
4508                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4509                } else {
4510                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4511                }
4512            } else {
4513                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4514            }
4515            obj = mSettings.getUserIdLPr(uid2);
4516            if (obj != null) {
4517                if (obj instanceof SharedUserSetting) {
4518                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4519                } else if (obj instanceof PackageSetting) {
4520                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4521                } else {
4522                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4523                }
4524            } else {
4525                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4526            }
4527            return compareSignatures(s1, s2);
4528        }
4529    }
4530
4531    /**
4532     * This method should typically only be used when granting or revoking
4533     * permissions, since the app may immediately restart after this call.
4534     * <p>
4535     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4536     * guard your work against the app being relaunched.
4537     */
4538    private void killUid(int appId, int userId, String reason) {
4539        final long identity = Binder.clearCallingIdentity();
4540        try {
4541            IActivityManager am = ActivityManagerNative.getDefault();
4542            if (am != null) {
4543                try {
4544                    am.killUid(appId, userId, reason);
4545                } catch (RemoteException e) {
4546                    /* ignore - same process */
4547                }
4548            }
4549        } finally {
4550            Binder.restoreCallingIdentity(identity);
4551        }
4552    }
4553
4554    /**
4555     * Compares two sets of signatures. Returns:
4556     * <br />
4557     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4558     * <br />
4559     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4560     * <br />
4561     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4562     * <br />
4563     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4564     * <br />
4565     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4566     */
4567    static int compareSignatures(Signature[] s1, Signature[] s2) {
4568        if (s1 == null) {
4569            return s2 == null
4570                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4571                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4572        }
4573
4574        if (s2 == null) {
4575            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4576        }
4577
4578        if (s1.length != s2.length) {
4579            return PackageManager.SIGNATURE_NO_MATCH;
4580        }
4581
4582        // Since both signature sets are of size 1, we can compare without HashSets.
4583        if (s1.length == 1) {
4584            return s1[0].equals(s2[0]) ?
4585                    PackageManager.SIGNATURE_MATCH :
4586                    PackageManager.SIGNATURE_NO_MATCH;
4587        }
4588
4589        ArraySet<Signature> set1 = new ArraySet<Signature>();
4590        for (Signature sig : s1) {
4591            set1.add(sig);
4592        }
4593        ArraySet<Signature> set2 = new ArraySet<Signature>();
4594        for (Signature sig : s2) {
4595            set2.add(sig);
4596        }
4597        // Make sure s2 contains all signatures in s1.
4598        if (set1.equals(set2)) {
4599            return PackageManager.SIGNATURE_MATCH;
4600        }
4601        return PackageManager.SIGNATURE_NO_MATCH;
4602    }
4603
4604    /**
4605     * If the database version for this type of package (internal storage or
4606     * external storage) is less than the version where package signatures
4607     * were updated, return true.
4608     */
4609    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4610        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4611        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4612    }
4613
4614    /**
4615     * Used for backward compatibility to make sure any packages with
4616     * certificate chains get upgraded to the new style. {@code existingSigs}
4617     * will be in the old format (since they were stored on disk from before the
4618     * system upgrade) and {@code scannedSigs} will be in the newer format.
4619     */
4620    private int compareSignaturesCompat(PackageSignatures existingSigs,
4621            PackageParser.Package scannedPkg) {
4622        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4623            return PackageManager.SIGNATURE_NO_MATCH;
4624        }
4625
4626        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4627        for (Signature sig : existingSigs.mSignatures) {
4628            existingSet.add(sig);
4629        }
4630        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4631        for (Signature sig : scannedPkg.mSignatures) {
4632            try {
4633                Signature[] chainSignatures = sig.getChainSignatures();
4634                for (Signature chainSig : chainSignatures) {
4635                    scannedCompatSet.add(chainSig);
4636                }
4637            } catch (CertificateEncodingException e) {
4638                scannedCompatSet.add(sig);
4639            }
4640        }
4641        /*
4642         * Make sure the expanded scanned set contains all signatures in the
4643         * existing one.
4644         */
4645        if (scannedCompatSet.equals(existingSet)) {
4646            // Migrate the old signatures to the new scheme.
4647            existingSigs.assignSignatures(scannedPkg.mSignatures);
4648            // The new KeySets will be re-added later in the scanning process.
4649            synchronized (mPackages) {
4650                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4651            }
4652            return PackageManager.SIGNATURE_MATCH;
4653        }
4654        return PackageManager.SIGNATURE_NO_MATCH;
4655    }
4656
4657    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4658        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4659        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4660    }
4661
4662    private int compareSignaturesRecover(PackageSignatures existingSigs,
4663            PackageParser.Package scannedPkg) {
4664        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4665            return PackageManager.SIGNATURE_NO_MATCH;
4666        }
4667
4668        String msg = null;
4669        try {
4670            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4671                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4672                        + scannedPkg.packageName);
4673                return PackageManager.SIGNATURE_MATCH;
4674            }
4675        } catch (CertificateException e) {
4676            msg = e.getMessage();
4677        }
4678
4679        logCriticalInfo(Log.INFO,
4680                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4681        return PackageManager.SIGNATURE_NO_MATCH;
4682    }
4683
4684    @Override
4685    public List<String> getAllPackages() {
4686        synchronized (mPackages) {
4687            return new ArrayList<String>(mPackages.keySet());
4688        }
4689    }
4690
4691    @Override
4692    public String[] getPackagesForUid(int uid) {
4693        final int userId = UserHandle.getUserId(uid);
4694        uid = UserHandle.getAppId(uid);
4695        // reader
4696        synchronized (mPackages) {
4697            Object obj = mSettings.getUserIdLPr(uid);
4698            if (obj instanceof SharedUserSetting) {
4699                final SharedUserSetting sus = (SharedUserSetting) obj;
4700                final int N = sus.packages.size();
4701                String[] res = new String[N];
4702                final Iterator<PackageSetting> it = sus.packages.iterator();
4703                int i = 0;
4704                while (it.hasNext()) {
4705                    PackageSetting ps = it.next();
4706                    if (ps.getInstalled(userId)) {
4707                        res[i++] = ps.name;
4708                    } else {
4709                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4710                    }
4711                }
4712                return res;
4713            } else if (obj instanceof PackageSetting) {
4714                final PackageSetting ps = (PackageSetting) obj;
4715                return new String[] { ps.name };
4716            }
4717        }
4718        return null;
4719    }
4720
4721    @Override
4722    public String getNameForUid(int uid) {
4723        // reader
4724        synchronized (mPackages) {
4725            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4726            if (obj instanceof SharedUserSetting) {
4727                final SharedUserSetting sus = (SharedUserSetting) obj;
4728                return sus.name + ":" + sus.userId;
4729            } else if (obj instanceof PackageSetting) {
4730                final PackageSetting ps = (PackageSetting) obj;
4731                return ps.name;
4732            }
4733        }
4734        return null;
4735    }
4736
4737    @Override
4738    public int getUidForSharedUser(String sharedUserName) {
4739        if(sharedUserName == null) {
4740            return -1;
4741        }
4742        // reader
4743        synchronized (mPackages) {
4744            SharedUserSetting suid;
4745            try {
4746                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4747                if (suid != null) {
4748                    return suid.userId;
4749                }
4750            } catch (PackageManagerException ignore) {
4751                // can't happen, but, still need to catch it
4752            }
4753            return -1;
4754        }
4755    }
4756
4757    @Override
4758    public int getFlagsForUid(int uid) {
4759        synchronized (mPackages) {
4760            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4761            if (obj instanceof SharedUserSetting) {
4762                final SharedUserSetting sus = (SharedUserSetting) obj;
4763                return sus.pkgFlags;
4764            } else if (obj instanceof PackageSetting) {
4765                final PackageSetting ps = (PackageSetting) obj;
4766                return ps.pkgFlags;
4767            }
4768        }
4769        return 0;
4770    }
4771
4772    @Override
4773    public int getPrivateFlagsForUid(int uid) {
4774        synchronized (mPackages) {
4775            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4776            if (obj instanceof SharedUserSetting) {
4777                final SharedUserSetting sus = (SharedUserSetting) obj;
4778                return sus.pkgPrivateFlags;
4779            } else if (obj instanceof PackageSetting) {
4780                final PackageSetting ps = (PackageSetting) obj;
4781                return ps.pkgPrivateFlags;
4782            }
4783        }
4784        return 0;
4785    }
4786
4787    @Override
4788    public boolean isUidPrivileged(int uid) {
4789        uid = UserHandle.getAppId(uid);
4790        // reader
4791        synchronized (mPackages) {
4792            Object obj = mSettings.getUserIdLPr(uid);
4793            if (obj instanceof SharedUserSetting) {
4794                final SharedUserSetting sus = (SharedUserSetting) obj;
4795                final Iterator<PackageSetting> it = sus.packages.iterator();
4796                while (it.hasNext()) {
4797                    if (it.next().isPrivileged()) {
4798                        return true;
4799                    }
4800                }
4801            } else if (obj instanceof PackageSetting) {
4802                final PackageSetting ps = (PackageSetting) obj;
4803                return ps.isPrivileged();
4804            }
4805        }
4806        return false;
4807    }
4808
4809    @Override
4810    public String[] getAppOpPermissionPackages(String permissionName) {
4811        synchronized (mPackages) {
4812            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4813            if (pkgs == null) {
4814                return null;
4815            }
4816            return pkgs.toArray(new String[pkgs.size()]);
4817        }
4818    }
4819
4820    @Override
4821    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4822            int flags, int userId) {
4823        try {
4824            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4825
4826            if (!sUserManager.exists(userId)) return null;
4827            flags = updateFlagsForResolve(flags, userId, intent);
4828            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4829                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4830
4831            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4832            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4833                    flags, userId);
4834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4835
4836            final ResolveInfo bestChoice =
4837                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4838            return bestChoice;
4839        } finally {
4840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4841        }
4842    }
4843
4844    @Override
4845    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4846            IntentFilter filter, int match, ComponentName activity) {
4847        final int userId = UserHandle.getCallingUserId();
4848        if (DEBUG_PREFERRED) {
4849            Log.v(TAG, "setLastChosenActivity intent=" + intent
4850                + " resolvedType=" + resolvedType
4851                + " flags=" + flags
4852                + " filter=" + filter
4853                + " match=" + match
4854                + " activity=" + activity);
4855            filter.dump(new PrintStreamPrinter(System.out), "    ");
4856        }
4857        intent.setComponent(null);
4858        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4859                userId);
4860        // Find any earlier preferred or last chosen entries and nuke them
4861        findPreferredActivity(intent, resolvedType,
4862                flags, query, 0, false, true, false, userId);
4863        // Add the new activity as the last chosen for this filter
4864        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4865                "Setting last chosen");
4866    }
4867
4868    @Override
4869    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4870        final int userId = UserHandle.getCallingUserId();
4871        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4872        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4873                userId);
4874        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4875                false, false, false, userId);
4876    }
4877
4878    private boolean isEphemeralDisabled() {
4879        // ephemeral apps have been disabled across the board
4880        if (DISABLE_EPHEMERAL_APPS) {
4881            return true;
4882        }
4883        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4884        if (!mSystemReady) {
4885            return true;
4886        }
4887        // we can't get a content resolver until the system is ready; these checks must happen last
4888        final ContentResolver resolver = mContext.getContentResolver();
4889        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4890            return true;
4891        }
4892        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4893    }
4894
4895    private boolean isEphemeralAllowed(
4896            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4897            boolean skipPackageCheck) {
4898        // Short circuit and return early if possible.
4899        if (isEphemeralDisabled()) {
4900            return false;
4901        }
4902        final int callingUser = UserHandle.getCallingUserId();
4903        if (callingUser != UserHandle.USER_SYSTEM) {
4904            return false;
4905        }
4906        if (mEphemeralResolverConnection == null) {
4907            return false;
4908        }
4909        if (intent.getComponent() != null) {
4910            return false;
4911        }
4912        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4913            return false;
4914        }
4915        if (!skipPackageCheck && intent.getPackage() != null) {
4916            return false;
4917        }
4918        final boolean isWebUri = hasWebURI(intent);
4919        if (!isWebUri || intent.getData().getHost() == null) {
4920            return false;
4921        }
4922        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4923        synchronized (mPackages) {
4924            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4925            for (int n = 0; n < count; n++) {
4926                ResolveInfo info = resolvedActivities.get(n);
4927                String packageName = info.activityInfo.packageName;
4928                PackageSetting ps = mSettings.mPackages.get(packageName);
4929                if (ps != null) {
4930                    // Try to get the status from User settings first
4931                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4932                    int status = (int) (packedStatus >> 32);
4933                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4934                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4935                        if (DEBUG_EPHEMERAL) {
4936                            Slog.v(TAG, "DENY ephemeral apps;"
4937                                + " pkg: " + packageName + ", status: " + status);
4938                        }
4939                        return false;
4940                    }
4941                }
4942            }
4943        }
4944        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4945        return true;
4946    }
4947
4948    private static EphemeralResolveIntentInfo getEphemeralIntentInfo(
4949            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4950            String resolvedType, int userId, String packageName) {
4951        final EphemeralDigest digest =
4952                new EphemeralDigest(intent.getData().getHost(), 5 /*maxDigests*/);
4953        final int[] shaPrefix = digest.getDigestPrefix();
4954        final byte[][] digestBytes = digest.getDigestBytes();
4955        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4956                resolverConnection.getEphemeralResolveInfoList(shaPrefix);
4957        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4958            // No hash prefix match; there are no ephemeral apps for this domain.
4959            return null;
4960        }
4961
4962        // Go in reverse order so we match the narrowest scope first.
4963        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4964            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4965                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4966                    continue;
4967                }
4968                final List<EphemeralIntentFilter> ephemeralFilters =
4969                        ephemeralApplication.getIntentFilters();
4970                // No filters; this should never happen.
4971                if (ephemeralFilters.isEmpty()) {
4972                    continue;
4973                }
4974                if (packageName != null
4975                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4976                    continue;
4977                }
4978                // We have a domain match; resolve the filters to see if anything matches.
4979                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4980                for (int j = ephemeralFilters.size() - 1; j >= 0; --j) {
4981                    final EphemeralIntentFilter ephemeralFilter = ephemeralFilters.get(j);
4982                    final List<IntentFilter> splitFilters = ephemeralFilter.getFilters();
4983                    if (splitFilters == null || splitFilters.isEmpty()) {
4984                        continue;
4985                    }
4986                    for (int k = splitFilters.size() - 1; k >= 0; --k) {
4987                        final EphemeralResolveIntentInfo intentInfo =
4988                                new EphemeralResolveIntentInfo(splitFilters.get(k),
4989                                        ephemeralApplication, ephemeralFilter.getSplitName());
4990                        ephemeralResolver.addFilter(intentInfo);
4991                    }
4992                }
4993                List<EphemeralResolveIntentInfo> matchedResolveInfoList = ephemeralResolver
4994                        .queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
4995                if (!matchedResolveInfoList.isEmpty()) {
4996                    return matchedResolveInfoList.get(0);
4997                }
4998            }
4999        }
5000        // Hash or filter mis-match; no ephemeral apps for this domain.
5001        return null;
5002    }
5003
5004    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5005            int flags, List<ResolveInfo> query, int userId) {
5006        if (query != null) {
5007            final int N = query.size();
5008            if (N == 1) {
5009                return query.get(0);
5010            } else if (N > 1) {
5011                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5012                // If there is more than one activity with the same priority,
5013                // then let the user decide between them.
5014                ResolveInfo r0 = query.get(0);
5015                ResolveInfo r1 = query.get(1);
5016                if (DEBUG_INTENT_MATCHING || debug) {
5017                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5018                            + r1.activityInfo.name + "=" + r1.priority);
5019                }
5020                // If the first activity has a higher priority, or a different
5021                // default, then it is always desirable to pick it.
5022                if (r0.priority != r1.priority
5023                        || r0.preferredOrder != r1.preferredOrder
5024                        || r0.isDefault != r1.isDefault) {
5025                    return query.get(0);
5026                }
5027                // If we have saved a preference for a preferred activity for
5028                // this Intent, use that.
5029                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5030                        flags, query, r0.priority, true, false, debug, userId);
5031                if (ri != null) {
5032                    return ri;
5033                }
5034                ri = new ResolveInfo(mResolveInfo);
5035                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5036                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5037                // If all of the options come from the same package, show the application's
5038                // label and icon instead of the generic resolver's.
5039                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5040                // and then throw away the ResolveInfo itself, meaning that the caller loses
5041                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5042                // a fallback for this case; we only set the target package's resources on
5043                // the ResolveInfo, not the ActivityInfo.
5044                final String intentPackage = intent.getPackage();
5045                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5046                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5047                    ri.resolvePackageName = intentPackage;
5048                    if (userNeedsBadging(userId)) {
5049                        ri.noResourceId = true;
5050                    } else {
5051                        ri.icon = appi.icon;
5052                    }
5053                    ri.iconResourceId = appi.icon;
5054                    ri.labelRes = appi.labelRes;
5055                }
5056                ri.activityInfo.applicationInfo = new ApplicationInfo(
5057                        ri.activityInfo.applicationInfo);
5058                if (userId != 0) {
5059                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5060                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5061                }
5062                // Make sure that the resolver is displayable in car mode
5063                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5064                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5065                return ri;
5066            }
5067        }
5068        return null;
5069    }
5070
5071    /**
5072     * Return true if the given list is not empty and all of its contents have
5073     * an activityInfo with the given package name.
5074     */
5075    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5076        if (ArrayUtils.isEmpty(list)) {
5077            return false;
5078        }
5079        for (int i = 0, N = list.size(); i < N; i++) {
5080            final ResolveInfo ri = list.get(i);
5081            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5082            if (ai == null || !packageName.equals(ai.packageName)) {
5083                return false;
5084            }
5085        }
5086        return true;
5087    }
5088
5089    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5090            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5091        final int N = query.size();
5092        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5093                .get(userId);
5094        // Get the list of persistent preferred activities that handle the intent
5095        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5096        List<PersistentPreferredActivity> pprefs = ppir != null
5097                ? ppir.queryIntent(intent, resolvedType,
5098                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5099                : null;
5100        if (pprefs != null && pprefs.size() > 0) {
5101            final int M = pprefs.size();
5102            for (int i=0; i<M; i++) {
5103                final PersistentPreferredActivity ppa = pprefs.get(i);
5104                if (DEBUG_PREFERRED || debug) {
5105                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5106                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5107                            + "\n  component=" + ppa.mComponent);
5108                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5109                }
5110                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5111                        flags | MATCH_DISABLED_COMPONENTS, userId);
5112                if (DEBUG_PREFERRED || debug) {
5113                    Slog.v(TAG, "Found persistent preferred activity:");
5114                    if (ai != null) {
5115                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5116                    } else {
5117                        Slog.v(TAG, "  null");
5118                    }
5119                }
5120                if (ai == null) {
5121                    // This previously registered persistent preferred activity
5122                    // component is no longer known. Ignore it and do NOT remove it.
5123                    continue;
5124                }
5125                for (int j=0; j<N; j++) {
5126                    final ResolveInfo ri = query.get(j);
5127                    if (!ri.activityInfo.applicationInfo.packageName
5128                            .equals(ai.applicationInfo.packageName)) {
5129                        continue;
5130                    }
5131                    if (!ri.activityInfo.name.equals(ai.name)) {
5132                        continue;
5133                    }
5134                    //  Found a persistent preference that can handle the intent.
5135                    if (DEBUG_PREFERRED || debug) {
5136                        Slog.v(TAG, "Returning persistent preferred activity: " +
5137                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5138                    }
5139                    return ri;
5140                }
5141            }
5142        }
5143        return null;
5144    }
5145
5146    // TODO: handle preferred activities missing while user has amnesia
5147    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5148            List<ResolveInfo> query, int priority, boolean always,
5149            boolean removeMatches, boolean debug, int userId) {
5150        if (!sUserManager.exists(userId)) return null;
5151        flags = updateFlagsForResolve(flags, userId, intent);
5152        // writer
5153        synchronized (mPackages) {
5154            if (intent.getSelector() != null) {
5155                intent = intent.getSelector();
5156            }
5157            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5158
5159            // Try to find a matching persistent preferred activity.
5160            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5161                    debug, userId);
5162
5163            // If a persistent preferred activity matched, use it.
5164            if (pri != null) {
5165                return pri;
5166            }
5167
5168            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5169            // Get the list of preferred activities that handle the intent
5170            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5171            List<PreferredActivity> prefs = pir != null
5172                    ? pir.queryIntent(intent, resolvedType,
5173                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5174                    : null;
5175            if (prefs != null && prefs.size() > 0) {
5176                boolean changed = false;
5177                try {
5178                    // First figure out how good the original match set is.
5179                    // We will only allow preferred activities that came
5180                    // from the same match quality.
5181                    int match = 0;
5182
5183                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5184
5185                    final int N = query.size();
5186                    for (int j=0; j<N; j++) {
5187                        final ResolveInfo ri = query.get(j);
5188                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5189                                + ": 0x" + Integer.toHexString(match));
5190                        if (ri.match > match) {
5191                            match = ri.match;
5192                        }
5193                    }
5194
5195                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5196                            + Integer.toHexString(match));
5197
5198                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5199                    final int M = prefs.size();
5200                    for (int i=0; i<M; i++) {
5201                        final PreferredActivity pa = prefs.get(i);
5202                        if (DEBUG_PREFERRED || debug) {
5203                            Slog.v(TAG, "Checking PreferredActivity ds="
5204                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5205                                    + "\n  component=" + pa.mPref.mComponent);
5206                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5207                        }
5208                        if (pa.mPref.mMatch != match) {
5209                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5210                                    + Integer.toHexString(pa.mPref.mMatch));
5211                            continue;
5212                        }
5213                        // If it's not an "always" type preferred activity and that's what we're
5214                        // looking for, skip it.
5215                        if (always && !pa.mPref.mAlways) {
5216                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5217                            continue;
5218                        }
5219                        final ActivityInfo ai = getActivityInfo(
5220                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5221                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5222                                userId);
5223                        if (DEBUG_PREFERRED || debug) {
5224                            Slog.v(TAG, "Found preferred activity:");
5225                            if (ai != null) {
5226                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5227                            } else {
5228                                Slog.v(TAG, "  null");
5229                            }
5230                        }
5231                        if (ai == null) {
5232                            // This previously registered preferred activity
5233                            // component is no longer known.  Most likely an update
5234                            // to the app was installed and in the new version this
5235                            // component no longer exists.  Clean it up by removing
5236                            // it from the preferred activities list, and skip it.
5237                            Slog.w(TAG, "Removing dangling preferred activity: "
5238                                    + pa.mPref.mComponent);
5239                            pir.removeFilter(pa);
5240                            changed = true;
5241                            continue;
5242                        }
5243                        for (int j=0; j<N; j++) {
5244                            final ResolveInfo ri = query.get(j);
5245                            if (!ri.activityInfo.applicationInfo.packageName
5246                                    .equals(ai.applicationInfo.packageName)) {
5247                                continue;
5248                            }
5249                            if (!ri.activityInfo.name.equals(ai.name)) {
5250                                continue;
5251                            }
5252
5253                            if (removeMatches) {
5254                                pir.removeFilter(pa);
5255                                changed = true;
5256                                if (DEBUG_PREFERRED) {
5257                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5258                                }
5259                                break;
5260                            }
5261
5262                            // Okay we found a previously set preferred or last chosen app.
5263                            // If the result set is different from when this
5264                            // was created, we need to clear it and re-ask the
5265                            // user their preference, if we're looking for an "always" type entry.
5266                            if (always && !pa.mPref.sameSet(query)) {
5267                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5268                                        + intent + " type " + resolvedType);
5269                                if (DEBUG_PREFERRED) {
5270                                    Slog.v(TAG, "Removing preferred activity since set changed "
5271                                            + pa.mPref.mComponent);
5272                                }
5273                                pir.removeFilter(pa);
5274                                // Re-add the filter as a "last chosen" entry (!always)
5275                                PreferredActivity lastChosen = new PreferredActivity(
5276                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5277                                pir.addFilter(lastChosen);
5278                                changed = true;
5279                                return null;
5280                            }
5281
5282                            // Yay! Either the set matched or we're looking for the last chosen
5283                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5284                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5285                            return ri;
5286                        }
5287                    }
5288                } finally {
5289                    if (changed) {
5290                        if (DEBUG_PREFERRED) {
5291                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5292                        }
5293                        scheduleWritePackageRestrictionsLocked(userId);
5294                    }
5295                }
5296            }
5297        }
5298        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5299        return null;
5300    }
5301
5302    /*
5303     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5304     */
5305    @Override
5306    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5307            int targetUserId) {
5308        mContext.enforceCallingOrSelfPermission(
5309                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5310        List<CrossProfileIntentFilter> matches =
5311                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5312        if (matches != null) {
5313            int size = matches.size();
5314            for (int i = 0; i < size; i++) {
5315                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5316            }
5317        }
5318        if (hasWebURI(intent)) {
5319            // cross-profile app linking works only towards the parent.
5320            final UserInfo parent = getProfileParent(sourceUserId);
5321            synchronized(mPackages) {
5322                int flags = updateFlagsForResolve(0, parent.id, intent);
5323                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5324                        intent, resolvedType, flags, sourceUserId, parent.id);
5325                return xpDomainInfo != null;
5326            }
5327        }
5328        return false;
5329    }
5330
5331    private UserInfo getProfileParent(int userId) {
5332        final long identity = Binder.clearCallingIdentity();
5333        try {
5334            return sUserManager.getProfileParent(userId);
5335        } finally {
5336            Binder.restoreCallingIdentity(identity);
5337        }
5338    }
5339
5340    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5341            String resolvedType, int userId) {
5342        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5343        if (resolver != null) {
5344            return resolver.queryIntent(intent, resolvedType, false, userId);
5345        }
5346        return null;
5347    }
5348
5349    @Override
5350    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5351            String resolvedType, int flags, int userId) {
5352        try {
5353            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5354
5355            return new ParceledListSlice<>(
5356                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5357        } finally {
5358            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5359        }
5360    }
5361
5362    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5363            String resolvedType, int flags, int userId) {
5364        if (!sUserManager.exists(userId)) return Collections.emptyList();
5365        flags = updateFlagsForResolve(flags, userId, intent);
5366        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5367                false /* requireFullPermission */, false /* checkShell */,
5368                "query intent activities");
5369        ComponentName comp = intent.getComponent();
5370        if (comp == null) {
5371            if (intent.getSelector() != null) {
5372                intent = intent.getSelector();
5373                comp = intent.getComponent();
5374            }
5375        }
5376
5377        if (comp != null) {
5378            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5379            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5380            if (ai != null) {
5381                final ResolveInfo ri = new ResolveInfo();
5382                ri.activityInfo = ai;
5383                list.add(ri);
5384            }
5385            return list;
5386        }
5387
5388        // reader
5389        boolean sortResult = false;
5390        boolean addEphemeral = false;
5391        boolean matchEphemeralPackage = false;
5392        List<ResolveInfo> result;
5393        final String pkgName = intent.getPackage();
5394        synchronized (mPackages) {
5395            if (pkgName == null) {
5396                List<CrossProfileIntentFilter> matchingFilters =
5397                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5398                // Check for results that need to skip the current profile.
5399                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5400                        resolvedType, flags, userId);
5401                if (xpResolveInfo != null) {
5402                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5403                    xpResult.add(xpResolveInfo);
5404                    return filterIfNotSystemUser(xpResult, userId);
5405                }
5406
5407                // Check for results in the current profile.
5408                result = filterIfNotSystemUser(mActivities.queryIntent(
5409                        intent, resolvedType, flags, userId), userId);
5410                addEphemeral =
5411                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5412
5413                // Check for cross profile results.
5414                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5415                xpResolveInfo = queryCrossProfileIntents(
5416                        matchingFilters, intent, resolvedType, flags, userId,
5417                        hasNonNegativePriorityResult);
5418                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5419                    boolean isVisibleToUser = filterIfNotSystemUser(
5420                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5421                    if (isVisibleToUser) {
5422                        result.add(xpResolveInfo);
5423                        sortResult = true;
5424                    }
5425                }
5426                if (hasWebURI(intent)) {
5427                    CrossProfileDomainInfo xpDomainInfo = null;
5428                    final UserInfo parent = getProfileParent(userId);
5429                    if (parent != null) {
5430                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5431                                flags, userId, parent.id);
5432                    }
5433                    if (xpDomainInfo != null) {
5434                        if (xpResolveInfo != null) {
5435                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5436                            // in the result.
5437                            result.remove(xpResolveInfo);
5438                        }
5439                        if (result.size() == 0 && !addEphemeral) {
5440                            // No result in current profile, but found candidate in parent user.
5441                            // And we are not going to add emphemeral app, so we can return the
5442                            // result straight away.
5443                            result.add(xpDomainInfo.resolveInfo);
5444                            return result;
5445                        }
5446                    } else if (result.size() <= 1 && !addEphemeral) {
5447                        // No result in parent user and <= 1 result in current profile, and we
5448                        // are not going to add emphemeral app, so we can return the result without
5449                        // further processing.
5450                        return result;
5451                    }
5452                    // We have more than one candidate (combining results from current and parent
5453                    // profile), so we need filtering and sorting.
5454                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5455                            intent, flags, result, xpDomainInfo, userId);
5456                    sortResult = true;
5457                }
5458            } else {
5459                final PackageParser.Package pkg = mPackages.get(pkgName);
5460                if (pkg != null) {
5461                    result = filterIfNotSystemUser(
5462                            mActivities.queryIntentForPackage(
5463                                    intent, resolvedType, flags, pkg.activities, userId),
5464                            userId);
5465                } else {
5466                    // the caller wants to resolve for a particular package; however, there
5467                    // were no installed results, so, try to find an ephemeral result
5468                    addEphemeral = isEphemeralAllowed(
5469                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5470                    matchEphemeralPackage = true;
5471                    result = new ArrayList<ResolveInfo>();
5472                }
5473            }
5474        }
5475        if (addEphemeral) {
5476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5477            final EphemeralResolveIntentInfo intentInfo = getEphemeralIntentInfo(
5478                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5479                    matchEphemeralPackage ? pkgName : null);
5480            if (intentInfo != null) {
5481                if (DEBUG_EPHEMERAL) {
5482                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5483                }
5484                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5485                ephemeralInstaller.ephemeralIntentInfo = intentInfo;
5486                // make sure this resolver is the default
5487                ephemeralInstaller.isDefault = true;
5488                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5489                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5490                // add a non-generic filter
5491                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5492                ephemeralInstaller.filter.addDataPath(
5493                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5494                result.add(ephemeralInstaller);
5495            }
5496            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5497        }
5498        if (sortResult) {
5499            Collections.sort(result, mResolvePrioritySorter);
5500        }
5501        return result;
5502    }
5503
5504    private static class CrossProfileDomainInfo {
5505        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5506        ResolveInfo resolveInfo;
5507        /* Best domain verification status of the activities found in the other profile */
5508        int bestDomainVerificationStatus;
5509    }
5510
5511    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5512            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5513        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5514                sourceUserId)) {
5515            return null;
5516        }
5517        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5518                resolvedType, flags, parentUserId);
5519
5520        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5521            return null;
5522        }
5523        CrossProfileDomainInfo result = null;
5524        int size = resultTargetUser.size();
5525        for (int i = 0; i < size; i++) {
5526            ResolveInfo riTargetUser = resultTargetUser.get(i);
5527            // Intent filter verification is only for filters that specify a host. So don't return
5528            // those that handle all web uris.
5529            if (riTargetUser.handleAllWebDataURI) {
5530                continue;
5531            }
5532            String packageName = riTargetUser.activityInfo.packageName;
5533            PackageSetting ps = mSettings.mPackages.get(packageName);
5534            if (ps == null) {
5535                continue;
5536            }
5537            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5538            int status = (int)(verificationState >> 32);
5539            if (result == null) {
5540                result = new CrossProfileDomainInfo();
5541                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5542                        sourceUserId, parentUserId);
5543                result.bestDomainVerificationStatus = status;
5544            } else {
5545                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5546                        result.bestDomainVerificationStatus);
5547            }
5548        }
5549        // Don't consider matches with status NEVER across profiles.
5550        if (result != null && result.bestDomainVerificationStatus
5551                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5552            return null;
5553        }
5554        return result;
5555    }
5556
5557    /**
5558     * Verification statuses are ordered from the worse to the best, except for
5559     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5560     */
5561    private int bestDomainVerificationStatus(int status1, int status2) {
5562        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5563            return status2;
5564        }
5565        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5566            return status1;
5567        }
5568        return (int) MathUtils.max(status1, status2);
5569    }
5570
5571    private boolean isUserEnabled(int userId) {
5572        long callingId = Binder.clearCallingIdentity();
5573        try {
5574            UserInfo userInfo = sUserManager.getUserInfo(userId);
5575            return userInfo != null && userInfo.isEnabled();
5576        } finally {
5577            Binder.restoreCallingIdentity(callingId);
5578        }
5579    }
5580
5581    /**
5582     * Filter out activities with systemUserOnly flag set, when current user is not System.
5583     *
5584     * @return filtered list
5585     */
5586    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5587        if (userId == UserHandle.USER_SYSTEM) {
5588            return resolveInfos;
5589        }
5590        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5591            ResolveInfo info = resolveInfos.get(i);
5592            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5593                resolveInfos.remove(i);
5594            }
5595        }
5596        return resolveInfos;
5597    }
5598
5599    /**
5600     * @param resolveInfos list of resolve infos in descending priority order
5601     * @return if the list contains a resolve info with non-negative priority
5602     */
5603    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5604        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5605    }
5606
5607    private static boolean hasWebURI(Intent intent) {
5608        if (intent.getData() == null) {
5609            return false;
5610        }
5611        final String scheme = intent.getScheme();
5612        if (TextUtils.isEmpty(scheme)) {
5613            return false;
5614        }
5615        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5616    }
5617
5618    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5619            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5620            int userId) {
5621        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5622
5623        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5624            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5625                    candidates.size());
5626        }
5627
5628        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5629        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5630        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5631        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5632        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5633        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5634
5635        synchronized (mPackages) {
5636            final int count = candidates.size();
5637            // First, try to use linked apps. Partition the candidates into four lists:
5638            // one for the final results, one for the "do not use ever", one for "undefined status"
5639            // and finally one for "browser app type".
5640            for (int n=0; n<count; n++) {
5641                ResolveInfo info = candidates.get(n);
5642                String packageName = info.activityInfo.packageName;
5643                PackageSetting ps = mSettings.mPackages.get(packageName);
5644                if (ps != null) {
5645                    // Add to the special match all list (Browser use case)
5646                    if (info.handleAllWebDataURI) {
5647                        matchAllList.add(info);
5648                        continue;
5649                    }
5650                    // Try to get the status from User settings first
5651                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5652                    int status = (int)(packedStatus >> 32);
5653                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5654                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5655                        if (DEBUG_DOMAIN_VERIFICATION) {
5656                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5657                                    + " : linkgen=" + linkGeneration);
5658                        }
5659                        // Use link-enabled generation as preferredOrder, i.e.
5660                        // prefer newly-enabled over earlier-enabled.
5661                        info.preferredOrder = linkGeneration;
5662                        alwaysList.add(info);
5663                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5664                        if (DEBUG_DOMAIN_VERIFICATION) {
5665                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5666                        }
5667                        neverList.add(info);
5668                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5669                        if (DEBUG_DOMAIN_VERIFICATION) {
5670                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5671                        }
5672                        alwaysAskList.add(info);
5673                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5674                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5675                        if (DEBUG_DOMAIN_VERIFICATION) {
5676                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5677                        }
5678                        undefinedList.add(info);
5679                    }
5680                }
5681            }
5682
5683            // We'll want to include browser possibilities in a few cases
5684            boolean includeBrowser = false;
5685
5686            // First try to add the "always" resolution(s) for the current user, if any
5687            if (alwaysList.size() > 0) {
5688                result.addAll(alwaysList);
5689            } else {
5690                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5691                result.addAll(undefinedList);
5692                // Maybe add one for the other profile.
5693                if (xpDomainInfo != null && (
5694                        xpDomainInfo.bestDomainVerificationStatus
5695                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5696                    result.add(xpDomainInfo.resolveInfo);
5697                }
5698                includeBrowser = true;
5699            }
5700
5701            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5702            // If there were 'always' entries their preferred order has been set, so we also
5703            // back that off to make the alternatives equivalent
5704            if (alwaysAskList.size() > 0) {
5705                for (ResolveInfo i : result) {
5706                    i.preferredOrder = 0;
5707                }
5708                result.addAll(alwaysAskList);
5709                includeBrowser = true;
5710            }
5711
5712            if (includeBrowser) {
5713                // Also add browsers (all of them or only the default one)
5714                if (DEBUG_DOMAIN_VERIFICATION) {
5715                    Slog.v(TAG, "   ...including browsers in candidate set");
5716                }
5717                if ((matchFlags & MATCH_ALL) != 0) {
5718                    result.addAll(matchAllList);
5719                } else {
5720                    // Browser/generic handling case.  If there's a default browser, go straight
5721                    // to that (but only if there is no other higher-priority match).
5722                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5723                    int maxMatchPrio = 0;
5724                    ResolveInfo defaultBrowserMatch = null;
5725                    final int numCandidates = matchAllList.size();
5726                    for (int n = 0; n < numCandidates; n++) {
5727                        ResolveInfo info = matchAllList.get(n);
5728                        // track the highest overall match priority...
5729                        if (info.priority > maxMatchPrio) {
5730                            maxMatchPrio = info.priority;
5731                        }
5732                        // ...and the highest-priority default browser match
5733                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5734                            if (defaultBrowserMatch == null
5735                                    || (defaultBrowserMatch.priority < info.priority)) {
5736                                if (debug) {
5737                                    Slog.v(TAG, "Considering default browser match " + info);
5738                                }
5739                                defaultBrowserMatch = info;
5740                            }
5741                        }
5742                    }
5743                    if (defaultBrowserMatch != null
5744                            && defaultBrowserMatch.priority >= maxMatchPrio
5745                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5746                    {
5747                        if (debug) {
5748                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5749                        }
5750                        result.add(defaultBrowserMatch);
5751                    } else {
5752                        result.addAll(matchAllList);
5753                    }
5754                }
5755
5756                // If there is nothing selected, add all candidates and remove the ones that the user
5757                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5758                if (result.size() == 0) {
5759                    result.addAll(candidates);
5760                    result.removeAll(neverList);
5761                }
5762            }
5763        }
5764        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5765            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5766                    result.size());
5767            for (ResolveInfo info : result) {
5768                Slog.v(TAG, "  + " + info.activityInfo);
5769            }
5770        }
5771        return result;
5772    }
5773
5774    // Returns a packed value as a long:
5775    //
5776    // high 'int'-sized word: link status: undefined/ask/never/always.
5777    // low 'int'-sized word: relative priority among 'always' results.
5778    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5779        long result = ps.getDomainVerificationStatusForUser(userId);
5780        // if none available, get the master status
5781        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5782            if (ps.getIntentFilterVerificationInfo() != null) {
5783                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5784            }
5785        }
5786        return result;
5787    }
5788
5789    private ResolveInfo querySkipCurrentProfileIntents(
5790            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5791            int flags, int sourceUserId) {
5792        if (matchingFilters != null) {
5793            int size = matchingFilters.size();
5794            for (int i = 0; i < size; i ++) {
5795                CrossProfileIntentFilter filter = matchingFilters.get(i);
5796                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5797                    // Checking if there are activities in the target user that can handle the
5798                    // intent.
5799                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5800                            resolvedType, flags, sourceUserId);
5801                    if (resolveInfo != null) {
5802                        return resolveInfo;
5803                    }
5804                }
5805            }
5806        }
5807        return null;
5808    }
5809
5810    // Return matching ResolveInfo in target user if any.
5811    private ResolveInfo queryCrossProfileIntents(
5812            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5813            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5814        if (matchingFilters != null) {
5815            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5816            // match the same intent. For performance reasons, it is better not to
5817            // run queryIntent twice for the same userId
5818            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5819            int size = matchingFilters.size();
5820            for (int i = 0; i < size; i++) {
5821                CrossProfileIntentFilter filter = matchingFilters.get(i);
5822                int targetUserId = filter.getTargetUserId();
5823                boolean skipCurrentProfile =
5824                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5825                boolean skipCurrentProfileIfNoMatchFound =
5826                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5827                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5828                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5829                    // Checking if there are activities in the target user that can handle the
5830                    // intent.
5831                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5832                            resolvedType, flags, sourceUserId);
5833                    if (resolveInfo != null) return resolveInfo;
5834                    alreadyTriedUserIds.put(targetUserId, true);
5835                }
5836            }
5837        }
5838        return null;
5839    }
5840
5841    /**
5842     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5843     * will forward the intent to the filter's target user.
5844     * Otherwise, returns null.
5845     */
5846    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5847            String resolvedType, int flags, int sourceUserId) {
5848        int targetUserId = filter.getTargetUserId();
5849        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5850                resolvedType, flags, targetUserId);
5851        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5852            // If all the matches in the target profile are suspended, return null.
5853            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5854                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5855                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5856                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5857                            targetUserId);
5858                }
5859            }
5860        }
5861        return null;
5862    }
5863
5864    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5865            int sourceUserId, int targetUserId) {
5866        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5867        long ident = Binder.clearCallingIdentity();
5868        boolean targetIsProfile;
5869        try {
5870            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5871        } finally {
5872            Binder.restoreCallingIdentity(ident);
5873        }
5874        String className;
5875        if (targetIsProfile) {
5876            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5877        } else {
5878            className = FORWARD_INTENT_TO_PARENT;
5879        }
5880        ComponentName forwardingActivityComponentName = new ComponentName(
5881                mAndroidApplication.packageName, className);
5882        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5883                sourceUserId);
5884        if (!targetIsProfile) {
5885            forwardingActivityInfo.showUserIcon = targetUserId;
5886            forwardingResolveInfo.noResourceId = true;
5887        }
5888        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5889        forwardingResolveInfo.priority = 0;
5890        forwardingResolveInfo.preferredOrder = 0;
5891        forwardingResolveInfo.match = 0;
5892        forwardingResolveInfo.isDefault = true;
5893        forwardingResolveInfo.filter = filter;
5894        forwardingResolveInfo.targetUserId = targetUserId;
5895        return forwardingResolveInfo;
5896    }
5897
5898    @Override
5899    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5900            Intent[] specifics, String[] specificTypes, Intent intent,
5901            String resolvedType, int flags, int userId) {
5902        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5903                specificTypes, intent, resolvedType, flags, userId));
5904    }
5905
5906    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5907            Intent[] specifics, String[] specificTypes, Intent intent,
5908            String resolvedType, int flags, int userId) {
5909        if (!sUserManager.exists(userId)) return Collections.emptyList();
5910        flags = updateFlagsForResolve(flags, userId, intent);
5911        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5912                false /* requireFullPermission */, false /* checkShell */,
5913                "query intent activity options");
5914        final String resultsAction = intent.getAction();
5915
5916        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5917                | PackageManager.GET_RESOLVED_FILTER, userId);
5918
5919        if (DEBUG_INTENT_MATCHING) {
5920            Log.v(TAG, "Query " + intent + ": " + results);
5921        }
5922
5923        int specificsPos = 0;
5924        int N;
5925
5926        // todo: note that the algorithm used here is O(N^2).  This
5927        // isn't a problem in our current environment, but if we start running
5928        // into situations where we have more than 5 or 10 matches then this
5929        // should probably be changed to something smarter...
5930
5931        // First we go through and resolve each of the specific items
5932        // that were supplied, taking care of removing any corresponding
5933        // duplicate items in the generic resolve list.
5934        if (specifics != null) {
5935            for (int i=0; i<specifics.length; i++) {
5936                final Intent sintent = specifics[i];
5937                if (sintent == null) {
5938                    continue;
5939                }
5940
5941                if (DEBUG_INTENT_MATCHING) {
5942                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5943                }
5944
5945                String action = sintent.getAction();
5946                if (resultsAction != null && resultsAction.equals(action)) {
5947                    // If this action was explicitly requested, then don't
5948                    // remove things that have it.
5949                    action = null;
5950                }
5951
5952                ResolveInfo ri = null;
5953                ActivityInfo ai = null;
5954
5955                ComponentName comp = sintent.getComponent();
5956                if (comp == null) {
5957                    ri = resolveIntent(
5958                        sintent,
5959                        specificTypes != null ? specificTypes[i] : null,
5960                            flags, userId);
5961                    if (ri == null) {
5962                        continue;
5963                    }
5964                    if (ri == mResolveInfo) {
5965                        // ACK!  Must do something better with this.
5966                    }
5967                    ai = ri.activityInfo;
5968                    comp = new ComponentName(ai.applicationInfo.packageName,
5969                            ai.name);
5970                } else {
5971                    ai = getActivityInfo(comp, flags, userId);
5972                    if (ai == null) {
5973                        continue;
5974                    }
5975                }
5976
5977                // Look for any generic query activities that are duplicates
5978                // of this specific one, and remove them from the results.
5979                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5980                N = results.size();
5981                int j;
5982                for (j=specificsPos; j<N; j++) {
5983                    ResolveInfo sri = results.get(j);
5984                    if ((sri.activityInfo.name.equals(comp.getClassName())
5985                            && sri.activityInfo.applicationInfo.packageName.equals(
5986                                    comp.getPackageName()))
5987                        || (action != null && sri.filter.matchAction(action))) {
5988                        results.remove(j);
5989                        if (DEBUG_INTENT_MATCHING) Log.v(
5990                            TAG, "Removing duplicate item from " + j
5991                            + " due to specific " + specificsPos);
5992                        if (ri == null) {
5993                            ri = sri;
5994                        }
5995                        j--;
5996                        N--;
5997                    }
5998                }
5999
6000                // Add this specific item to its proper place.
6001                if (ri == null) {
6002                    ri = new ResolveInfo();
6003                    ri.activityInfo = ai;
6004                }
6005                results.add(specificsPos, ri);
6006                ri.specificIndex = i;
6007                specificsPos++;
6008            }
6009        }
6010
6011        // Now we go through the remaining generic results and remove any
6012        // duplicate actions that are found here.
6013        N = results.size();
6014        for (int i=specificsPos; i<N-1; i++) {
6015            final ResolveInfo rii = results.get(i);
6016            if (rii.filter == null) {
6017                continue;
6018            }
6019
6020            // Iterate over all of the actions of this result's intent
6021            // filter...  typically this should be just one.
6022            final Iterator<String> it = rii.filter.actionsIterator();
6023            if (it == null) {
6024                continue;
6025            }
6026            while (it.hasNext()) {
6027                final String action = it.next();
6028                if (resultsAction != null && resultsAction.equals(action)) {
6029                    // If this action was explicitly requested, then don't
6030                    // remove things that have it.
6031                    continue;
6032                }
6033                for (int j=i+1; j<N; j++) {
6034                    final ResolveInfo rij = results.get(j);
6035                    if (rij.filter != null && rij.filter.hasAction(action)) {
6036                        results.remove(j);
6037                        if (DEBUG_INTENT_MATCHING) Log.v(
6038                            TAG, "Removing duplicate item from " + j
6039                            + " due to action " + action + " at " + i);
6040                        j--;
6041                        N--;
6042                    }
6043                }
6044            }
6045
6046            // If the caller didn't request filter information, drop it now
6047            // so we don't have to marshall/unmarshall it.
6048            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6049                rii.filter = null;
6050            }
6051        }
6052
6053        // Filter out the caller activity if so requested.
6054        if (caller != null) {
6055            N = results.size();
6056            for (int i=0; i<N; i++) {
6057                ActivityInfo ainfo = results.get(i).activityInfo;
6058                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6059                        && caller.getClassName().equals(ainfo.name)) {
6060                    results.remove(i);
6061                    break;
6062                }
6063            }
6064        }
6065
6066        // If the caller didn't request filter information,
6067        // drop them now so we don't have to
6068        // marshall/unmarshall it.
6069        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6070            N = results.size();
6071            for (int i=0; i<N; i++) {
6072                results.get(i).filter = null;
6073            }
6074        }
6075
6076        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6077        return results;
6078    }
6079
6080    @Override
6081    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6082            String resolvedType, int flags, int userId) {
6083        return new ParceledListSlice<>(
6084                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6085    }
6086
6087    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6088            String resolvedType, int flags, int userId) {
6089        if (!sUserManager.exists(userId)) return Collections.emptyList();
6090        flags = updateFlagsForResolve(flags, userId, intent);
6091        ComponentName comp = intent.getComponent();
6092        if (comp == null) {
6093            if (intent.getSelector() != null) {
6094                intent = intent.getSelector();
6095                comp = intent.getComponent();
6096            }
6097        }
6098        if (comp != null) {
6099            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6100            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6101            if (ai != null) {
6102                ResolveInfo ri = new ResolveInfo();
6103                ri.activityInfo = ai;
6104                list.add(ri);
6105            }
6106            return list;
6107        }
6108
6109        // reader
6110        synchronized (mPackages) {
6111            String pkgName = intent.getPackage();
6112            if (pkgName == null) {
6113                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6114            }
6115            final PackageParser.Package pkg = mPackages.get(pkgName);
6116            if (pkg != null) {
6117                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6118                        userId);
6119            }
6120            return Collections.emptyList();
6121        }
6122    }
6123
6124    @Override
6125    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6126        if (!sUserManager.exists(userId)) return null;
6127        flags = updateFlagsForResolve(flags, userId, intent);
6128        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6129        if (query != null) {
6130            if (query.size() >= 1) {
6131                // If there is more than one service with the same priority,
6132                // just arbitrarily pick the first one.
6133                return query.get(0);
6134            }
6135        }
6136        return null;
6137    }
6138
6139    @Override
6140    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6141            String resolvedType, int flags, int userId) {
6142        return new ParceledListSlice<>(
6143                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6144    }
6145
6146    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6147            String resolvedType, int flags, int userId) {
6148        if (!sUserManager.exists(userId)) return Collections.emptyList();
6149        flags = updateFlagsForResolve(flags, userId, intent);
6150        ComponentName comp = intent.getComponent();
6151        if (comp == null) {
6152            if (intent.getSelector() != null) {
6153                intent = intent.getSelector();
6154                comp = intent.getComponent();
6155            }
6156        }
6157        if (comp != null) {
6158            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6159            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6160            if (si != null) {
6161                final ResolveInfo ri = new ResolveInfo();
6162                ri.serviceInfo = si;
6163                list.add(ri);
6164            }
6165            return list;
6166        }
6167
6168        // reader
6169        synchronized (mPackages) {
6170            String pkgName = intent.getPackage();
6171            if (pkgName == null) {
6172                return mServices.queryIntent(intent, resolvedType, flags, userId);
6173            }
6174            final PackageParser.Package pkg = mPackages.get(pkgName);
6175            if (pkg != null) {
6176                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6177                        userId);
6178            }
6179            return Collections.emptyList();
6180        }
6181    }
6182
6183    @Override
6184    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6185            String resolvedType, int flags, int userId) {
6186        return new ParceledListSlice<>(
6187                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6188    }
6189
6190    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6191            Intent intent, String resolvedType, int flags, int userId) {
6192        if (!sUserManager.exists(userId)) return Collections.emptyList();
6193        flags = updateFlagsForResolve(flags, userId, intent);
6194        ComponentName comp = intent.getComponent();
6195        if (comp == null) {
6196            if (intent.getSelector() != null) {
6197                intent = intent.getSelector();
6198                comp = intent.getComponent();
6199            }
6200        }
6201        if (comp != null) {
6202            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6203            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6204            if (pi != null) {
6205                final ResolveInfo ri = new ResolveInfo();
6206                ri.providerInfo = pi;
6207                list.add(ri);
6208            }
6209            return list;
6210        }
6211
6212        // reader
6213        synchronized (mPackages) {
6214            String pkgName = intent.getPackage();
6215            if (pkgName == null) {
6216                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6217            }
6218            final PackageParser.Package pkg = mPackages.get(pkgName);
6219            if (pkg != null) {
6220                return mProviders.queryIntentForPackage(
6221                        intent, resolvedType, flags, pkg.providers, userId);
6222            }
6223            return Collections.emptyList();
6224        }
6225    }
6226
6227    @Override
6228    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6229        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6230        flags = updateFlagsForPackage(flags, userId, null);
6231        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6233                true /* requireFullPermission */, false /* checkShell */,
6234                "get installed packages");
6235
6236        // writer
6237        synchronized (mPackages) {
6238            ArrayList<PackageInfo> list;
6239            if (listUninstalled) {
6240                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6241                for (PackageSetting ps : mSettings.mPackages.values()) {
6242                    final PackageInfo pi;
6243                    if (ps.pkg != null) {
6244                        pi = generatePackageInfo(ps, flags, userId);
6245                    } else {
6246                        pi = generatePackageInfo(ps, flags, userId);
6247                    }
6248                    if (pi != null) {
6249                        list.add(pi);
6250                    }
6251                }
6252            } else {
6253                list = new ArrayList<PackageInfo>(mPackages.size());
6254                for (PackageParser.Package p : mPackages.values()) {
6255                    final PackageInfo pi =
6256                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6257                    if (pi != null) {
6258                        list.add(pi);
6259                    }
6260                }
6261            }
6262
6263            return new ParceledListSlice<PackageInfo>(list);
6264        }
6265    }
6266
6267    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6268            String[] permissions, boolean[] tmp, int flags, int userId) {
6269        int numMatch = 0;
6270        final PermissionsState permissionsState = ps.getPermissionsState();
6271        for (int i=0; i<permissions.length; i++) {
6272            final String permission = permissions[i];
6273            if (permissionsState.hasPermission(permission, userId)) {
6274                tmp[i] = true;
6275                numMatch++;
6276            } else {
6277                tmp[i] = false;
6278            }
6279        }
6280        if (numMatch == 0) {
6281            return;
6282        }
6283        final PackageInfo pi;
6284        if (ps.pkg != null) {
6285            pi = generatePackageInfo(ps, flags, userId);
6286        } else {
6287            pi = generatePackageInfo(ps, flags, userId);
6288        }
6289        // The above might return null in cases of uninstalled apps or install-state
6290        // skew across users/profiles.
6291        if (pi != null) {
6292            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6293                if (numMatch == permissions.length) {
6294                    pi.requestedPermissions = permissions;
6295                } else {
6296                    pi.requestedPermissions = new String[numMatch];
6297                    numMatch = 0;
6298                    for (int i=0; i<permissions.length; i++) {
6299                        if (tmp[i]) {
6300                            pi.requestedPermissions[numMatch] = permissions[i];
6301                            numMatch++;
6302                        }
6303                    }
6304                }
6305            }
6306            list.add(pi);
6307        }
6308    }
6309
6310    @Override
6311    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6312            String[] permissions, int flags, int userId) {
6313        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6314        flags = updateFlagsForPackage(flags, userId, permissions);
6315        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6316
6317        // writer
6318        synchronized (mPackages) {
6319            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6320            boolean[] tmpBools = new boolean[permissions.length];
6321            if (listUninstalled) {
6322                for (PackageSetting ps : mSettings.mPackages.values()) {
6323                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6324                }
6325            } else {
6326                for (PackageParser.Package pkg : mPackages.values()) {
6327                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6328                    if (ps != null) {
6329                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6330                                userId);
6331                    }
6332                }
6333            }
6334
6335            return new ParceledListSlice<PackageInfo>(list);
6336        }
6337    }
6338
6339    @Override
6340    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6341        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6342        flags = updateFlagsForApplication(flags, userId, null);
6343        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6344
6345        // writer
6346        synchronized (mPackages) {
6347            ArrayList<ApplicationInfo> list;
6348            if (listUninstalled) {
6349                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6350                for (PackageSetting ps : mSettings.mPackages.values()) {
6351                    ApplicationInfo ai;
6352                    if (ps.pkg != null) {
6353                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6354                                ps.readUserState(userId), userId);
6355                    } else {
6356                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6357                    }
6358                    if (ai != null) {
6359                        list.add(ai);
6360                    }
6361                }
6362            } else {
6363                list = new ArrayList<ApplicationInfo>(mPackages.size());
6364                for (PackageParser.Package p : mPackages.values()) {
6365                    if (p.mExtras != null) {
6366                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6367                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6368                        if (ai != null) {
6369                            list.add(ai);
6370                        }
6371                    }
6372                }
6373            }
6374
6375            return new ParceledListSlice<ApplicationInfo>(list);
6376        }
6377    }
6378
6379    @Override
6380    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6381        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6382            return null;
6383        }
6384
6385        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6386                "getEphemeralApplications");
6387        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6388                true /* requireFullPermission */, false /* checkShell */,
6389                "getEphemeralApplications");
6390        synchronized (mPackages) {
6391            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6392                    .getEphemeralApplicationsLPw(userId);
6393            if (ephemeralApps != null) {
6394                return new ParceledListSlice<>(ephemeralApps);
6395            }
6396        }
6397        return null;
6398    }
6399
6400    @Override
6401    public boolean isEphemeralApplication(String packageName, int userId) {
6402        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6403                true /* requireFullPermission */, false /* checkShell */,
6404                "isEphemeral");
6405        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6406            return false;
6407        }
6408
6409        if (!isCallerSameApp(packageName)) {
6410            return false;
6411        }
6412        synchronized (mPackages) {
6413            PackageParser.Package pkg = mPackages.get(packageName);
6414            if (pkg != null) {
6415                return pkg.applicationInfo.isEphemeralApp();
6416            }
6417        }
6418        return false;
6419    }
6420
6421    @Override
6422    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6423        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6424            return null;
6425        }
6426
6427        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6428                true /* requireFullPermission */, false /* checkShell */,
6429                "getCookie");
6430        if (!isCallerSameApp(packageName)) {
6431            return null;
6432        }
6433        synchronized (mPackages) {
6434            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6435                    packageName, userId);
6436        }
6437    }
6438
6439    @Override
6440    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6441        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6442            return true;
6443        }
6444
6445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6446                true /* requireFullPermission */, true /* checkShell */,
6447                "setCookie");
6448        if (!isCallerSameApp(packageName)) {
6449            return false;
6450        }
6451        synchronized (mPackages) {
6452            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6453                    packageName, cookie, userId);
6454        }
6455    }
6456
6457    @Override
6458    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6459        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6460            return null;
6461        }
6462
6463        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6464                "getEphemeralApplicationIcon");
6465        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6466                true /* requireFullPermission */, false /* checkShell */,
6467                "getEphemeralApplicationIcon");
6468        synchronized (mPackages) {
6469            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6470                    packageName, userId);
6471        }
6472    }
6473
6474    private boolean isCallerSameApp(String packageName) {
6475        PackageParser.Package pkg = mPackages.get(packageName);
6476        return pkg != null
6477                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6478    }
6479
6480    @Override
6481    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6482        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6483    }
6484
6485    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6486        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6487
6488        // reader
6489        synchronized (mPackages) {
6490            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6491            final int userId = UserHandle.getCallingUserId();
6492            while (i.hasNext()) {
6493                final PackageParser.Package p = i.next();
6494                if (p.applicationInfo == null) continue;
6495
6496                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6497                        && !p.applicationInfo.isDirectBootAware();
6498                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6499                        && p.applicationInfo.isDirectBootAware();
6500
6501                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6502                        && (!mSafeMode || isSystemApp(p))
6503                        && (matchesUnaware || matchesAware)) {
6504                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6505                    if (ps != null) {
6506                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6507                                ps.readUserState(userId), userId);
6508                        if (ai != null) {
6509                            finalList.add(ai);
6510                        }
6511                    }
6512                }
6513            }
6514        }
6515
6516        return finalList;
6517    }
6518
6519    @Override
6520    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6521        if (!sUserManager.exists(userId)) return null;
6522        flags = updateFlagsForComponent(flags, userId, name);
6523        // reader
6524        synchronized (mPackages) {
6525            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6526            PackageSetting ps = provider != null
6527                    ? mSettings.mPackages.get(provider.owner.packageName)
6528                    : null;
6529            return ps != null
6530                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6531                    ? PackageParser.generateProviderInfo(provider, flags,
6532                            ps.readUserState(userId), userId)
6533                    : null;
6534        }
6535    }
6536
6537    /**
6538     * @deprecated
6539     */
6540    @Deprecated
6541    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6542        // reader
6543        synchronized (mPackages) {
6544            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6545                    .entrySet().iterator();
6546            final int userId = UserHandle.getCallingUserId();
6547            while (i.hasNext()) {
6548                Map.Entry<String, PackageParser.Provider> entry = i.next();
6549                PackageParser.Provider p = entry.getValue();
6550                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6551
6552                if (ps != null && p.syncable
6553                        && (!mSafeMode || (p.info.applicationInfo.flags
6554                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6555                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6556                            ps.readUserState(userId), userId);
6557                    if (info != null) {
6558                        outNames.add(entry.getKey());
6559                        outInfo.add(info);
6560                    }
6561                }
6562            }
6563        }
6564    }
6565
6566    @Override
6567    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6568            int uid, int flags) {
6569        final int userId = processName != null ? UserHandle.getUserId(uid)
6570                : UserHandle.getCallingUserId();
6571        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6572        flags = updateFlagsForComponent(flags, userId, processName);
6573
6574        ArrayList<ProviderInfo> finalList = null;
6575        // reader
6576        synchronized (mPackages) {
6577            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6578            while (i.hasNext()) {
6579                final PackageParser.Provider p = i.next();
6580                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6581                if (ps != null && p.info.authority != null
6582                        && (processName == null
6583                                || (p.info.processName.equals(processName)
6584                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6585                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6586                    if (finalList == null) {
6587                        finalList = new ArrayList<ProviderInfo>(3);
6588                    }
6589                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6590                            ps.readUserState(userId), userId);
6591                    if (info != null) {
6592                        finalList.add(info);
6593                    }
6594                }
6595            }
6596        }
6597
6598        if (finalList != null) {
6599            Collections.sort(finalList, mProviderInitOrderSorter);
6600            return new ParceledListSlice<ProviderInfo>(finalList);
6601        }
6602
6603        return ParceledListSlice.emptyList();
6604    }
6605
6606    @Override
6607    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6608        // reader
6609        synchronized (mPackages) {
6610            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6611            return PackageParser.generateInstrumentationInfo(i, flags);
6612        }
6613    }
6614
6615    @Override
6616    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6617            String targetPackage, int flags) {
6618        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6619    }
6620
6621    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6622            int flags) {
6623        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6624
6625        // reader
6626        synchronized (mPackages) {
6627            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6628            while (i.hasNext()) {
6629                final PackageParser.Instrumentation p = i.next();
6630                if (targetPackage == null
6631                        || targetPackage.equals(p.info.targetPackage)) {
6632                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6633                            flags);
6634                    if (ii != null) {
6635                        finalList.add(ii);
6636                    }
6637                }
6638            }
6639        }
6640
6641        return finalList;
6642    }
6643
6644    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6645        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6646        if (overlays == null) {
6647            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6648            return;
6649        }
6650        for (PackageParser.Package opkg : overlays.values()) {
6651            // Not much to do if idmap fails: we already logged the error
6652            // and we certainly don't want to abort installation of pkg simply
6653            // because an overlay didn't fit properly. For these reasons,
6654            // ignore the return value of createIdmapForPackagePairLI.
6655            createIdmapForPackagePairLI(pkg, opkg);
6656        }
6657    }
6658
6659    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6660            PackageParser.Package opkg) {
6661        if (!opkg.mTrustedOverlay) {
6662            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6663                    opkg.baseCodePath + ": overlay not trusted");
6664            return false;
6665        }
6666        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6667        if (overlaySet == null) {
6668            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6669                    opkg.baseCodePath + " but target package has no known overlays");
6670            return false;
6671        }
6672        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6673        // TODO: generate idmap for split APKs
6674        try {
6675            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6676        } catch (InstallerException e) {
6677            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6678                    + opkg.baseCodePath);
6679            return false;
6680        }
6681        PackageParser.Package[] overlayArray =
6682            overlaySet.values().toArray(new PackageParser.Package[0]);
6683        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6684            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6685                return p1.mOverlayPriority - p2.mOverlayPriority;
6686            }
6687        };
6688        Arrays.sort(overlayArray, cmp);
6689
6690        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6691        int i = 0;
6692        for (PackageParser.Package p : overlayArray) {
6693            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6694        }
6695        return true;
6696    }
6697
6698    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6699        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6700        try {
6701            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6702        } finally {
6703            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6704        }
6705    }
6706
6707    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6708        final File[] files = dir.listFiles();
6709        if (ArrayUtils.isEmpty(files)) {
6710            Log.d(TAG, "No files in app dir " + dir);
6711            return;
6712        }
6713
6714        if (DEBUG_PACKAGE_SCANNING) {
6715            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6716                    + " flags=0x" + Integer.toHexString(parseFlags));
6717        }
6718
6719        for (File file : files) {
6720            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6721                    && !PackageInstallerService.isStageName(file.getName());
6722            if (!isPackage) {
6723                // Ignore entries which are not packages
6724                continue;
6725            }
6726            try {
6727                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6728                        scanFlags, currentTime, null);
6729            } catch (PackageManagerException e) {
6730                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6731
6732                // Delete invalid userdata apps
6733                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6734                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6735                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6736                    removeCodePathLI(file);
6737                }
6738            }
6739        }
6740    }
6741
6742    private static File getSettingsProblemFile() {
6743        File dataDir = Environment.getDataDirectory();
6744        File systemDir = new File(dataDir, "system");
6745        File fname = new File(systemDir, "uiderrors.txt");
6746        return fname;
6747    }
6748
6749    static void reportSettingsProblem(int priority, String msg) {
6750        logCriticalInfo(priority, msg);
6751    }
6752
6753    static void logCriticalInfo(int priority, String msg) {
6754        Slog.println(priority, TAG, msg);
6755        EventLogTags.writePmCriticalInfo(msg);
6756        try {
6757            File fname = getSettingsProblemFile();
6758            FileOutputStream out = new FileOutputStream(fname, true);
6759            PrintWriter pw = new FastPrintWriter(out);
6760            SimpleDateFormat formatter = new SimpleDateFormat();
6761            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6762            pw.println(dateString + ": " + msg);
6763            pw.close();
6764            FileUtils.setPermissions(
6765                    fname.toString(),
6766                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6767                    -1, -1);
6768        } catch (java.io.IOException e) {
6769        }
6770    }
6771
6772    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6773        if (srcFile.isDirectory()) {
6774            final File baseFile = new File(pkg.baseCodePath);
6775            long maxModifiedTime = baseFile.lastModified();
6776            if (pkg.splitCodePaths != null) {
6777                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6778                    final File splitFile = new File(pkg.splitCodePaths[i]);
6779                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6780                }
6781            }
6782            return maxModifiedTime;
6783        }
6784        return srcFile.lastModified();
6785    }
6786
6787    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6788            final int policyFlags) throws PackageManagerException {
6789        // When upgrading from pre-N MR1, verify the package time stamp using the package
6790        // directory and not the APK file.
6791        final long lastModifiedTime = mIsPreNMR1Upgrade
6792                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6793        if (ps != null
6794                && ps.codePath.equals(srcFile)
6795                && ps.timeStamp == lastModifiedTime
6796                && !isCompatSignatureUpdateNeeded(pkg)
6797                && !isRecoverSignatureUpdateNeeded(pkg)) {
6798            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6799            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6800            ArraySet<PublicKey> signingKs;
6801            synchronized (mPackages) {
6802                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6803            }
6804            if (ps.signatures.mSignatures != null
6805                    && ps.signatures.mSignatures.length != 0
6806                    && signingKs != null) {
6807                // Optimization: reuse the existing cached certificates
6808                // if the package appears to be unchanged.
6809                pkg.mSignatures = ps.signatures.mSignatures;
6810                pkg.mSigningKeys = signingKs;
6811                return;
6812            }
6813
6814            Slog.w(TAG, "PackageSetting for " + ps.name
6815                    + " is missing signatures.  Collecting certs again to recover them.");
6816        } else {
6817            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6818        }
6819
6820        try {
6821            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6822            PackageParser.collectCertificates(pkg, policyFlags);
6823        } catch (PackageParserException e) {
6824            throw PackageManagerException.from(e);
6825        } finally {
6826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6827        }
6828    }
6829
6830    /**
6831     *  Traces a package scan.
6832     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6833     */
6834    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6835            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6836        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6837        try {
6838            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6839        } finally {
6840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6841        }
6842    }
6843
6844    /**
6845     *  Scans a package and returns the newly parsed package.
6846     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6847     */
6848    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6849            long currentTime, UserHandle user) throws PackageManagerException {
6850        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6851        PackageParser pp = new PackageParser();
6852        pp.setSeparateProcesses(mSeparateProcesses);
6853        pp.setOnlyCoreApps(mOnlyCore);
6854        pp.setDisplayMetrics(mMetrics);
6855
6856        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6857            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6858        }
6859
6860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6861        final PackageParser.Package pkg;
6862        try {
6863            pkg = pp.parsePackage(scanFile, parseFlags);
6864        } catch (PackageParserException e) {
6865            throw PackageManagerException.from(e);
6866        } finally {
6867            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6868        }
6869
6870        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6871    }
6872
6873    /**
6874     *  Scans a package and returns the newly parsed package.
6875     *  @throws PackageManagerException on a parse error.
6876     */
6877    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6878            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6879            throws PackageManagerException {
6880        // If the package has children and this is the first dive in the function
6881        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6882        // packages (parent and children) would be successfully scanned before the
6883        // actual scan since scanning mutates internal state and we want to atomically
6884        // install the package and its children.
6885        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6886            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6887                scanFlags |= SCAN_CHECK_ONLY;
6888            }
6889        } else {
6890            scanFlags &= ~SCAN_CHECK_ONLY;
6891        }
6892
6893        // Scan the parent
6894        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6895                scanFlags, currentTime, user);
6896
6897        // Scan the children
6898        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6899        for (int i = 0; i < childCount; i++) {
6900            PackageParser.Package childPackage = pkg.childPackages.get(i);
6901            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6902                    currentTime, user);
6903        }
6904
6905
6906        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6907            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6908        }
6909
6910        return scannedPkg;
6911    }
6912
6913    /**
6914     *  Scans a package and returns the newly parsed package.
6915     *  @throws PackageManagerException on a parse error.
6916     */
6917    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6918            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6919            throws PackageManagerException {
6920        PackageSetting ps = null;
6921        PackageSetting updatedPkg;
6922        // reader
6923        synchronized (mPackages) {
6924            // Look to see if we already know about this package.
6925            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6926            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6927                // This package has been renamed to its original name.  Let's
6928                // use that.
6929                ps = mSettings.getPackageLPr(oldName);
6930            }
6931            // If there was no original package, see one for the real package name.
6932            if (ps == null) {
6933                ps = mSettings.getPackageLPr(pkg.packageName);
6934            }
6935            // Check to see if this package could be hiding/updating a system
6936            // package.  Must look for it either under the original or real
6937            // package name depending on our state.
6938            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6939            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6940
6941            // If this is a package we don't know about on the system partition, we
6942            // may need to remove disabled child packages on the system partition
6943            // or may need to not add child packages if the parent apk is updated
6944            // on the data partition and no longer defines this child package.
6945            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6946                // If this is a parent package for an updated system app and this system
6947                // app got an OTA update which no longer defines some of the child packages
6948                // we have to prune them from the disabled system packages.
6949                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6950                if (disabledPs != null) {
6951                    final int scannedChildCount = (pkg.childPackages != null)
6952                            ? pkg.childPackages.size() : 0;
6953                    final int disabledChildCount = disabledPs.childPackageNames != null
6954                            ? disabledPs.childPackageNames.size() : 0;
6955                    for (int i = 0; i < disabledChildCount; i++) {
6956                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6957                        boolean disabledPackageAvailable = false;
6958                        for (int j = 0; j < scannedChildCount; j++) {
6959                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6960                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6961                                disabledPackageAvailable = true;
6962                                break;
6963                            }
6964                         }
6965                         if (!disabledPackageAvailable) {
6966                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6967                         }
6968                    }
6969                }
6970            }
6971        }
6972
6973        boolean updatedPkgBetter = false;
6974        // First check if this is a system package that may involve an update
6975        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6976            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6977            // it needs to drop FLAG_PRIVILEGED.
6978            if (locationIsPrivileged(scanFile)) {
6979                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6980            } else {
6981                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6982            }
6983
6984            if (ps != null && !ps.codePath.equals(scanFile)) {
6985                // The path has changed from what was last scanned...  check the
6986                // version of the new path against what we have stored to determine
6987                // what to do.
6988                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6989                if (pkg.mVersionCode <= ps.versionCode) {
6990                    // The system package has been updated and the code path does not match
6991                    // Ignore entry. Skip it.
6992                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6993                            + " ignored: updated version " + ps.versionCode
6994                            + " better than this " + pkg.mVersionCode);
6995                    if (!updatedPkg.codePath.equals(scanFile)) {
6996                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6997                                + ps.name + " changing from " + updatedPkg.codePathString
6998                                + " to " + scanFile);
6999                        updatedPkg.codePath = scanFile;
7000                        updatedPkg.codePathString = scanFile.toString();
7001                        updatedPkg.resourcePath = scanFile;
7002                        updatedPkg.resourcePathString = scanFile.toString();
7003                    }
7004                    updatedPkg.pkg = pkg;
7005                    updatedPkg.versionCode = pkg.mVersionCode;
7006
7007                    // Update the disabled system child packages to point to the package too.
7008                    final int childCount = updatedPkg.childPackageNames != null
7009                            ? updatedPkg.childPackageNames.size() : 0;
7010                    for (int i = 0; i < childCount; i++) {
7011                        String childPackageName = updatedPkg.childPackageNames.get(i);
7012                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7013                                childPackageName);
7014                        if (updatedChildPkg != null) {
7015                            updatedChildPkg.pkg = pkg;
7016                            updatedChildPkg.versionCode = pkg.mVersionCode;
7017                        }
7018                    }
7019
7020                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7021                            + scanFile + " ignored: updated version " + ps.versionCode
7022                            + " better than this " + pkg.mVersionCode);
7023                } else {
7024                    // The current app on the system partition is better than
7025                    // what we have updated to on the data partition; switch
7026                    // back to the system partition version.
7027                    // At this point, its safely assumed that package installation for
7028                    // apps in system partition will go through. If not there won't be a working
7029                    // version of the app
7030                    // writer
7031                    synchronized (mPackages) {
7032                        // Just remove the loaded entries from package lists.
7033                        mPackages.remove(ps.name);
7034                    }
7035
7036                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7037                            + " reverting from " + ps.codePathString
7038                            + ": new version " + pkg.mVersionCode
7039                            + " better than installed " + ps.versionCode);
7040
7041                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7042                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7043                    synchronized (mInstallLock) {
7044                        args.cleanUpResourcesLI();
7045                    }
7046                    synchronized (mPackages) {
7047                        mSettings.enableSystemPackageLPw(ps.name);
7048                    }
7049                    updatedPkgBetter = true;
7050                }
7051            }
7052        }
7053
7054        if (updatedPkg != null) {
7055            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7056            // initially
7057            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7058
7059            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7060            // flag set initially
7061            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7062                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7063            }
7064        }
7065
7066        // Verify certificates against what was last scanned
7067        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7068
7069        /*
7070         * A new system app appeared, but we already had a non-system one of the
7071         * same name installed earlier.
7072         */
7073        boolean shouldHideSystemApp = false;
7074        if (updatedPkg == null && ps != null
7075                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7076            /*
7077             * Check to make sure the signatures match first. If they don't,
7078             * wipe the installed application and its data.
7079             */
7080            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7081                    != PackageManager.SIGNATURE_MATCH) {
7082                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7083                        + " signatures don't match existing userdata copy; removing");
7084                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7085                        "scanPackageInternalLI")) {
7086                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7087                }
7088                ps = null;
7089            } else {
7090                /*
7091                 * If the newly-added system app is an older version than the
7092                 * already installed version, hide it. It will be scanned later
7093                 * and re-added like an update.
7094                 */
7095                if (pkg.mVersionCode <= ps.versionCode) {
7096                    shouldHideSystemApp = true;
7097                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7098                            + " but new version " + pkg.mVersionCode + " better than installed "
7099                            + ps.versionCode + "; hiding system");
7100                } else {
7101                    /*
7102                     * The newly found system app is a newer version that the
7103                     * one previously installed. Simply remove the
7104                     * already-installed application and replace it with our own
7105                     * while keeping the application data.
7106                     */
7107                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7108                            + " reverting from " + ps.codePathString + ": new version "
7109                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7110                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7111                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7112                    synchronized (mInstallLock) {
7113                        args.cleanUpResourcesLI();
7114                    }
7115                }
7116            }
7117        }
7118
7119        // The apk is forward locked (not public) if its code and resources
7120        // are kept in different files. (except for app in either system or
7121        // vendor path).
7122        // TODO grab this value from PackageSettings
7123        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7124            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7125                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7126            }
7127        }
7128
7129        // TODO: extend to support forward-locked splits
7130        String resourcePath = null;
7131        String baseResourcePath = null;
7132        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7133            if (ps != null && ps.resourcePathString != null) {
7134                resourcePath = ps.resourcePathString;
7135                baseResourcePath = ps.resourcePathString;
7136            } else {
7137                // Should not happen at all. Just log an error.
7138                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7139            }
7140        } else {
7141            resourcePath = pkg.codePath;
7142            baseResourcePath = pkg.baseCodePath;
7143        }
7144
7145        // Set application objects path explicitly.
7146        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7147        pkg.setApplicationInfoCodePath(pkg.codePath);
7148        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7149        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7150        pkg.setApplicationInfoResourcePath(resourcePath);
7151        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7152        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7153
7154        // Note that we invoke the following method only if we are about to unpack an application
7155        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7156                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7157
7158        /*
7159         * If the system app should be overridden by a previously installed
7160         * data, hide the system app now and let the /data/app scan pick it up
7161         * again.
7162         */
7163        if (shouldHideSystemApp) {
7164            synchronized (mPackages) {
7165                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7166            }
7167        }
7168
7169        return scannedPkg;
7170    }
7171
7172    private static String fixProcessName(String defProcessName,
7173            String processName) {
7174        if (processName == null) {
7175            return defProcessName;
7176        }
7177        return processName;
7178    }
7179
7180    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7181            throws PackageManagerException {
7182        if (pkgSetting.signatures.mSignatures != null) {
7183            // Already existing package. Make sure signatures match
7184            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7185                    == PackageManager.SIGNATURE_MATCH;
7186            if (!match) {
7187                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7188                        == PackageManager.SIGNATURE_MATCH;
7189            }
7190            if (!match) {
7191                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7192                        == PackageManager.SIGNATURE_MATCH;
7193            }
7194            if (!match) {
7195                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7196                        + pkg.packageName + " signatures do not match the "
7197                        + "previously installed version; ignoring!");
7198            }
7199        }
7200
7201        // Check for shared user signatures
7202        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7203            // Already existing package. Make sure signatures match
7204            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7205                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7206            if (!match) {
7207                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7208                        == PackageManager.SIGNATURE_MATCH;
7209            }
7210            if (!match) {
7211                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7212                        == PackageManager.SIGNATURE_MATCH;
7213            }
7214            if (!match) {
7215                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7216                        "Package " + pkg.packageName
7217                        + " has no signatures that match those in shared user "
7218                        + pkgSetting.sharedUser.name + "; ignoring!");
7219            }
7220        }
7221    }
7222
7223    /**
7224     * Enforces that only the system UID or root's UID can call a method exposed
7225     * via Binder.
7226     *
7227     * @param message used as message if SecurityException is thrown
7228     * @throws SecurityException if the caller is not system or root
7229     */
7230    private static final void enforceSystemOrRoot(String message) {
7231        final int uid = Binder.getCallingUid();
7232        if (uid != Process.SYSTEM_UID && uid != 0) {
7233            throw new SecurityException(message);
7234        }
7235    }
7236
7237    @Override
7238    public void performFstrimIfNeeded() {
7239        enforceSystemOrRoot("Only the system can request fstrim");
7240
7241        // Before everything else, see whether we need to fstrim.
7242        try {
7243            IMountService ms = PackageHelper.getMountService();
7244            if (ms != null) {
7245                boolean doTrim = false;
7246                final long interval = android.provider.Settings.Global.getLong(
7247                        mContext.getContentResolver(),
7248                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7249                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7250                if (interval > 0) {
7251                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7252                    if (timeSinceLast > interval) {
7253                        doTrim = true;
7254                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7255                                + "; running immediately");
7256                    }
7257                }
7258                if (doTrim) {
7259                    final boolean dexOptDialogShown;
7260                    synchronized (mPackages) {
7261                        dexOptDialogShown = mDexOptDialogShown;
7262                    }
7263                    if (!isFirstBoot() && dexOptDialogShown) {
7264                        try {
7265                            ActivityManagerNative.getDefault().showBootMessage(
7266                                    mContext.getResources().getString(
7267                                            R.string.android_upgrading_fstrim), true);
7268                        } catch (RemoteException e) {
7269                        }
7270                    }
7271                    ms.runMaintenance();
7272                }
7273            } else {
7274                Slog.e(TAG, "Mount service unavailable!");
7275            }
7276        } catch (RemoteException e) {
7277            // Can't happen; MountService is local
7278        }
7279    }
7280
7281    @Override
7282    public void updatePackagesIfNeeded() {
7283        enforceSystemOrRoot("Only the system can request package update");
7284
7285        // We need to re-extract after an OTA.
7286        boolean causeUpgrade = isUpgrade();
7287
7288        // First boot or factory reset.
7289        // Note: we also handle devices that are upgrading to N right now as if it is their
7290        //       first boot, as they do not have profile data.
7291        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7292
7293        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7294        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7295
7296        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7297            return;
7298        }
7299
7300        List<PackageParser.Package> pkgs;
7301        synchronized (mPackages) {
7302            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7303        }
7304
7305        final long startTime = System.nanoTime();
7306        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7307                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7308
7309        final int elapsedTimeSeconds =
7310                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7311
7312        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7313        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7314        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7315        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7316        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7317    }
7318
7319    /**
7320     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7321     * containing statistics about the invocation. The array consists of three elements,
7322     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7323     * and {@code numberOfPackagesFailed}.
7324     */
7325    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7326            String compilerFilter) {
7327
7328        int numberOfPackagesVisited = 0;
7329        int numberOfPackagesOptimized = 0;
7330        int numberOfPackagesSkipped = 0;
7331        int numberOfPackagesFailed = 0;
7332        final int numberOfPackagesToDexopt = pkgs.size();
7333
7334        for (PackageParser.Package pkg : pkgs) {
7335            numberOfPackagesVisited++;
7336
7337            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7338                if (DEBUG_DEXOPT) {
7339                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7340                }
7341                numberOfPackagesSkipped++;
7342                continue;
7343            }
7344
7345            if (DEBUG_DEXOPT) {
7346                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7347                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7348            }
7349
7350            if (showDialog) {
7351                try {
7352                    ActivityManagerNative.getDefault().showBootMessage(
7353                            mContext.getResources().getString(R.string.android_upgrading_apk,
7354                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7355                } catch (RemoteException e) {
7356                }
7357                synchronized (mPackages) {
7358                    mDexOptDialogShown = true;
7359                }
7360            }
7361
7362            // If the OTA updates a system app which was previously preopted to a non-preopted state
7363            // the app might end up being verified at runtime. That's because by default the apps
7364            // are verify-profile but for preopted apps there's no profile.
7365            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7366            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7367            // filter (by default interpret-only).
7368            // Note that at this stage unused apps are already filtered.
7369            if (isSystemApp(pkg) &&
7370                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7371                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7372                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7373            }
7374
7375            // If the OTA updates a system app which was previously preopted to a non-preopted state
7376            // the app might end up being verified at runtime. That's because by default the apps
7377            // are verify-profile but for preopted apps there's no profile.
7378            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7379            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7380            // filter (by default interpret-only).
7381            // Note that at this stage unused apps are already filtered.
7382            if (isSystemApp(pkg) &&
7383                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7384                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7385                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7386            }
7387
7388            // checkProfiles is false to avoid merging profiles during boot which
7389            // might interfere with background compilation (b/28612421).
7390            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7391            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7392            // trade-off worth doing to save boot time work.
7393            int dexOptStatus = performDexOptTraced(pkg.packageName,
7394                    false /* checkProfiles */,
7395                    compilerFilter,
7396                    false /* force */);
7397            switch (dexOptStatus) {
7398                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7399                    numberOfPackagesOptimized++;
7400                    break;
7401                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7402                    numberOfPackagesSkipped++;
7403                    break;
7404                case PackageDexOptimizer.DEX_OPT_FAILED:
7405                    numberOfPackagesFailed++;
7406                    break;
7407                default:
7408                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7409                    break;
7410            }
7411        }
7412
7413        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7414                numberOfPackagesFailed };
7415    }
7416
7417    @Override
7418    public void notifyPackageUse(String packageName, int reason) {
7419        synchronized (mPackages) {
7420            PackageParser.Package p = mPackages.get(packageName);
7421            if (p == null) {
7422                return;
7423            }
7424            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7425        }
7426    }
7427
7428    // TODO: this is not used nor needed. Delete it.
7429    @Override
7430    public boolean performDexOptIfNeeded(String packageName) {
7431        int dexOptStatus = performDexOptTraced(packageName,
7432                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7433        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7434    }
7435
7436    @Override
7437    public boolean performDexOpt(String packageName,
7438            boolean checkProfiles, int compileReason, boolean force) {
7439        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7440                getCompilerFilterForReason(compileReason), force);
7441        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7442    }
7443
7444    @Override
7445    public boolean performDexOptMode(String packageName,
7446            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7447        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7448                targetCompilerFilter, force);
7449        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7450    }
7451
7452    private int performDexOptTraced(String packageName,
7453                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7455        try {
7456            return performDexOptInternal(packageName, checkProfiles,
7457                    targetCompilerFilter, force);
7458        } finally {
7459            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7460        }
7461    }
7462
7463    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7464    // if the package can now be considered up to date for the given filter.
7465    private int performDexOptInternal(String packageName,
7466                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7467        PackageParser.Package p;
7468        synchronized (mPackages) {
7469            p = mPackages.get(packageName);
7470            if (p == null) {
7471                // Package could not be found. Report failure.
7472                return PackageDexOptimizer.DEX_OPT_FAILED;
7473            }
7474            mPackageUsage.maybeWriteAsync(mPackages);
7475            mCompilerStats.maybeWriteAsync();
7476        }
7477        long callingId = Binder.clearCallingIdentity();
7478        try {
7479            synchronized (mInstallLock) {
7480                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7481                        targetCompilerFilter, force);
7482            }
7483        } finally {
7484            Binder.restoreCallingIdentity(callingId);
7485        }
7486    }
7487
7488    public ArraySet<String> getOptimizablePackages() {
7489        ArraySet<String> pkgs = new ArraySet<String>();
7490        synchronized (mPackages) {
7491            for (PackageParser.Package p : mPackages.values()) {
7492                if (PackageDexOptimizer.canOptimizePackage(p)) {
7493                    pkgs.add(p.packageName);
7494                }
7495            }
7496        }
7497        return pkgs;
7498    }
7499
7500    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7501            boolean checkProfiles, String targetCompilerFilter,
7502            boolean force) {
7503        // Select the dex optimizer based on the force parameter.
7504        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7505        //       allocate an object here.
7506        PackageDexOptimizer pdo = force
7507                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7508                : mPackageDexOptimizer;
7509
7510        // Optimize all dependencies first. Note: we ignore the return value and march on
7511        // on errors.
7512        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7513        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7514        if (!deps.isEmpty()) {
7515            for (PackageParser.Package depPackage : deps) {
7516                // TODO: Analyze and investigate if we (should) profile libraries.
7517                // Currently this will do a full compilation of the library by default.
7518                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7519                        false /* checkProfiles */,
7520                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7521                        getOrCreateCompilerPackageStats(depPackage));
7522            }
7523        }
7524        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7525                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7526    }
7527
7528    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7529        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7530            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7531            Set<String> collectedNames = new HashSet<>();
7532            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7533
7534            retValue.remove(p);
7535
7536            return retValue;
7537        } else {
7538            return Collections.emptyList();
7539        }
7540    }
7541
7542    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7543            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7544        if (!collectedNames.contains(p.packageName)) {
7545            collectedNames.add(p.packageName);
7546            collected.add(p);
7547
7548            if (p.usesLibraries != null) {
7549                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7550            }
7551            if (p.usesOptionalLibraries != null) {
7552                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7553                        collectedNames);
7554            }
7555        }
7556    }
7557
7558    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7559            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7560        for (String libName : libs) {
7561            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7562            if (libPkg != null) {
7563                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7564            }
7565        }
7566    }
7567
7568    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7569        synchronized (mPackages) {
7570            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7571            if (lib != null && lib.apk != null) {
7572                return mPackages.get(lib.apk);
7573            }
7574        }
7575        return null;
7576    }
7577
7578    public void shutdown() {
7579        mPackageUsage.writeNow(mPackages);
7580        mCompilerStats.writeNow();
7581    }
7582
7583    @Override
7584    public void dumpProfiles(String packageName) {
7585        PackageParser.Package pkg;
7586        synchronized (mPackages) {
7587            pkg = mPackages.get(packageName);
7588            if (pkg == null) {
7589                throw new IllegalArgumentException("Unknown package: " + packageName);
7590            }
7591        }
7592        /* Only the shell, root, or the app user should be able to dump profiles. */
7593        int callingUid = Binder.getCallingUid();
7594        if (callingUid != Process.SHELL_UID &&
7595            callingUid != Process.ROOT_UID &&
7596            callingUid != pkg.applicationInfo.uid) {
7597            throw new SecurityException("dumpProfiles");
7598        }
7599
7600        synchronized (mInstallLock) {
7601            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7602            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7603            try {
7604                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7605                String gid = Integer.toString(sharedGid);
7606                String codePaths = TextUtils.join(";", allCodePaths);
7607                mInstaller.dumpProfiles(gid, packageName, codePaths);
7608            } catch (InstallerException e) {
7609                Slog.w(TAG, "Failed to dump profiles", e);
7610            }
7611            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7612        }
7613    }
7614
7615    @Override
7616    public void forceDexOpt(String packageName) {
7617        enforceSystemOrRoot("forceDexOpt");
7618
7619        PackageParser.Package pkg;
7620        synchronized (mPackages) {
7621            pkg = mPackages.get(packageName);
7622            if (pkg == null) {
7623                throw new IllegalArgumentException("Unknown package: " + packageName);
7624            }
7625        }
7626
7627        synchronized (mInstallLock) {
7628            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7629
7630            // Whoever is calling forceDexOpt wants a fully compiled package.
7631            // Don't use profiles since that may cause compilation to be skipped.
7632            final int res = performDexOptInternalWithDependenciesLI(pkg,
7633                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7634                    true /* force */);
7635
7636            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7637            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7638                throw new IllegalStateException("Failed to dexopt: " + res);
7639            }
7640        }
7641    }
7642
7643    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7644        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7645            Slog.w(TAG, "Unable to update from " + oldPkg.name
7646                    + " to " + newPkg.packageName
7647                    + ": old package not in system partition");
7648            return false;
7649        } else if (mPackages.get(oldPkg.name) != null) {
7650            Slog.w(TAG, "Unable to update from " + oldPkg.name
7651                    + " to " + newPkg.packageName
7652                    + ": old package still exists");
7653            return false;
7654        }
7655        return true;
7656    }
7657
7658    void removeCodePathLI(File codePath) {
7659        if (codePath.isDirectory()) {
7660            try {
7661                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7662            } catch (InstallerException e) {
7663                Slog.w(TAG, "Failed to remove code path", e);
7664            }
7665        } else {
7666            codePath.delete();
7667        }
7668    }
7669
7670    private int[] resolveUserIds(int userId) {
7671        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7672    }
7673
7674    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7675        if (pkg == null) {
7676            Slog.wtf(TAG, "Package was null!", new Throwable());
7677            return;
7678        }
7679        clearAppDataLeafLIF(pkg, userId, flags);
7680        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7681        for (int i = 0; i < childCount; i++) {
7682            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7683        }
7684    }
7685
7686    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7687        final PackageSetting ps;
7688        synchronized (mPackages) {
7689            ps = mSettings.mPackages.get(pkg.packageName);
7690        }
7691        for (int realUserId : resolveUserIds(userId)) {
7692            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7693            try {
7694                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7695                        ceDataInode);
7696            } catch (InstallerException e) {
7697                Slog.w(TAG, String.valueOf(e));
7698            }
7699        }
7700    }
7701
7702    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7703        if (pkg == null) {
7704            Slog.wtf(TAG, "Package was null!", new Throwable());
7705            return;
7706        }
7707        destroyAppDataLeafLIF(pkg, userId, flags);
7708        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7709        for (int i = 0; i < childCount; i++) {
7710            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7711        }
7712    }
7713
7714    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7715        final PackageSetting ps;
7716        synchronized (mPackages) {
7717            ps = mSettings.mPackages.get(pkg.packageName);
7718        }
7719        for (int realUserId : resolveUserIds(userId)) {
7720            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7721            try {
7722                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7723                        ceDataInode);
7724            } catch (InstallerException e) {
7725                Slog.w(TAG, String.valueOf(e));
7726            }
7727        }
7728    }
7729
7730    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7731        if (pkg == null) {
7732            Slog.wtf(TAG, "Package was null!", new Throwable());
7733            return;
7734        }
7735        destroyAppProfilesLeafLIF(pkg);
7736        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7737        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7738        for (int i = 0; i < childCount; i++) {
7739            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7740            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7741                    true /* removeBaseMarker */);
7742        }
7743    }
7744
7745    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7746            boolean removeBaseMarker) {
7747        if (pkg.isForwardLocked()) {
7748            return;
7749        }
7750
7751        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7752            try {
7753                path = PackageManagerServiceUtils.realpath(new File(path));
7754            } catch (IOException e) {
7755                // TODO: Should we return early here ?
7756                Slog.w(TAG, "Failed to get canonical path", e);
7757                continue;
7758            }
7759
7760            final String useMarker = path.replace('/', '@');
7761            for (int realUserId : resolveUserIds(userId)) {
7762                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7763                if (removeBaseMarker) {
7764                    File foreignUseMark = new File(profileDir, useMarker);
7765                    if (foreignUseMark.exists()) {
7766                        if (!foreignUseMark.delete()) {
7767                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7768                                    + pkg.packageName);
7769                        }
7770                    }
7771                }
7772
7773                File[] markers = profileDir.listFiles();
7774                if (markers != null) {
7775                    final String searchString = "@" + pkg.packageName + "@";
7776                    // We also delete all markers that contain the package name we're
7777                    // uninstalling. These are associated with secondary dex-files belonging
7778                    // to the package. Reconstructing the path of these dex files is messy
7779                    // in general.
7780                    for (File marker : markers) {
7781                        if (marker.getName().indexOf(searchString) > 0) {
7782                            if (!marker.delete()) {
7783                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7784                                    + pkg.packageName);
7785                            }
7786                        }
7787                    }
7788                }
7789            }
7790        }
7791    }
7792
7793    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7794        try {
7795            mInstaller.destroyAppProfiles(pkg.packageName);
7796        } catch (InstallerException e) {
7797            Slog.w(TAG, String.valueOf(e));
7798        }
7799    }
7800
7801    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7802        if (pkg == null) {
7803            Slog.wtf(TAG, "Package was null!", new Throwable());
7804            return;
7805        }
7806        clearAppProfilesLeafLIF(pkg);
7807        // We don't remove the base foreign use marker when clearing profiles because
7808        // we will rename it when the app is updated. Unlike the actual profile contents,
7809        // the foreign use marker is good across installs.
7810        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7811        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7812        for (int i = 0; i < childCount; i++) {
7813            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7814        }
7815    }
7816
7817    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7818        try {
7819            mInstaller.clearAppProfiles(pkg.packageName);
7820        } catch (InstallerException e) {
7821            Slog.w(TAG, String.valueOf(e));
7822        }
7823    }
7824
7825    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7826            long lastUpdateTime) {
7827        // Set parent install/update time
7828        PackageSetting ps = (PackageSetting) pkg.mExtras;
7829        if (ps != null) {
7830            ps.firstInstallTime = firstInstallTime;
7831            ps.lastUpdateTime = lastUpdateTime;
7832        }
7833        // Set children install/update time
7834        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7835        for (int i = 0; i < childCount; i++) {
7836            PackageParser.Package childPkg = pkg.childPackages.get(i);
7837            ps = (PackageSetting) childPkg.mExtras;
7838            if (ps != null) {
7839                ps.firstInstallTime = firstInstallTime;
7840                ps.lastUpdateTime = lastUpdateTime;
7841            }
7842        }
7843    }
7844
7845    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7846            PackageParser.Package changingLib) {
7847        if (file.path != null) {
7848            usesLibraryFiles.add(file.path);
7849            return;
7850        }
7851        PackageParser.Package p = mPackages.get(file.apk);
7852        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7853            // If we are doing this while in the middle of updating a library apk,
7854            // then we need to make sure to use that new apk for determining the
7855            // dependencies here.  (We haven't yet finished committing the new apk
7856            // to the package manager state.)
7857            if (p == null || p.packageName.equals(changingLib.packageName)) {
7858                p = changingLib;
7859            }
7860        }
7861        if (p != null) {
7862            usesLibraryFiles.addAll(p.getAllCodePaths());
7863        }
7864    }
7865
7866    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7867            PackageParser.Package changingLib) throws PackageManagerException {
7868        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7869            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7870            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7871            for (int i=0; i<N; i++) {
7872                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7873                if (file == null) {
7874                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7875                            "Package " + pkg.packageName + " requires unavailable shared library "
7876                            + pkg.usesLibraries.get(i) + "; failing!");
7877                }
7878                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7879            }
7880            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7881            for (int i=0; i<N; i++) {
7882                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7883                if (file == null) {
7884                    Slog.w(TAG, "Package " + pkg.packageName
7885                            + " desires unavailable shared library "
7886                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7887                } else {
7888                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7889                }
7890            }
7891            N = usesLibraryFiles.size();
7892            if (N > 0) {
7893                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7894            } else {
7895                pkg.usesLibraryFiles = null;
7896            }
7897        }
7898    }
7899
7900    private static boolean hasString(List<String> list, List<String> which) {
7901        if (list == null) {
7902            return false;
7903        }
7904        for (int i=list.size()-1; i>=0; i--) {
7905            for (int j=which.size()-1; j>=0; j--) {
7906                if (which.get(j).equals(list.get(i))) {
7907                    return true;
7908                }
7909            }
7910        }
7911        return false;
7912    }
7913
7914    private void updateAllSharedLibrariesLPw() {
7915        for (PackageParser.Package pkg : mPackages.values()) {
7916            try {
7917                updateSharedLibrariesLPr(pkg, null);
7918            } catch (PackageManagerException e) {
7919                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7920            }
7921        }
7922    }
7923
7924    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7925            PackageParser.Package changingPkg) {
7926        ArrayList<PackageParser.Package> res = null;
7927        for (PackageParser.Package pkg : mPackages.values()) {
7928            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7929                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7930                if (res == null) {
7931                    res = new ArrayList<PackageParser.Package>();
7932                }
7933                res.add(pkg);
7934                try {
7935                    updateSharedLibrariesLPr(pkg, changingPkg);
7936                } catch (PackageManagerException e) {
7937                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7938                }
7939            }
7940        }
7941        return res;
7942    }
7943
7944    /**
7945     * Derive the value of the {@code cpuAbiOverride} based on the provided
7946     * value and an optional stored value from the package settings.
7947     */
7948    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7949        String cpuAbiOverride = null;
7950
7951        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7952            cpuAbiOverride = null;
7953        } else if (abiOverride != null) {
7954            cpuAbiOverride = abiOverride;
7955        } else if (settings != null) {
7956            cpuAbiOverride = settings.cpuAbiOverrideString;
7957        }
7958
7959        return cpuAbiOverride;
7960    }
7961
7962    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7963            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7964                    throws PackageManagerException {
7965        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7966        // If the package has children and this is the first dive in the function
7967        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7968        // whether all packages (parent and children) would be successfully scanned
7969        // before the actual scan since scanning mutates internal state and we want
7970        // to atomically install the package and its children.
7971        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7972            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7973                scanFlags |= SCAN_CHECK_ONLY;
7974            }
7975        } else {
7976            scanFlags &= ~SCAN_CHECK_ONLY;
7977        }
7978
7979        final PackageParser.Package scannedPkg;
7980        try {
7981            // Scan the parent
7982            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7983            // Scan the children
7984            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7985            for (int i = 0; i < childCount; i++) {
7986                PackageParser.Package childPkg = pkg.childPackages.get(i);
7987                scanPackageLI(childPkg, policyFlags,
7988                        scanFlags, currentTime, user);
7989            }
7990        } finally {
7991            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7992        }
7993
7994        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7995            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7996        }
7997
7998        return scannedPkg;
7999    }
8000
8001    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8002            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8003        boolean success = false;
8004        try {
8005            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8006                    currentTime, user);
8007            success = true;
8008            return res;
8009        } finally {
8010            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8011                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8012                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8013                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8014                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8015            }
8016        }
8017    }
8018
8019    /**
8020     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8021     */
8022    private static boolean apkHasCode(String fileName) {
8023        StrictJarFile jarFile = null;
8024        try {
8025            jarFile = new StrictJarFile(fileName,
8026                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8027            return jarFile.findEntry("classes.dex") != null;
8028        } catch (IOException ignore) {
8029        } finally {
8030            try {
8031                if (jarFile != null) {
8032                    jarFile.close();
8033                }
8034            } catch (IOException ignore) {}
8035        }
8036        return false;
8037    }
8038
8039    /**
8040     * Enforces code policy for the package. This ensures that if an APK has
8041     * declared hasCode="true" in its manifest that the APK actually contains
8042     * code.
8043     *
8044     * @throws PackageManagerException If bytecode could not be found when it should exist
8045     */
8046    private static void assertCodePolicy(PackageParser.Package pkg)
8047            throws PackageManagerException {
8048        final boolean shouldHaveCode =
8049                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8050        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8051            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8052                    "Package " + pkg.baseCodePath + " code is missing");
8053        }
8054
8055        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8056            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8057                final boolean splitShouldHaveCode =
8058                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8059                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8060                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8061                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8062                }
8063            }
8064        }
8065    }
8066
8067    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8068            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8069                    throws PackageManagerException {
8070        if (DEBUG_PACKAGE_SCANNING) {
8071            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8072                Log.d(TAG, "Scanning package " + pkg.packageName);
8073        }
8074
8075        applyPolicy(pkg, policyFlags);
8076
8077        assertPackageIsValid(pkg, policyFlags);
8078
8079        // Initialize package source and resource directories
8080        final File scanFile = new File(pkg.codePath);
8081        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8082        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8083
8084        SharedUserSetting suid = null;
8085        PackageSetting pkgSetting = null;
8086
8087        // Getting the package setting may have a side-effect, so if we
8088        // are only checking if scan would succeed, stash a copy of the
8089        // old setting to restore at the end.
8090        PackageSetting nonMutatedPs = null;
8091
8092        // writer
8093        synchronized (mPackages) {
8094            if (pkg.mSharedUserId != null) {
8095                // SIDE EFFECTS; may potentially allocate a new shared user
8096                suid = mSettings.getSharedUserLPw(
8097                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8098                if (DEBUG_PACKAGE_SCANNING) {
8099                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8100                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8101                                + "): packages=" + suid.packages);
8102                }
8103            }
8104
8105            // Check if we are renaming from an original package name.
8106            PackageSetting origPackage = null;
8107            String realName = null;
8108            if (pkg.mOriginalPackages != null) {
8109                // This package may need to be renamed to a previously
8110                // installed name.  Let's check on that...
8111                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8112                if (pkg.mOriginalPackages.contains(renamed)) {
8113                    // This package had originally been installed as the
8114                    // original name, and we have already taken care of
8115                    // transitioning to the new one.  Just update the new
8116                    // one to continue using the old name.
8117                    realName = pkg.mRealPackage;
8118                    if (!pkg.packageName.equals(renamed)) {
8119                        // Callers into this function may have already taken
8120                        // care of renaming the package; only do it here if
8121                        // it is not already done.
8122                        pkg.setPackageName(renamed);
8123                    }
8124                } else {
8125                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8126                        if ((origPackage = mSettings.getPackageLPr(
8127                                pkg.mOriginalPackages.get(i))) != null) {
8128                            // We do have the package already installed under its
8129                            // original name...  should we use it?
8130                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8131                                // New package is not compatible with original.
8132                                origPackage = null;
8133                                continue;
8134                            } else if (origPackage.sharedUser != null) {
8135                                // Make sure uid is compatible between packages.
8136                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8137                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8138                                            + " to " + pkg.packageName + ": old uid "
8139                                            + origPackage.sharedUser.name
8140                                            + " differs from " + pkg.mSharedUserId);
8141                                    origPackage = null;
8142                                    continue;
8143                                }
8144                                // TODO: Add case when shared user id is added [b/28144775]
8145                            } else {
8146                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8147                                        + pkg.packageName + " to old name " + origPackage.name);
8148                            }
8149                            break;
8150                        }
8151                    }
8152                }
8153            }
8154
8155            if (mTransferedPackages.contains(pkg.packageName)) {
8156                Slog.w(TAG, "Package " + pkg.packageName
8157                        + " was transferred to another, but its .apk remains");
8158            }
8159
8160            // See comments in nonMutatedPs declaration
8161            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8162                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8163                if (foundPs != null) {
8164                    nonMutatedPs = new PackageSetting(foundPs);
8165                }
8166            }
8167
8168            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8169            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8170                PackageManagerService.reportSettingsProblem(Log.WARN,
8171                        "Package " + pkg.packageName + " shared user changed from "
8172                                + (pkgSetting.sharedUser != null
8173                                        ? pkgSetting.sharedUser.name : "<nothing>")
8174                                + " to "
8175                                + (suid != null ? suid.name : "<nothing>")
8176                                + "; replacing with new");
8177                pkgSetting = null;
8178            }
8179            final PackageSetting oldPkgSetting =
8180                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8181            final PackageSetting disabledPkgSetting =
8182                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8183            if (pkgSetting == null) {
8184                final String parentPackageName = (pkg.parentPackage != null)
8185                        ? pkg.parentPackage.packageName : null;
8186                // REMOVE SharedUserSetting from method; update in a separate call
8187                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8188                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8189                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8190                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8191                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8192                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8193                        UserManagerService.getInstance());
8194                // SIDE EFFECTS; updates system state; move elsewhere
8195                if (origPackage != null) {
8196                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8197                }
8198                mSettings.addUserToSettingLPw(pkgSetting);
8199            } else {
8200                // REMOVE SharedUserSetting from method; update in a separate call
8201                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8202                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8203                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8204                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8205                        UserManagerService.getInstance());
8206            }
8207            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8208            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8209
8210            // SIDE EFFECTS; modifies system state; move elsewhere
8211            if (pkgSetting.origPackage != null) {
8212                // If we are first transitioning from an original package,
8213                // fix up the new package's name now.  We need to do this after
8214                // looking up the package under its new name, so getPackageLP
8215                // can take care of fiddling things correctly.
8216                pkg.setPackageName(origPackage.name);
8217
8218                // File a report about this.
8219                String msg = "New package " + pkgSetting.realName
8220                        + " renamed to replace old package " + pkgSetting.name;
8221                reportSettingsProblem(Log.WARN, msg);
8222
8223                // Make a note of it.
8224                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8225                    mTransferedPackages.add(origPackage.name);
8226                }
8227
8228                // No longer need to retain this.
8229                pkgSetting.origPackage = null;
8230            }
8231
8232            // SIDE EFFECTS; modifies system state; move elsewhere
8233            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8234                // Make a note of it.
8235                mTransferedPackages.add(pkg.packageName);
8236            }
8237
8238            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8239                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8240            }
8241
8242            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8243                // Check all shared libraries and map to their actual file path.
8244                // We only do this here for apps not on a system dir, because those
8245                // are the only ones that can fail an install due to this.  We
8246                // will take care of the system apps by updating all of their
8247                // library paths after the scan is done.
8248                updateSharedLibrariesLPr(pkg, null);
8249            }
8250
8251            if (mFoundPolicyFile) {
8252                SELinuxMMAC.assignSeinfoValue(pkg);
8253            }
8254
8255            pkg.applicationInfo.uid = pkgSetting.appId;
8256            pkg.mExtras = pkgSetting;
8257            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8258                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8259                    // We just determined the app is signed correctly, so bring
8260                    // over the latest parsed certs.
8261                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8262                } else {
8263                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8264                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8265                                "Package " + pkg.packageName + " upgrade keys do not match the "
8266                                + "previously installed version");
8267                    } else {
8268                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8269                        String msg = "System package " + pkg.packageName
8270                                + " signature changed; retaining data.";
8271                        reportSettingsProblem(Log.WARN, msg);
8272                    }
8273                }
8274            } else {
8275                try {
8276                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8277                    verifySignaturesLP(pkgSetting, pkg);
8278                    // We just determined the app is signed correctly, so bring
8279                    // over the latest parsed certs.
8280                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8281                } catch (PackageManagerException e) {
8282                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8283                        throw e;
8284                    }
8285                    // The signature has changed, but this package is in the system
8286                    // image...  let's recover!
8287                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8288                    // However...  if this package is part of a shared user, but it
8289                    // doesn't match the signature of the shared user, let's fail.
8290                    // What this means is that you can't change the signatures
8291                    // associated with an overall shared user, which doesn't seem all
8292                    // that unreasonable.
8293                    if (pkgSetting.sharedUser != null) {
8294                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8295                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8296                            throw new PackageManagerException(
8297                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8298                                    "Signature mismatch for shared user: "
8299                                            + pkgSetting.sharedUser);
8300                        }
8301                    }
8302                    // File a report about this.
8303                    String msg = "System package " + pkg.packageName
8304                            + " signature changed; retaining data.";
8305                    reportSettingsProblem(Log.WARN, msg);
8306                }
8307            }
8308
8309            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8310                // This package wants to adopt ownership of permissions from
8311                // another package.
8312                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8313                    final String origName = pkg.mAdoptPermissions.get(i);
8314                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8315                    if (orig != null) {
8316                        if (verifyPackageUpdateLPr(orig, pkg)) {
8317                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8318                                    + pkg.packageName);
8319                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8320                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8321                        }
8322                    }
8323                }
8324            }
8325        }
8326
8327        pkg.applicationInfo.processName = fixProcessName(
8328                pkg.applicationInfo.packageName,
8329                pkg.applicationInfo.processName);
8330
8331        if (pkg != mPlatformPackage) {
8332            // Get all of our default paths setup
8333            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8334        }
8335
8336        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8337
8338        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8340            derivePackageAbi(
8341                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8343
8344            // Some system apps still use directory structure for native libraries
8345            // in which case we might end up not detecting abi solely based on apk
8346            // structure. Try to detect abi based on directory structure.
8347            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8348                    pkg.applicationInfo.primaryCpuAbi == null) {
8349                setBundledAppAbisAndRoots(pkg, pkgSetting);
8350                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8351            }
8352        } else {
8353            if ((scanFlags & SCAN_MOVE) != 0) {
8354                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8355                // but we already have this packages package info in the PackageSetting. We just
8356                // use that and derive the native library path based on the new codepath.
8357                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8358                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8359            }
8360
8361            // Set native library paths again. For moves, the path will be updated based on the
8362            // ABIs we've determined above. For non-moves, the path will be updated based on the
8363            // ABIs we determined during compilation, but the path will depend on the final
8364            // package path (after the rename away from the stage path).
8365            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8366        }
8367
8368        // This is a special case for the "system" package, where the ABI is
8369        // dictated by the zygote configuration (and init.rc). We should keep track
8370        // of this ABI so that we can deal with "normal" applications that run under
8371        // the same UID correctly.
8372        if (mPlatformPackage == pkg) {
8373            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8374                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8375        }
8376
8377        // If there's a mismatch between the abi-override in the package setting
8378        // and the abiOverride specified for the install. Warn about this because we
8379        // would've already compiled the app without taking the package setting into
8380        // account.
8381        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8382            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8383                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8384                        " for package " + pkg.packageName);
8385            }
8386        }
8387
8388        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8389        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8390        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8391
8392        // Copy the derived override back to the parsed package, so that we can
8393        // update the package settings accordingly.
8394        pkg.cpuAbiOverride = cpuAbiOverride;
8395
8396        if (DEBUG_ABI_SELECTION) {
8397            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8398                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8399                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8400        }
8401
8402        // Push the derived path down into PackageSettings so we know what to
8403        // clean up at uninstall time.
8404        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8405
8406        if (DEBUG_ABI_SELECTION) {
8407            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8408                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8409                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8410        }
8411
8412        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8413        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8414            // We don't do this here during boot because we can do it all
8415            // at once after scanning all existing packages.
8416            //
8417            // We also do this *before* we perform dexopt on this package, so that
8418            // we can avoid redundant dexopts, and also to make sure we've got the
8419            // code and package path correct.
8420            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8421        }
8422
8423        if (mFactoryTest && pkg.requestedPermissions.contains(
8424                android.Manifest.permission.FACTORY_TEST)) {
8425            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8426        }
8427
8428        if (isSystemApp(pkg)) {
8429            pkgSetting.isOrphaned = true;
8430        }
8431
8432        // Take care of first install / last update times.
8433        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8434        if (currentTime != 0) {
8435            if (pkgSetting.firstInstallTime == 0) {
8436                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8437            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8438                pkgSetting.lastUpdateTime = currentTime;
8439            }
8440        } else if (pkgSetting.firstInstallTime == 0) {
8441            // We need *something*.  Take time time stamp of the file.
8442            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8443        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8444            if (scanFileTime != pkgSetting.timeStamp) {
8445                // A package on the system image has changed; consider this
8446                // to be an update.
8447                pkgSetting.lastUpdateTime = scanFileTime;
8448            }
8449        }
8450        pkgSetting.setTimeStamp(scanFileTime);
8451
8452        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8453            if (nonMutatedPs != null) {
8454                synchronized (mPackages) {
8455                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8456                }
8457            }
8458        } else {
8459            // Modify state for the given package setting
8460            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8461                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8462        }
8463        return pkg;
8464    }
8465
8466    /**
8467     * Applies policy to the parsed package based upon the given policy flags.
8468     * Ensures the package is in a good state.
8469     * <p>
8470     * Implementation detail: This method must NOT have any side effect. It would
8471     * ideally be static, but, it requires locks to read system state.
8472     */
8473    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8474        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8475            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8476            if (pkg.applicationInfo.isDirectBootAware()) {
8477                // we're direct boot aware; set for all components
8478                for (PackageParser.Service s : pkg.services) {
8479                    s.info.encryptionAware = s.info.directBootAware = true;
8480                }
8481                for (PackageParser.Provider p : pkg.providers) {
8482                    p.info.encryptionAware = p.info.directBootAware = true;
8483                }
8484                for (PackageParser.Activity a : pkg.activities) {
8485                    a.info.encryptionAware = a.info.directBootAware = true;
8486                }
8487                for (PackageParser.Activity r : pkg.receivers) {
8488                    r.info.encryptionAware = r.info.directBootAware = true;
8489                }
8490            }
8491        } else {
8492            // Only allow system apps to be flagged as core apps.
8493            pkg.coreApp = false;
8494            // clear flags not applicable to regular apps
8495            pkg.applicationInfo.privateFlags &=
8496                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8497            pkg.applicationInfo.privateFlags &=
8498                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8499        }
8500        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8501
8502        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8503            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8504        }
8505
8506        if (!isSystemApp(pkg)) {
8507            // Only system apps can use these features.
8508            pkg.mOriginalPackages = null;
8509            pkg.mRealPackage = null;
8510            pkg.mAdoptPermissions = null;
8511        }
8512    }
8513
8514    /**
8515     * Asserts the parsed package is valid according to teh given policy. If the
8516     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8517     * <p>
8518     * Implementation detail: This method must NOT have any side effects. It would
8519     * ideally be static, but, it requires locks to read system state.
8520     *
8521     * @throws PackageManagerException If the package fails any of the validation checks
8522     */
8523    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags)
8524            throws PackageManagerException {
8525        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8526            assertCodePolicy(pkg);
8527        }
8528
8529        if (pkg.applicationInfo.getCodePath() == null ||
8530                pkg.applicationInfo.getResourcePath() == null) {
8531            // Bail out. The resource and code paths haven't been set.
8532            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8533                    "Code and resource paths haven't been set correctly");
8534        }
8535
8536        // Make sure we're not adding any bogus keyset info
8537        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8538        ksms.assertScannedPackageValid(pkg);
8539
8540        synchronized (mPackages) {
8541            // The special "android" package can only be defined once
8542            if (pkg.packageName.equals("android")) {
8543                if (mAndroidApplication != null) {
8544                    Slog.w(TAG, "*************************************************");
8545                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8546                    Slog.w(TAG, " codePath=" + pkg.codePath);
8547                    Slog.w(TAG, "*************************************************");
8548                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8549                            "Core android package being redefined.  Skipping.");
8550                }
8551            }
8552
8553            // A package name must be unique; don't allow duplicates
8554            if (mPackages.containsKey(pkg.packageName)
8555                    || mSharedLibraries.containsKey(pkg.packageName)) {
8556                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8557                        "Application package " + pkg.packageName
8558                        + " already installed.  Skipping duplicate.");
8559            }
8560
8561            // Only privileged apps and updated privileged apps can add child packages.
8562            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8563                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8564                    throw new PackageManagerException("Only privileged apps can add child "
8565                            + "packages. Ignoring package " + pkg.packageName);
8566                }
8567                final int childCount = pkg.childPackages.size();
8568                for (int i = 0; i < childCount; i++) {
8569                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8570                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8571                            childPkg.packageName)) {
8572                        throw new PackageManagerException("Can't override child of "
8573                                + "another disabled app. Ignoring package " + pkg.packageName);
8574                    }
8575                }
8576            }
8577
8578            // If we're only installing presumed-existing packages, require that the
8579            // scanned APK is both already known and at the path previously established
8580            // for it.  Previously unknown packages we pick up normally, but if we have an
8581            // a priori expectation about this package's install presence, enforce it.
8582            // With a singular exception for new system packages. When an OTA contains
8583            // a new system package, we allow the codepath to change from a system location
8584            // to the user-installed location. If we don't allow this change, any newer,
8585            // user-installed version of the application will be ignored.
8586            if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) {
8587                if (mExpectingBetter.containsKey(pkg.packageName)) {
8588                    logCriticalInfo(Log.WARN,
8589                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8590                } else {
8591                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8592                    if (known != null) {
8593                        if (DEBUG_PACKAGE_SCANNING) {
8594                            Log.d(TAG, "Examining " + pkg.codePath
8595                                    + " and requiring known paths " + known.codePathString
8596                                    + " & " + known.resourcePathString);
8597                        }
8598                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8599                                || !pkg.applicationInfo.getResourcePath().equals(
8600                                        known.resourcePathString)) {
8601                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8602                                    "Application package " + pkg.packageName
8603                                    + " found at " + pkg.applicationInfo.getCodePath()
8604                                    + " but expected at " + known.codePathString
8605                                    + "; ignoring.");
8606                        }
8607                    }
8608                }
8609            }
8610
8611            // Verify that this new package doesn't have any content providers
8612            // that conflict with existing packages.  Only do this if the
8613            // package isn't already installed, since we don't want to break
8614            // things that are installed.
8615            if ((policyFlags & SCAN_NEW_INSTALL) != 0) {
8616                final int N = pkg.providers.size();
8617                int i;
8618                for (i=0; i<N; i++) {
8619                    PackageParser.Provider p = pkg.providers.get(i);
8620                    if (p.info.authority != null) {
8621                        String names[] = p.info.authority.split(";");
8622                        for (int j = 0; j < names.length; j++) {
8623                            if (mProvidersByAuthority.containsKey(names[j])) {
8624                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8625                                final String otherPackageName =
8626                                        ((other != null && other.getComponentName() != null) ?
8627                                                other.getComponentName().getPackageName() : "?");
8628                                throw new PackageManagerException(
8629                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8630                                        "Can't install because provider name " + names[j]
8631                                                + " (in package " + pkg.applicationInfo.packageName
8632                                                + ") is already used by " + otherPackageName);
8633                            }
8634                        }
8635                    }
8636                }
8637            }
8638        }
8639    }
8640
8641    /**
8642     * Adds a scanned package to the system. When this method is finished, the package will
8643     * be available for query, resolution, etc...
8644     */
8645    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8646            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8647        final String pkgName = pkg.packageName;
8648        if (mCustomResolverComponentName != null &&
8649                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8650            setUpCustomResolverActivity(pkg);
8651        }
8652
8653        if (pkg.packageName.equals("android")) {
8654            synchronized (mPackages) {
8655                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8656                    // Set up information for our fall-back user intent resolution activity.
8657                    mPlatformPackage = pkg;
8658                    pkg.mVersionCode = mSdkVersion;
8659                    mAndroidApplication = pkg.applicationInfo;
8660
8661                    if (!mResolverReplaced) {
8662                        mResolveActivity.applicationInfo = mAndroidApplication;
8663                        mResolveActivity.name = ResolverActivity.class.getName();
8664                        mResolveActivity.packageName = mAndroidApplication.packageName;
8665                        mResolveActivity.processName = "system:ui";
8666                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8667                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8668                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8669                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8670                        mResolveActivity.exported = true;
8671                        mResolveActivity.enabled = true;
8672                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8673                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8674                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8675                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8676                                | ActivityInfo.CONFIG_ORIENTATION
8677                                | ActivityInfo.CONFIG_KEYBOARD
8678                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8679                        mResolveInfo.activityInfo = mResolveActivity;
8680                        mResolveInfo.priority = 0;
8681                        mResolveInfo.preferredOrder = 0;
8682                        mResolveInfo.match = 0;
8683                        mResolveComponentName = new ComponentName(
8684                                mAndroidApplication.packageName, mResolveActivity.name);
8685                    }
8686                }
8687            }
8688        }
8689
8690        ArrayList<PackageParser.Package> clientLibPkgs = null;
8691        // writer
8692        synchronized (mPackages) {
8693            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8694                // Only system apps can add new shared libraries.
8695                if (pkg.libraryNames != null) {
8696                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8697                        String name = pkg.libraryNames.get(i);
8698                        boolean allowed = false;
8699                        if (pkg.isUpdatedSystemApp()) {
8700                            // New library entries can only be added through the
8701                            // system image.  This is important to get rid of a lot
8702                            // of nasty edge cases: for example if we allowed a non-
8703                            // system update of the app to add a library, then uninstalling
8704                            // the update would make the library go away, and assumptions
8705                            // we made such as through app install filtering would now
8706                            // have allowed apps on the device which aren't compatible
8707                            // with it.  Better to just have the restriction here, be
8708                            // conservative, and create many fewer cases that can negatively
8709                            // impact the user experience.
8710                            final PackageSetting sysPs = mSettings
8711                                    .getDisabledSystemPkgLPr(pkg.packageName);
8712                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8713                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8714                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8715                                        allowed = true;
8716                                        break;
8717                                    }
8718                                }
8719                            }
8720                        } else {
8721                            allowed = true;
8722                        }
8723                        if (allowed) {
8724                            if (!mSharedLibraries.containsKey(name)) {
8725                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8726                            } else if (!name.equals(pkg.packageName)) {
8727                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8728                                        + name + " already exists; skipping");
8729                            }
8730                        } else {
8731                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8732                                    + name + " that is not declared on system image; skipping");
8733                        }
8734                    }
8735                    if ((scanFlags & SCAN_BOOTING) == 0) {
8736                        // If we are not booting, we need to update any applications
8737                        // that are clients of our shared library.  If we are booting,
8738                        // this will all be done once the scan is complete.
8739                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8740                    }
8741                }
8742            }
8743        }
8744
8745        if ((scanFlags & SCAN_BOOTING) != 0) {
8746            // No apps can run during boot scan, so they don't need to be frozen
8747        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8748            // Caller asked to not kill app, so it's probably not frozen
8749        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8750            // Caller asked us to ignore frozen check for some reason; they
8751            // probably didn't know the package name
8752        } else {
8753            // We're doing major surgery on this package, so it better be frozen
8754            // right now to keep it from launching
8755            checkPackageFrozen(pkgName);
8756        }
8757
8758        // Also need to kill any apps that are dependent on the library.
8759        if (clientLibPkgs != null) {
8760            for (int i=0; i<clientLibPkgs.size(); i++) {
8761                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8762                killApplication(clientPkg.applicationInfo.packageName,
8763                        clientPkg.applicationInfo.uid, "update lib");
8764            }
8765        }
8766
8767        // writer
8768        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8769
8770        boolean createIdmapFailed = false;
8771        synchronized (mPackages) {
8772            // We don't expect installation to fail beyond this point
8773
8774            if (pkgSetting.pkg != null) {
8775                // Note that |user| might be null during the initial boot scan. If a codePath
8776                // for an app has changed during a boot scan, it's due to an app update that's
8777                // part of the system partition and marker changes must be applied to all users.
8778                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8779                final int[] userIds = resolveUserIds(userId);
8780                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8781            }
8782
8783            // Add the new setting to mSettings
8784            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8785            // Add the new setting to mPackages
8786            mPackages.put(pkg.applicationInfo.packageName, pkg);
8787            // Make sure we don't accidentally delete its data.
8788            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8789            while (iter.hasNext()) {
8790                PackageCleanItem item = iter.next();
8791                if (pkgName.equals(item.packageName)) {
8792                    iter.remove();
8793                }
8794            }
8795
8796            // Add the package's KeySets to the global KeySetManagerService
8797            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8798            ksms.addScannedPackageLPw(pkg);
8799
8800            int N = pkg.providers.size();
8801            StringBuilder r = null;
8802            int i;
8803            for (i=0; i<N; i++) {
8804                PackageParser.Provider p = pkg.providers.get(i);
8805                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8806                        p.info.processName);
8807                mProviders.addProvider(p);
8808                p.syncable = p.info.isSyncable;
8809                if (p.info.authority != null) {
8810                    String names[] = p.info.authority.split(";");
8811                    p.info.authority = null;
8812                    for (int j = 0; j < names.length; j++) {
8813                        if (j == 1 && p.syncable) {
8814                            // We only want the first authority for a provider to possibly be
8815                            // syncable, so if we already added this provider using a different
8816                            // authority clear the syncable flag. We copy the provider before
8817                            // changing it because the mProviders object contains a reference
8818                            // to a provider that we don't want to change.
8819                            // Only do this for the second authority since the resulting provider
8820                            // object can be the same for all future authorities for this provider.
8821                            p = new PackageParser.Provider(p);
8822                            p.syncable = false;
8823                        }
8824                        if (!mProvidersByAuthority.containsKey(names[j])) {
8825                            mProvidersByAuthority.put(names[j], p);
8826                            if (p.info.authority == null) {
8827                                p.info.authority = names[j];
8828                            } else {
8829                                p.info.authority = p.info.authority + ";" + names[j];
8830                            }
8831                            if (DEBUG_PACKAGE_SCANNING) {
8832                                if (chatty)
8833                                    Log.d(TAG, "Registered content provider: " + names[j]
8834                                            + ", className = " + p.info.name + ", isSyncable = "
8835                                            + p.info.isSyncable);
8836                            }
8837                        } else {
8838                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8839                            Slog.w(TAG, "Skipping provider name " + names[j] +
8840                                    " (in package " + pkg.applicationInfo.packageName +
8841                                    "): name already used by "
8842                                    + ((other != null && other.getComponentName() != null)
8843                                            ? other.getComponentName().getPackageName() : "?"));
8844                        }
8845                    }
8846                }
8847                if (chatty) {
8848                    if (r == null) {
8849                        r = new StringBuilder(256);
8850                    } else {
8851                        r.append(' ');
8852                    }
8853                    r.append(p.info.name);
8854                }
8855            }
8856            if (r != null) {
8857                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8858            }
8859
8860            N = pkg.services.size();
8861            r = null;
8862            for (i=0; i<N; i++) {
8863                PackageParser.Service s = pkg.services.get(i);
8864                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8865                        s.info.processName);
8866                mServices.addService(s);
8867                if (chatty) {
8868                    if (r == null) {
8869                        r = new StringBuilder(256);
8870                    } else {
8871                        r.append(' ');
8872                    }
8873                    r.append(s.info.name);
8874                }
8875            }
8876            if (r != null) {
8877                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8878            }
8879
8880            N = pkg.receivers.size();
8881            r = null;
8882            for (i=0; i<N; i++) {
8883                PackageParser.Activity a = pkg.receivers.get(i);
8884                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8885                        a.info.processName);
8886                mReceivers.addActivity(a, "receiver");
8887                if (chatty) {
8888                    if (r == null) {
8889                        r = new StringBuilder(256);
8890                    } else {
8891                        r.append(' ');
8892                    }
8893                    r.append(a.info.name);
8894                }
8895            }
8896            if (r != null) {
8897                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8898            }
8899
8900            N = pkg.activities.size();
8901            r = null;
8902            for (i=0; i<N; i++) {
8903                PackageParser.Activity a = pkg.activities.get(i);
8904                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8905                        a.info.processName);
8906                mActivities.addActivity(a, "activity");
8907                if (chatty) {
8908                    if (r == null) {
8909                        r = new StringBuilder(256);
8910                    } else {
8911                        r.append(' ');
8912                    }
8913                    r.append(a.info.name);
8914                }
8915            }
8916            if (r != null) {
8917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8918            }
8919
8920            N = pkg.permissionGroups.size();
8921            r = null;
8922            for (i=0; i<N; i++) {
8923                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8924                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8925                final String curPackageName = cur == null ? null : cur.info.packageName;
8926                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8927                if (cur == null || isPackageUpdate) {
8928                    mPermissionGroups.put(pg.info.name, pg);
8929                    if (chatty) {
8930                        if (r == null) {
8931                            r = new StringBuilder(256);
8932                        } else {
8933                            r.append(' ');
8934                        }
8935                        if (isPackageUpdate) {
8936                            r.append("UPD:");
8937                        }
8938                        r.append(pg.info.name);
8939                    }
8940                } else {
8941                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8942                            + pg.info.packageName + " ignored: original from "
8943                            + cur.info.packageName);
8944                    if (chatty) {
8945                        if (r == null) {
8946                            r = new StringBuilder(256);
8947                        } else {
8948                            r.append(' ');
8949                        }
8950                        r.append("DUP:");
8951                        r.append(pg.info.name);
8952                    }
8953                }
8954            }
8955            if (r != null) {
8956                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8957            }
8958
8959            N = pkg.permissions.size();
8960            r = null;
8961            for (i=0; i<N; i++) {
8962                PackageParser.Permission p = pkg.permissions.get(i);
8963
8964                // Assume by default that we did not install this permission into the system.
8965                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8966
8967                // Now that permission groups have a special meaning, we ignore permission
8968                // groups for legacy apps to prevent unexpected behavior. In particular,
8969                // permissions for one app being granted to someone just becase they happen
8970                // to be in a group defined by another app (before this had no implications).
8971                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8972                    p.group = mPermissionGroups.get(p.info.group);
8973                    // Warn for a permission in an unknown group.
8974                    if (p.info.group != null && p.group == null) {
8975                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8976                                + p.info.packageName + " in an unknown group " + p.info.group);
8977                    }
8978                }
8979
8980                ArrayMap<String, BasePermission> permissionMap =
8981                        p.tree ? mSettings.mPermissionTrees
8982                                : mSettings.mPermissions;
8983                BasePermission bp = permissionMap.get(p.info.name);
8984
8985                // Allow system apps to redefine non-system permissions
8986                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8987                    final boolean currentOwnerIsSystem = (bp.perm != null
8988                            && isSystemApp(bp.perm.owner));
8989                    if (isSystemApp(p.owner)) {
8990                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8991                            // It's a built-in permission and no owner, take ownership now
8992                            bp.packageSetting = pkgSetting;
8993                            bp.perm = p;
8994                            bp.uid = pkg.applicationInfo.uid;
8995                            bp.sourcePackage = p.info.packageName;
8996                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8997                        } else if (!currentOwnerIsSystem) {
8998                            String msg = "New decl " + p.owner + " of permission  "
8999                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9000                            reportSettingsProblem(Log.WARN, msg);
9001                            bp = null;
9002                        }
9003                    }
9004                }
9005
9006                if (bp == null) {
9007                    bp = new BasePermission(p.info.name, p.info.packageName,
9008                            BasePermission.TYPE_NORMAL);
9009                    permissionMap.put(p.info.name, bp);
9010                }
9011
9012                if (bp.perm == null) {
9013                    if (bp.sourcePackage == null
9014                            || bp.sourcePackage.equals(p.info.packageName)) {
9015                        BasePermission tree = findPermissionTreeLP(p.info.name);
9016                        if (tree == null
9017                                || tree.sourcePackage.equals(p.info.packageName)) {
9018                            bp.packageSetting = pkgSetting;
9019                            bp.perm = p;
9020                            bp.uid = pkg.applicationInfo.uid;
9021                            bp.sourcePackage = p.info.packageName;
9022                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9023                            if (chatty) {
9024                                if (r == null) {
9025                                    r = new StringBuilder(256);
9026                                } else {
9027                                    r.append(' ');
9028                                }
9029                                r.append(p.info.name);
9030                            }
9031                        } else {
9032                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9033                                    + p.info.packageName + " ignored: base tree "
9034                                    + tree.name + " is from package "
9035                                    + tree.sourcePackage);
9036                        }
9037                    } else {
9038                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9039                                + p.info.packageName + " ignored: original from "
9040                                + bp.sourcePackage);
9041                    }
9042                } else if (chatty) {
9043                    if (r == null) {
9044                        r = new StringBuilder(256);
9045                    } else {
9046                        r.append(' ');
9047                    }
9048                    r.append("DUP:");
9049                    r.append(p.info.name);
9050                }
9051                if (bp.perm == p) {
9052                    bp.protectionLevel = p.info.protectionLevel;
9053                }
9054            }
9055
9056            if (r != null) {
9057                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9058            }
9059
9060            N = pkg.instrumentation.size();
9061            r = null;
9062            for (i=0; i<N; i++) {
9063                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9064                a.info.packageName = pkg.applicationInfo.packageName;
9065                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9066                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9067                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9068                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9069                a.info.dataDir = pkg.applicationInfo.dataDir;
9070                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9071                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9072                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9073                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9074                mInstrumentation.put(a.getComponentName(), a);
9075                if (chatty) {
9076                    if (r == null) {
9077                        r = new StringBuilder(256);
9078                    } else {
9079                        r.append(' ');
9080                    }
9081                    r.append(a.info.name);
9082                }
9083            }
9084            if (r != null) {
9085                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9086            }
9087
9088            if (pkg.protectedBroadcasts != null) {
9089                N = pkg.protectedBroadcasts.size();
9090                for (i=0; i<N; i++) {
9091                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9092                }
9093            }
9094
9095            // Create idmap files for pairs of (packages, overlay packages).
9096            // Note: "android", ie framework-res.apk, is handled by native layers.
9097            if (pkg.mOverlayTarget != null) {
9098                // This is an overlay package.
9099                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9100                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9101                        mOverlays.put(pkg.mOverlayTarget,
9102                                new ArrayMap<String, PackageParser.Package>());
9103                    }
9104                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9105                    map.put(pkg.packageName, pkg);
9106                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9107                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9108                        createIdmapFailed = true;
9109                    }
9110                }
9111            } else if (mOverlays.containsKey(pkg.packageName) &&
9112                    !pkg.packageName.equals("android")) {
9113                // This is a regular package, with one or more known overlay packages.
9114                createIdmapsForPackageLI(pkg);
9115            }
9116        }
9117
9118        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9119
9120        if (createIdmapFailed) {
9121            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9122                    "scanPackageLI failed to createIdmap");
9123        }
9124    }
9125
9126    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9127            PackageParser.Package update, int[] userIds) {
9128        if (existing.applicationInfo == null || update.applicationInfo == null) {
9129            // This isn't due to an app installation.
9130            return;
9131        }
9132
9133        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9134        final File newCodePath = new File(update.applicationInfo.getCodePath());
9135
9136        // The codePath hasn't changed, so there's nothing for us to do.
9137        if (Objects.equals(oldCodePath, newCodePath)) {
9138            return;
9139        }
9140
9141        File canonicalNewCodePath;
9142        try {
9143            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9144        } catch (IOException e) {
9145            Slog.w(TAG, "Failed to get canonical path.", e);
9146            return;
9147        }
9148
9149        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9150        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9151        // that the last component of the path (i.e, the name) doesn't need canonicalization
9152        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9153        // but may change in the future. Hopefully this function won't exist at that point.
9154        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9155                oldCodePath.getName());
9156
9157        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9158        // with "@".
9159        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9160        if (!oldMarkerPrefix.endsWith("@")) {
9161            oldMarkerPrefix += "@";
9162        }
9163        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9164        if (!newMarkerPrefix.endsWith("@")) {
9165            newMarkerPrefix += "@";
9166        }
9167
9168        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9169        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9170        for (String updatedPath : updatedPaths) {
9171            String updatedPathName = new File(updatedPath).getName();
9172            markerSuffixes.add(updatedPathName.replace('/', '@'));
9173        }
9174
9175        for (int userId : userIds) {
9176            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9177
9178            for (String markerSuffix : markerSuffixes) {
9179                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9180                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9181                if (oldForeignUseMark.exists()) {
9182                    try {
9183                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9184                                newForeignUseMark.getAbsolutePath());
9185                    } catch (ErrnoException e) {
9186                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9187                        oldForeignUseMark.delete();
9188                    }
9189                }
9190            }
9191        }
9192    }
9193
9194    /**
9195     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9196     * is derived purely on the basis of the contents of {@code scanFile} and
9197     * {@code cpuAbiOverride}.
9198     *
9199     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9200     */
9201    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9202                                 String cpuAbiOverride, boolean extractLibs,
9203                                 File appLib32InstallDir)
9204            throws PackageManagerException {
9205        // TODO: We can probably be smarter about this stuff. For installed apps,
9206        // we can calculate this information at install time once and for all. For
9207        // system apps, we can probably assume that this information doesn't change
9208        // after the first boot scan. As things stand, we do lots of unnecessary work.
9209
9210        // Give ourselves some initial paths; we'll come back for another
9211        // pass once we've determined ABI below.
9212        setNativeLibraryPaths(pkg, appLib32InstallDir);
9213
9214        // We would never need to extract libs for forward-locked and external packages,
9215        // since the container service will do it for us. We shouldn't attempt to
9216        // extract libs from system app when it was not updated.
9217        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9218                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9219            extractLibs = false;
9220        }
9221
9222        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9223        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9224
9225        NativeLibraryHelper.Handle handle = null;
9226        try {
9227            handle = NativeLibraryHelper.Handle.create(pkg);
9228            // TODO(multiArch): This can be null for apps that didn't go through the
9229            // usual installation process. We can calculate it again, like we
9230            // do during install time.
9231            //
9232            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9233            // unnecessary.
9234            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9235
9236            // Null out the abis so that they can be recalculated.
9237            pkg.applicationInfo.primaryCpuAbi = null;
9238            pkg.applicationInfo.secondaryCpuAbi = null;
9239            if (isMultiArch(pkg.applicationInfo)) {
9240                // Warn if we've set an abiOverride for multi-lib packages..
9241                // By definition, we need to copy both 32 and 64 bit libraries for
9242                // such packages.
9243                if (pkg.cpuAbiOverride != null
9244                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9245                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9246                }
9247
9248                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9249                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9250                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9251                    if (extractLibs) {
9252                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9253                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9254                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9255                                useIsaSpecificSubdirs);
9256                    } else {
9257                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9258                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9259                    }
9260                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9261                }
9262
9263                maybeThrowExceptionForMultiArchCopy(
9264                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9265
9266                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9267                    if (extractLibs) {
9268                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9269                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9270                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9271                                useIsaSpecificSubdirs);
9272                    } else {
9273                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9274                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9275                    }
9276                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9277                }
9278
9279                maybeThrowExceptionForMultiArchCopy(
9280                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9281
9282                if (abi64 >= 0) {
9283                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9284                }
9285
9286                if (abi32 >= 0) {
9287                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9288                    if (abi64 >= 0) {
9289                        if (pkg.use32bitAbi) {
9290                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9291                            pkg.applicationInfo.primaryCpuAbi = abi;
9292                        } else {
9293                            pkg.applicationInfo.secondaryCpuAbi = abi;
9294                        }
9295                    } else {
9296                        pkg.applicationInfo.primaryCpuAbi = abi;
9297                    }
9298                }
9299
9300            } else {
9301                String[] abiList = (cpuAbiOverride != null) ?
9302                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9303
9304                // Enable gross and lame hacks for apps that are built with old
9305                // SDK tools. We must scan their APKs for renderscript bitcode and
9306                // not launch them if it's present. Don't bother checking on devices
9307                // that don't have 64 bit support.
9308                boolean needsRenderScriptOverride = false;
9309                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9310                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9311                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9312                    needsRenderScriptOverride = true;
9313                }
9314
9315                final int copyRet;
9316                if (extractLibs) {
9317                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9318                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9319                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9320                } else {
9321                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9322                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9323                }
9324                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9325
9326                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9327                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9328                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9329                }
9330
9331                if (copyRet >= 0) {
9332                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9333                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9334                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9335                } else if (needsRenderScriptOverride) {
9336                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9337                }
9338            }
9339        } catch (IOException ioe) {
9340            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9341        } finally {
9342            IoUtils.closeQuietly(handle);
9343        }
9344
9345        // Now that we've calculated the ABIs and determined if it's an internal app,
9346        // we will go ahead and populate the nativeLibraryPath.
9347        setNativeLibraryPaths(pkg, appLib32InstallDir);
9348    }
9349
9350    /**
9351     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9352     * i.e, so that all packages can be run inside a single process if required.
9353     *
9354     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9355     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9356     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9357     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9358     * updating a package that belongs to a shared user.
9359     *
9360     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9361     * adds unnecessary complexity.
9362     */
9363    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9364            PackageParser.Package scannedPackage) {
9365        String requiredInstructionSet = null;
9366        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9367            requiredInstructionSet = VMRuntime.getInstructionSet(
9368                     scannedPackage.applicationInfo.primaryCpuAbi);
9369        }
9370
9371        PackageSetting requirer = null;
9372        for (PackageSetting ps : packagesForUser) {
9373            // If packagesForUser contains scannedPackage, we skip it. This will happen
9374            // when scannedPackage is an update of an existing package. Without this check,
9375            // we will never be able to change the ABI of any package belonging to a shared
9376            // user, even if it's compatible with other packages.
9377            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9378                if (ps.primaryCpuAbiString == null) {
9379                    continue;
9380                }
9381
9382                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9383                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9384                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9385                    // this but there's not much we can do.
9386                    String errorMessage = "Instruction set mismatch, "
9387                            + ((requirer == null) ? "[caller]" : requirer)
9388                            + " requires " + requiredInstructionSet + " whereas " + ps
9389                            + " requires " + instructionSet;
9390                    Slog.w(TAG, errorMessage);
9391                }
9392
9393                if (requiredInstructionSet == null) {
9394                    requiredInstructionSet = instructionSet;
9395                    requirer = ps;
9396                }
9397            }
9398        }
9399
9400        if (requiredInstructionSet != null) {
9401            String adjustedAbi;
9402            if (requirer != null) {
9403                // requirer != null implies that either scannedPackage was null or that scannedPackage
9404                // did not require an ABI, in which case we have to adjust scannedPackage to match
9405                // the ABI of the set (which is the same as requirer's ABI)
9406                adjustedAbi = requirer.primaryCpuAbiString;
9407                if (scannedPackage != null) {
9408                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9409                }
9410            } else {
9411                // requirer == null implies that we're updating all ABIs in the set to
9412                // match scannedPackage.
9413                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9414            }
9415
9416            for (PackageSetting ps : packagesForUser) {
9417                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9418                    if (ps.primaryCpuAbiString != null) {
9419                        continue;
9420                    }
9421
9422                    ps.primaryCpuAbiString = adjustedAbi;
9423                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9424                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9425                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9426                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9427                                + " (requirer="
9428                                + (requirer == null ? "null" : requirer.pkg.packageName)
9429                                + ", scannedPackage="
9430                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9431                                + ")");
9432                        try {
9433                            mInstaller.rmdex(ps.codePathString,
9434                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9435                        } catch (InstallerException ignored) {
9436                        }
9437                    }
9438                }
9439            }
9440        }
9441    }
9442
9443    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9444        synchronized (mPackages) {
9445            mResolverReplaced = true;
9446            // Set up information for custom user intent resolution activity.
9447            mResolveActivity.applicationInfo = pkg.applicationInfo;
9448            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9449            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9450            mResolveActivity.processName = pkg.applicationInfo.packageName;
9451            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9452            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9453                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9454            mResolveActivity.theme = 0;
9455            mResolveActivity.exported = true;
9456            mResolveActivity.enabled = true;
9457            mResolveInfo.activityInfo = mResolveActivity;
9458            mResolveInfo.priority = 0;
9459            mResolveInfo.preferredOrder = 0;
9460            mResolveInfo.match = 0;
9461            mResolveComponentName = mCustomResolverComponentName;
9462            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9463                    mResolveComponentName);
9464        }
9465    }
9466
9467    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9468        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9469
9470        // Set up information for ephemeral installer activity
9471        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9472        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9473        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9474        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9475        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9476        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9477                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9478        mEphemeralInstallerActivity.theme = 0;
9479        mEphemeralInstallerActivity.exported = true;
9480        mEphemeralInstallerActivity.enabled = true;
9481        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9482        mEphemeralInstallerInfo.priority = 0;
9483        mEphemeralInstallerInfo.preferredOrder = 1;
9484        mEphemeralInstallerInfo.isDefault = true;
9485        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9486                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9487
9488        if (DEBUG_EPHEMERAL) {
9489            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9490        }
9491    }
9492
9493    private static String calculateBundledApkRoot(final String codePathString) {
9494        final File codePath = new File(codePathString);
9495        final File codeRoot;
9496        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9497            codeRoot = Environment.getRootDirectory();
9498        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9499            codeRoot = Environment.getOemDirectory();
9500        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9501            codeRoot = Environment.getVendorDirectory();
9502        } else {
9503            // Unrecognized code path; take its top real segment as the apk root:
9504            // e.g. /something/app/blah.apk => /something
9505            try {
9506                File f = codePath.getCanonicalFile();
9507                File parent = f.getParentFile();    // non-null because codePath is a file
9508                File tmp;
9509                while ((tmp = parent.getParentFile()) != null) {
9510                    f = parent;
9511                    parent = tmp;
9512                }
9513                codeRoot = f;
9514                Slog.w(TAG, "Unrecognized code path "
9515                        + codePath + " - using " + codeRoot);
9516            } catch (IOException e) {
9517                // Can't canonicalize the code path -- shenanigans?
9518                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9519                return Environment.getRootDirectory().getPath();
9520            }
9521        }
9522        return codeRoot.getPath();
9523    }
9524
9525    /**
9526     * Derive and set the location of native libraries for the given package,
9527     * which varies depending on where and how the package was installed.
9528     */
9529    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9530        final ApplicationInfo info = pkg.applicationInfo;
9531        final String codePath = pkg.codePath;
9532        final File codeFile = new File(codePath);
9533        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9534        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9535
9536        info.nativeLibraryRootDir = null;
9537        info.nativeLibraryRootRequiresIsa = false;
9538        info.nativeLibraryDir = null;
9539        info.secondaryNativeLibraryDir = null;
9540
9541        if (isApkFile(codeFile)) {
9542            // Monolithic install
9543            if (bundledApp) {
9544                // If "/system/lib64/apkname" exists, assume that is the per-package
9545                // native library directory to use; otherwise use "/system/lib/apkname".
9546                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9547                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9548                        getPrimaryInstructionSet(info));
9549
9550                // This is a bundled system app so choose the path based on the ABI.
9551                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9552                // is just the default path.
9553                final String apkName = deriveCodePathName(codePath);
9554                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9555                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9556                        apkName).getAbsolutePath();
9557
9558                if (info.secondaryCpuAbi != null) {
9559                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9560                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9561                            secondaryLibDir, apkName).getAbsolutePath();
9562                }
9563            } else if (asecApp) {
9564                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9565                        .getAbsolutePath();
9566            } else {
9567                final String apkName = deriveCodePathName(codePath);
9568                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9569                        .getAbsolutePath();
9570            }
9571
9572            info.nativeLibraryRootRequiresIsa = false;
9573            info.nativeLibraryDir = info.nativeLibraryRootDir;
9574        } else {
9575            // Cluster install
9576            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9577            info.nativeLibraryRootRequiresIsa = true;
9578
9579            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9580                    getPrimaryInstructionSet(info)).getAbsolutePath();
9581
9582            if (info.secondaryCpuAbi != null) {
9583                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9584                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9585            }
9586        }
9587    }
9588
9589    /**
9590     * Calculate the abis and roots for a bundled app. These can uniquely
9591     * be determined from the contents of the system partition, i.e whether
9592     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9593     * of this information, and instead assume that the system was built
9594     * sensibly.
9595     */
9596    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9597                                           PackageSetting pkgSetting) {
9598        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9599
9600        // If "/system/lib64/apkname" exists, assume that is the per-package
9601        // native library directory to use; otherwise use "/system/lib/apkname".
9602        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9603        setBundledAppAbi(pkg, apkRoot, apkName);
9604        // pkgSetting might be null during rescan following uninstall of updates
9605        // to a bundled app, so accommodate that possibility.  The settings in
9606        // that case will be established later from the parsed package.
9607        //
9608        // If the settings aren't null, sync them up with what we've just derived.
9609        // note that apkRoot isn't stored in the package settings.
9610        if (pkgSetting != null) {
9611            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9612            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9613        }
9614    }
9615
9616    /**
9617     * Deduces the ABI of a bundled app and sets the relevant fields on the
9618     * parsed pkg object.
9619     *
9620     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9621     *        under which system libraries are installed.
9622     * @param apkName the name of the installed package.
9623     */
9624    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9625        final File codeFile = new File(pkg.codePath);
9626
9627        final boolean has64BitLibs;
9628        final boolean has32BitLibs;
9629        if (isApkFile(codeFile)) {
9630            // Monolithic install
9631            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9632            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9633        } else {
9634            // Cluster install
9635            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9636            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9637                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9638                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9639                has64BitLibs = (new File(rootDir, isa)).exists();
9640            } else {
9641                has64BitLibs = false;
9642            }
9643            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9644                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9645                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9646                has32BitLibs = (new File(rootDir, isa)).exists();
9647            } else {
9648                has32BitLibs = false;
9649            }
9650        }
9651
9652        if (has64BitLibs && !has32BitLibs) {
9653            // The package has 64 bit libs, but not 32 bit libs. Its primary
9654            // ABI should be 64 bit. We can safely assume here that the bundled
9655            // native libraries correspond to the most preferred ABI in the list.
9656
9657            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9658            pkg.applicationInfo.secondaryCpuAbi = null;
9659        } else if (has32BitLibs && !has64BitLibs) {
9660            // The package has 32 bit libs but not 64 bit libs. Its primary
9661            // ABI should be 32 bit.
9662
9663            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9664            pkg.applicationInfo.secondaryCpuAbi = null;
9665        } else if (has32BitLibs && has64BitLibs) {
9666            // The application has both 64 and 32 bit bundled libraries. We check
9667            // here that the app declares multiArch support, and warn if it doesn't.
9668            //
9669            // We will be lenient here and record both ABIs. The primary will be the
9670            // ABI that's higher on the list, i.e, a device that's configured to prefer
9671            // 64 bit apps will see a 64 bit primary ABI,
9672
9673            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9674                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9675            }
9676
9677            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9678                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9679                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9680            } else {
9681                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9682                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9683            }
9684        } else {
9685            pkg.applicationInfo.primaryCpuAbi = null;
9686            pkg.applicationInfo.secondaryCpuAbi = null;
9687        }
9688    }
9689
9690    private void killApplication(String pkgName, int appId, String reason) {
9691        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9692    }
9693
9694    private void killApplication(String pkgName, int appId, int userId, String reason) {
9695        // Request the ActivityManager to kill the process(only for existing packages)
9696        // so that we do not end up in a confused state while the user is still using the older
9697        // version of the application while the new one gets installed.
9698        final long token = Binder.clearCallingIdentity();
9699        try {
9700            IActivityManager am = ActivityManagerNative.getDefault();
9701            if (am != null) {
9702                try {
9703                    am.killApplication(pkgName, appId, userId, reason);
9704                } catch (RemoteException e) {
9705                }
9706            }
9707        } finally {
9708            Binder.restoreCallingIdentity(token);
9709        }
9710    }
9711
9712    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9713        // Remove the parent package setting
9714        PackageSetting ps = (PackageSetting) pkg.mExtras;
9715        if (ps != null) {
9716            removePackageLI(ps, chatty);
9717        }
9718        // Remove the child package setting
9719        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9720        for (int i = 0; i < childCount; i++) {
9721            PackageParser.Package childPkg = pkg.childPackages.get(i);
9722            ps = (PackageSetting) childPkg.mExtras;
9723            if (ps != null) {
9724                removePackageLI(ps, chatty);
9725            }
9726        }
9727    }
9728
9729    void removePackageLI(PackageSetting ps, boolean chatty) {
9730        if (DEBUG_INSTALL) {
9731            if (chatty)
9732                Log.d(TAG, "Removing package " + ps.name);
9733        }
9734
9735        // writer
9736        synchronized (mPackages) {
9737            mPackages.remove(ps.name);
9738            final PackageParser.Package pkg = ps.pkg;
9739            if (pkg != null) {
9740                cleanPackageDataStructuresLILPw(pkg, chatty);
9741            }
9742        }
9743    }
9744
9745    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9746        if (DEBUG_INSTALL) {
9747            if (chatty)
9748                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9749        }
9750
9751        // writer
9752        synchronized (mPackages) {
9753            // Remove the parent package
9754            mPackages.remove(pkg.applicationInfo.packageName);
9755            cleanPackageDataStructuresLILPw(pkg, chatty);
9756
9757            // Remove the child packages
9758            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9759            for (int i = 0; i < childCount; i++) {
9760                PackageParser.Package childPkg = pkg.childPackages.get(i);
9761                mPackages.remove(childPkg.applicationInfo.packageName);
9762                cleanPackageDataStructuresLILPw(childPkg, chatty);
9763            }
9764        }
9765    }
9766
9767    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9768        int N = pkg.providers.size();
9769        StringBuilder r = null;
9770        int i;
9771        for (i=0; i<N; i++) {
9772            PackageParser.Provider p = pkg.providers.get(i);
9773            mProviders.removeProvider(p);
9774            if (p.info.authority == null) {
9775
9776                /* There was another ContentProvider with this authority when
9777                 * this app was installed so this authority is null,
9778                 * Ignore it as we don't have to unregister the provider.
9779                 */
9780                continue;
9781            }
9782            String names[] = p.info.authority.split(";");
9783            for (int j = 0; j < names.length; j++) {
9784                if (mProvidersByAuthority.get(names[j]) == p) {
9785                    mProvidersByAuthority.remove(names[j]);
9786                    if (DEBUG_REMOVE) {
9787                        if (chatty)
9788                            Log.d(TAG, "Unregistered content provider: " + names[j]
9789                                    + ", className = " + p.info.name + ", isSyncable = "
9790                                    + p.info.isSyncable);
9791                    }
9792                }
9793            }
9794            if (DEBUG_REMOVE && chatty) {
9795                if (r == null) {
9796                    r = new StringBuilder(256);
9797                } else {
9798                    r.append(' ');
9799                }
9800                r.append(p.info.name);
9801            }
9802        }
9803        if (r != null) {
9804            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9805        }
9806
9807        N = pkg.services.size();
9808        r = null;
9809        for (i=0; i<N; i++) {
9810            PackageParser.Service s = pkg.services.get(i);
9811            mServices.removeService(s);
9812            if (chatty) {
9813                if (r == null) {
9814                    r = new StringBuilder(256);
9815                } else {
9816                    r.append(' ');
9817                }
9818                r.append(s.info.name);
9819            }
9820        }
9821        if (r != null) {
9822            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9823        }
9824
9825        N = pkg.receivers.size();
9826        r = null;
9827        for (i=0; i<N; i++) {
9828            PackageParser.Activity a = pkg.receivers.get(i);
9829            mReceivers.removeActivity(a, "receiver");
9830            if (DEBUG_REMOVE && chatty) {
9831                if (r == null) {
9832                    r = new StringBuilder(256);
9833                } else {
9834                    r.append(' ');
9835                }
9836                r.append(a.info.name);
9837            }
9838        }
9839        if (r != null) {
9840            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9841        }
9842
9843        N = pkg.activities.size();
9844        r = null;
9845        for (i=0; i<N; i++) {
9846            PackageParser.Activity a = pkg.activities.get(i);
9847            mActivities.removeActivity(a, "activity");
9848            if (DEBUG_REMOVE && chatty) {
9849                if (r == null) {
9850                    r = new StringBuilder(256);
9851                } else {
9852                    r.append(' ');
9853                }
9854                r.append(a.info.name);
9855            }
9856        }
9857        if (r != null) {
9858            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9859        }
9860
9861        N = pkg.permissions.size();
9862        r = null;
9863        for (i=0; i<N; i++) {
9864            PackageParser.Permission p = pkg.permissions.get(i);
9865            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9866            if (bp == null) {
9867                bp = mSettings.mPermissionTrees.get(p.info.name);
9868            }
9869            if (bp != null && bp.perm == p) {
9870                bp.perm = null;
9871                if (DEBUG_REMOVE && chatty) {
9872                    if (r == null) {
9873                        r = new StringBuilder(256);
9874                    } else {
9875                        r.append(' ');
9876                    }
9877                    r.append(p.info.name);
9878                }
9879            }
9880            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9881                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9882                if (appOpPkgs != null) {
9883                    appOpPkgs.remove(pkg.packageName);
9884                }
9885            }
9886        }
9887        if (r != null) {
9888            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9889        }
9890
9891        N = pkg.requestedPermissions.size();
9892        r = null;
9893        for (i=0; i<N; i++) {
9894            String perm = pkg.requestedPermissions.get(i);
9895            BasePermission bp = mSettings.mPermissions.get(perm);
9896            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9897                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9898                if (appOpPkgs != null) {
9899                    appOpPkgs.remove(pkg.packageName);
9900                    if (appOpPkgs.isEmpty()) {
9901                        mAppOpPermissionPackages.remove(perm);
9902                    }
9903                }
9904            }
9905        }
9906        if (r != null) {
9907            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9908        }
9909
9910        N = pkg.instrumentation.size();
9911        r = null;
9912        for (i=0; i<N; i++) {
9913            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9914            mInstrumentation.remove(a.getComponentName());
9915            if (DEBUG_REMOVE && chatty) {
9916                if (r == null) {
9917                    r = new StringBuilder(256);
9918                } else {
9919                    r.append(' ');
9920                }
9921                r.append(a.info.name);
9922            }
9923        }
9924        if (r != null) {
9925            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9926        }
9927
9928        r = null;
9929        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9930            // Only system apps can hold shared libraries.
9931            if (pkg.libraryNames != null) {
9932                for (i=0; i<pkg.libraryNames.size(); i++) {
9933                    String name = pkg.libraryNames.get(i);
9934                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9935                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9936                        mSharedLibraries.remove(name);
9937                        if (DEBUG_REMOVE && chatty) {
9938                            if (r == null) {
9939                                r = new StringBuilder(256);
9940                            } else {
9941                                r.append(' ');
9942                            }
9943                            r.append(name);
9944                        }
9945                    }
9946                }
9947            }
9948        }
9949        if (r != null) {
9950            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9951        }
9952    }
9953
9954    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9955        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9956            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9957                return true;
9958            }
9959        }
9960        return false;
9961    }
9962
9963    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9964    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9965    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9966
9967    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9968        // Update the parent permissions
9969        updatePermissionsLPw(pkg.packageName, pkg, flags);
9970        // Update the child permissions
9971        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9972        for (int i = 0; i < childCount; i++) {
9973            PackageParser.Package childPkg = pkg.childPackages.get(i);
9974            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9975        }
9976    }
9977
9978    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9979            int flags) {
9980        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9981        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9982    }
9983
9984    private void updatePermissionsLPw(String changingPkg,
9985            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9986        // Make sure there are no dangling permission trees.
9987        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9988        while (it.hasNext()) {
9989            final BasePermission bp = it.next();
9990            if (bp.packageSetting == null) {
9991                // We may not yet have parsed the package, so just see if
9992                // we still know about its settings.
9993                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9994            }
9995            if (bp.packageSetting == null) {
9996                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9997                        + " from package " + bp.sourcePackage);
9998                it.remove();
9999            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10000                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10001                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10002                            + " from package " + bp.sourcePackage);
10003                    flags |= UPDATE_PERMISSIONS_ALL;
10004                    it.remove();
10005                }
10006            }
10007        }
10008
10009        // Make sure all dynamic permissions have been assigned to a package,
10010        // and make sure there are no dangling permissions.
10011        it = mSettings.mPermissions.values().iterator();
10012        while (it.hasNext()) {
10013            final BasePermission bp = it.next();
10014            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10015                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10016                        + bp.name + " pkg=" + bp.sourcePackage
10017                        + " info=" + bp.pendingInfo);
10018                if (bp.packageSetting == null && bp.pendingInfo != null) {
10019                    final BasePermission tree = findPermissionTreeLP(bp.name);
10020                    if (tree != null && tree.perm != null) {
10021                        bp.packageSetting = tree.packageSetting;
10022                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10023                                new PermissionInfo(bp.pendingInfo));
10024                        bp.perm.info.packageName = tree.perm.info.packageName;
10025                        bp.perm.info.name = bp.name;
10026                        bp.uid = tree.uid;
10027                    }
10028                }
10029            }
10030            if (bp.packageSetting == null) {
10031                // We may not yet have parsed the package, so just see if
10032                // we still know about its settings.
10033                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10034            }
10035            if (bp.packageSetting == null) {
10036                Slog.w(TAG, "Removing dangling permission: " + bp.name
10037                        + " from package " + bp.sourcePackage);
10038                it.remove();
10039            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10040                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10041                    Slog.i(TAG, "Removing old permission: " + bp.name
10042                            + " from package " + bp.sourcePackage);
10043                    flags |= UPDATE_PERMISSIONS_ALL;
10044                    it.remove();
10045                }
10046            }
10047        }
10048
10049        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10050        // Now update the permissions for all packages, in particular
10051        // replace the granted permissions of the system packages.
10052        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10053            for (PackageParser.Package pkg : mPackages.values()) {
10054                if (pkg != pkgInfo) {
10055                    // Only replace for packages on requested volume
10056                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10057                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10058                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10059                    grantPermissionsLPw(pkg, replace, changingPkg);
10060                }
10061            }
10062        }
10063
10064        if (pkgInfo != null) {
10065            // Only replace for packages on requested volume
10066            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10067            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10068                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10069            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10070        }
10071        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10072    }
10073
10074    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10075            String packageOfInterest) {
10076        // IMPORTANT: There are two types of permissions: install and runtime.
10077        // Install time permissions are granted when the app is installed to
10078        // all device users and users added in the future. Runtime permissions
10079        // are granted at runtime explicitly to specific users. Normal and signature
10080        // protected permissions are install time permissions. Dangerous permissions
10081        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10082        // otherwise they are runtime permissions. This function does not manage
10083        // runtime permissions except for the case an app targeting Lollipop MR1
10084        // being upgraded to target a newer SDK, in which case dangerous permissions
10085        // are transformed from install time to runtime ones.
10086
10087        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10088        if (ps == null) {
10089            return;
10090        }
10091
10092        PermissionsState permissionsState = ps.getPermissionsState();
10093        PermissionsState origPermissions = permissionsState;
10094
10095        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10096
10097        boolean runtimePermissionsRevoked = false;
10098        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10099
10100        boolean changedInstallPermission = false;
10101
10102        if (replace) {
10103            ps.installPermissionsFixed = false;
10104            if (!ps.isSharedUser()) {
10105                origPermissions = new PermissionsState(permissionsState);
10106                permissionsState.reset();
10107            } else {
10108                // We need to know only about runtime permission changes since the
10109                // calling code always writes the install permissions state but
10110                // the runtime ones are written only if changed. The only cases of
10111                // changed runtime permissions here are promotion of an install to
10112                // runtime and revocation of a runtime from a shared user.
10113                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10114                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10115                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10116                    runtimePermissionsRevoked = true;
10117                }
10118            }
10119        }
10120
10121        permissionsState.setGlobalGids(mGlobalGids);
10122
10123        final int N = pkg.requestedPermissions.size();
10124        for (int i=0; i<N; i++) {
10125            final String name = pkg.requestedPermissions.get(i);
10126            final BasePermission bp = mSettings.mPermissions.get(name);
10127
10128            if (DEBUG_INSTALL) {
10129                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10130            }
10131
10132            if (bp == null || bp.packageSetting == null) {
10133                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10134                    Slog.w(TAG, "Unknown permission " + name
10135                            + " in package " + pkg.packageName);
10136                }
10137                continue;
10138            }
10139
10140
10141            // Limit ephemeral apps to ephemeral allowed permissions.
10142            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10143                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10144                        + pkg.packageName);
10145                continue;
10146            }
10147
10148            final String perm = bp.name;
10149            boolean allowedSig = false;
10150            int grant = GRANT_DENIED;
10151
10152            // Keep track of app op permissions.
10153            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10154                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10155                if (pkgs == null) {
10156                    pkgs = new ArraySet<>();
10157                    mAppOpPermissionPackages.put(bp.name, pkgs);
10158                }
10159                pkgs.add(pkg.packageName);
10160            }
10161
10162            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10163            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10164                    >= Build.VERSION_CODES.M;
10165            switch (level) {
10166                case PermissionInfo.PROTECTION_NORMAL: {
10167                    // For all apps normal permissions are install time ones.
10168                    grant = GRANT_INSTALL;
10169                } break;
10170
10171                case PermissionInfo.PROTECTION_DANGEROUS: {
10172                    // If a permission review is required for legacy apps we represent
10173                    // their permissions as always granted runtime ones since we need
10174                    // to keep the review required permission flag per user while an
10175                    // install permission's state is shared across all users.
10176                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10177                        // For legacy apps dangerous permissions are install time ones.
10178                        grant = GRANT_INSTALL;
10179                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10180                        // For legacy apps that became modern, install becomes runtime.
10181                        grant = GRANT_UPGRADE;
10182                    } else if (mPromoteSystemApps
10183                            && isSystemApp(ps)
10184                            && mExistingSystemPackages.contains(ps.name)) {
10185                        // For legacy system apps, install becomes runtime.
10186                        // We cannot check hasInstallPermission() for system apps since those
10187                        // permissions were granted implicitly and not persisted pre-M.
10188                        grant = GRANT_UPGRADE;
10189                    } else {
10190                        // For modern apps keep runtime permissions unchanged.
10191                        grant = GRANT_RUNTIME;
10192                    }
10193                } break;
10194
10195                case PermissionInfo.PROTECTION_SIGNATURE: {
10196                    // For all apps signature permissions are install time ones.
10197                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10198                    if (allowedSig) {
10199                        grant = GRANT_INSTALL;
10200                    }
10201                } break;
10202            }
10203
10204            if (DEBUG_INSTALL) {
10205                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10206            }
10207
10208            if (grant != GRANT_DENIED) {
10209                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10210                    // If this is an existing, non-system package, then
10211                    // we can't add any new permissions to it.
10212                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10213                        // Except...  if this is a permission that was added
10214                        // to the platform (note: need to only do this when
10215                        // updating the platform).
10216                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10217                            grant = GRANT_DENIED;
10218                        }
10219                    }
10220                }
10221
10222                switch (grant) {
10223                    case GRANT_INSTALL: {
10224                        // Revoke this as runtime permission to handle the case of
10225                        // a runtime permission being downgraded to an install one.
10226                        // Also in permission review mode we keep dangerous permissions
10227                        // for legacy apps
10228                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10229                            if (origPermissions.getRuntimePermissionState(
10230                                    bp.name, userId) != null) {
10231                                // Revoke the runtime permission and clear the flags.
10232                                origPermissions.revokeRuntimePermission(bp, userId);
10233                                origPermissions.updatePermissionFlags(bp, userId,
10234                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10235                                // If we revoked a permission permission, we have to write.
10236                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10237                                        changedRuntimePermissionUserIds, userId);
10238                            }
10239                        }
10240                        // Grant an install permission.
10241                        if (permissionsState.grantInstallPermission(bp) !=
10242                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10243                            changedInstallPermission = true;
10244                        }
10245                    } break;
10246
10247                    case GRANT_RUNTIME: {
10248                        // Grant previously granted runtime permissions.
10249                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10250                            PermissionState permissionState = origPermissions
10251                                    .getRuntimePermissionState(bp.name, userId);
10252                            int flags = permissionState != null
10253                                    ? permissionState.getFlags() : 0;
10254                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10255                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10256                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10257                                    // If we cannot put the permission as it was, we have to write.
10258                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10259                                            changedRuntimePermissionUserIds, userId);
10260                                }
10261                                // If the app supports runtime permissions no need for a review.
10262                                if (mPermissionReviewRequired
10263                                        && appSupportsRuntimePermissions
10264                                        && (flags & PackageManager
10265                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10266                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10267                                    // Since we changed the flags, we have to write.
10268                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10269                                            changedRuntimePermissionUserIds, userId);
10270                                }
10271                            } else if (mPermissionReviewRequired
10272                                    && !appSupportsRuntimePermissions) {
10273                                // For legacy apps that need a permission review, every new
10274                                // runtime permission is granted but it is pending a review.
10275                                // We also need to review only platform defined runtime
10276                                // permissions as these are the only ones the platform knows
10277                                // how to disable the API to simulate revocation as legacy
10278                                // apps don't expect to run with revoked permissions.
10279                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10280                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10281                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10282                                        // We changed the flags, hence have to write.
10283                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10284                                                changedRuntimePermissionUserIds, userId);
10285                                    }
10286                                }
10287                                if (permissionsState.grantRuntimePermission(bp, userId)
10288                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10289                                    // We changed the permission, hence have to write.
10290                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10291                                            changedRuntimePermissionUserIds, userId);
10292                                }
10293                            }
10294                            // Propagate the permission flags.
10295                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10296                        }
10297                    } break;
10298
10299                    case GRANT_UPGRADE: {
10300                        // Grant runtime permissions for a previously held install permission.
10301                        PermissionState permissionState = origPermissions
10302                                .getInstallPermissionState(bp.name);
10303                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10304
10305                        if (origPermissions.revokeInstallPermission(bp)
10306                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10307                            // We will be transferring the permission flags, so clear them.
10308                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10309                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10310                            changedInstallPermission = true;
10311                        }
10312
10313                        // If the permission is not to be promoted to runtime we ignore it and
10314                        // also its other flags as they are not applicable to install permissions.
10315                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10316                            for (int userId : currentUserIds) {
10317                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10318                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10319                                    // Transfer the permission flags.
10320                                    permissionsState.updatePermissionFlags(bp, userId,
10321                                            flags, flags);
10322                                    // If we granted the permission, we have to write.
10323                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10324                                            changedRuntimePermissionUserIds, userId);
10325                                }
10326                            }
10327                        }
10328                    } break;
10329
10330                    default: {
10331                        if (packageOfInterest == null
10332                                || packageOfInterest.equals(pkg.packageName)) {
10333                            Slog.w(TAG, "Not granting permission " + perm
10334                                    + " to package " + pkg.packageName
10335                                    + " because it was previously installed without");
10336                        }
10337                    } break;
10338                }
10339            } else {
10340                if (permissionsState.revokeInstallPermission(bp) !=
10341                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10342                    // Also drop the permission flags.
10343                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10344                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10345                    changedInstallPermission = true;
10346                    Slog.i(TAG, "Un-granting permission " + perm
10347                            + " from package " + pkg.packageName
10348                            + " (protectionLevel=" + bp.protectionLevel
10349                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10350                            + ")");
10351                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10352                    // Don't print warning for app op permissions, since it is fine for them
10353                    // not to be granted, there is a UI for the user to decide.
10354                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10355                        Slog.w(TAG, "Not granting permission " + perm
10356                                + " to package " + pkg.packageName
10357                                + " (protectionLevel=" + bp.protectionLevel
10358                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10359                                + ")");
10360                    }
10361                }
10362            }
10363        }
10364
10365        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10366                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10367            // This is the first that we have heard about this package, so the
10368            // permissions we have now selected are fixed until explicitly
10369            // changed.
10370            ps.installPermissionsFixed = true;
10371        }
10372
10373        // Persist the runtime permissions state for users with changes. If permissions
10374        // were revoked because no app in the shared user declares them we have to
10375        // write synchronously to avoid losing runtime permissions state.
10376        for (int userId : changedRuntimePermissionUserIds) {
10377            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10378        }
10379    }
10380
10381    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10382        boolean allowed = false;
10383        final int NP = PackageParser.NEW_PERMISSIONS.length;
10384        for (int ip=0; ip<NP; ip++) {
10385            final PackageParser.NewPermissionInfo npi
10386                    = PackageParser.NEW_PERMISSIONS[ip];
10387            if (npi.name.equals(perm)
10388                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10389                allowed = true;
10390                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10391                        + pkg.packageName);
10392                break;
10393            }
10394        }
10395        return allowed;
10396    }
10397
10398    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10399            BasePermission bp, PermissionsState origPermissions) {
10400        boolean allowed;
10401        allowed = (compareSignatures(
10402                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10403                        == PackageManager.SIGNATURE_MATCH)
10404                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10405                        == PackageManager.SIGNATURE_MATCH);
10406        if (!allowed && (bp.protectionLevel
10407                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10408            if (isSystemApp(pkg)) {
10409                // For updated system applications, a system permission
10410                // is granted only if it had been defined by the original application.
10411                if (pkg.isUpdatedSystemApp()) {
10412                    final PackageSetting sysPs = mSettings
10413                            .getDisabledSystemPkgLPr(pkg.packageName);
10414                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10415                        // If the original was granted this permission, we take
10416                        // that grant decision as read and propagate it to the
10417                        // update.
10418                        if (sysPs.isPrivileged()) {
10419                            allowed = true;
10420                        }
10421                    } else {
10422                        // The system apk may have been updated with an older
10423                        // version of the one on the data partition, but which
10424                        // granted a new system permission that it didn't have
10425                        // before.  In this case we do want to allow the app to
10426                        // now get the new permission if the ancestral apk is
10427                        // privileged to get it.
10428                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10429                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10430                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10431                                    allowed = true;
10432                                    break;
10433                                }
10434                            }
10435                        }
10436                        // Also if a privileged parent package on the system image or any of
10437                        // its children requested a privileged permission, the updated child
10438                        // packages can also get the permission.
10439                        if (pkg.parentPackage != null) {
10440                            final PackageSetting disabledSysParentPs = mSettings
10441                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10442                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10443                                    && disabledSysParentPs.isPrivileged()) {
10444                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10445                                    allowed = true;
10446                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10447                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10448                                    for (int i = 0; i < count; i++) {
10449                                        PackageParser.Package disabledSysChildPkg =
10450                                                disabledSysParentPs.pkg.childPackages.get(i);
10451                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10452                                                perm)) {
10453                                            allowed = true;
10454                                            break;
10455                                        }
10456                                    }
10457                                }
10458                            }
10459                        }
10460                    }
10461                } else {
10462                    allowed = isPrivilegedApp(pkg);
10463                }
10464            }
10465        }
10466        if (!allowed) {
10467            if (!allowed && (bp.protectionLevel
10468                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10469                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10470                // If this was a previously normal/dangerous permission that got moved
10471                // to a system permission as part of the runtime permission redesign, then
10472                // we still want to blindly grant it to old apps.
10473                allowed = true;
10474            }
10475            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10476                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10477                // If this permission is to be granted to the system installer and
10478                // this app is an installer, then it gets the permission.
10479                allowed = true;
10480            }
10481            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10482                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10483                // If this permission is to be granted to the system verifier and
10484                // this app is a verifier, then it gets the permission.
10485                allowed = true;
10486            }
10487            if (!allowed && (bp.protectionLevel
10488                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10489                    && isSystemApp(pkg)) {
10490                // Any pre-installed system app is allowed to get this permission.
10491                allowed = true;
10492            }
10493            if (!allowed && (bp.protectionLevel
10494                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10495                // For development permissions, a development permission
10496                // is granted only if it was already granted.
10497                allowed = origPermissions.hasInstallPermission(perm);
10498            }
10499            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10500                    && pkg.packageName.equals(mSetupWizardPackage)) {
10501                // If this permission is to be granted to the system setup wizard and
10502                // this app is a setup wizard, then it gets the permission.
10503                allowed = true;
10504            }
10505        }
10506        return allowed;
10507    }
10508
10509    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10510        final int permCount = pkg.requestedPermissions.size();
10511        for (int j = 0; j < permCount; j++) {
10512            String requestedPermission = pkg.requestedPermissions.get(j);
10513            if (permission.equals(requestedPermission)) {
10514                return true;
10515            }
10516        }
10517        return false;
10518    }
10519
10520    final class ActivityIntentResolver
10521            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10522        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10523                boolean defaultOnly, int userId) {
10524            if (!sUserManager.exists(userId)) return null;
10525            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10526            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10527        }
10528
10529        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10530                int userId) {
10531            if (!sUserManager.exists(userId)) return null;
10532            mFlags = flags;
10533            return super.queryIntent(intent, resolvedType,
10534                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10535        }
10536
10537        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10538                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10539            if (!sUserManager.exists(userId)) return null;
10540            if (packageActivities == null) {
10541                return null;
10542            }
10543            mFlags = flags;
10544            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10545            final int N = packageActivities.size();
10546            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10547                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10548
10549            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10550            for (int i = 0; i < N; ++i) {
10551                intentFilters = packageActivities.get(i).intents;
10552                if (intentFilters != null && intentFilters.size() > 0) {
10553                    PackageParser.ActivityIntentInfo[] array =
10554                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10555                    intentFilters.toArray(array);
10556                    listCut.add(array);
10557                }
10558            }
10559            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10560        }
10561
10562        /**
10563         * Finds a privileged activity that matches the specified activity names.
10564         */
10565        private PackageParser.Activity findMatchingActivity(
10566                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10567            for (PackageParser.Activity sysActivity : activityList) {
10568                if (sysActivity.info.name.equals(activityInfo.name)) {
10569                    return sysActivity;
10570                }
10571                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10572                    return sysActivity;
10573                }
10574                if (sysActivity.info.targetActivity != null) {
10575                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10576                        return sysActivity;
10577                    }
10578                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10579                        return sysActivity;
10580                    }
10581                }
10582            }
10583            return null;
10584        }
10585
10586        public class IterGenerator<E> {
10587            public Iterator<E> generate(ActivityIntentInfo info) {
10588                return null;
10589            }
10590        }
10591
10592        public class ActionIterGenerator extends IterGenerator<String> {
10593            @Override
10594            public Iterator<String> generate(ActivityIntentInfo info) {
10595                return info.actionsIterator();
10596            }
10597        }
10598
10599        public class CategoriesIterGenerator extends IterGenerator<String> {
10600            @Override
10601            public Iterator<String> generate(ActivityIntentInfo info) {
10602                return info.categoriesIterator();
10603            }
10604        }
10605
10606        public class SchemesIterGenerator extends IterGenerator<String> {
10607            @Override
10608            public Iterator<String> generate(ActivityIntentInfo info) {
10609                return info.schemesIterator();
10610            }
10611        }
10612
10613        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10614            @Override
10615            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10616                return info.authoritiesIterator();
10617            }
10618        }
10619
10620        /**
10621         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10622         * MODIFIED. Do not pass in a list that should not be changed.
10623         */
10624        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10625                IterGenerator<T> generator, Iterator<T> searchIterator) {
10626            // loop through the set of actions; every one must be found in the intent filter
10627            while (searchIterator.hasNext()) {
10628                // we must have at least one filter in the list to consider a match
10629                if (intentList.size() == 0) {
10630                    break;
10631                }
10632
10633                final T searchAction = searchIterator.next();
10634
10635                // loop through the set of intent filters
10636                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10637                while (intentIter.hasNext()) {
10638                    final ActivityIntentInfo intentInfo = intentIter.next();
10639                    boolean selectionFound = false;
10640
10641                    // loop through the intent filter's selection criteria; at least one
10642                    // of them must match the searched criteria
10643                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10644                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10645                        final T intentSelection = intentSelectionIter.next();
10646                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10647                            selectionFound = true;
10648                            break;
10649                        }
10650                    }
10651
10652                    // the selection criteria wasn't found in this filter's set; this filter
10653                    // is not a potential match
10654                    if (!selectionFound) {
10655                        intentIter.remove();
10656                    }
10657                }
10658            }
10659        }
10660
10661        private boolean isProtectedAction(ActivityIntentInfo filter) {
10662            final Iterator<String> actionsIter = filter.actionsIterator();
10663            while (actionsIter != null && actionsIter.hasNext()) {
10664                final String filterAction = actionsIter.next();
10665                if (PROTECTED_ACTIONS.contains(filterAction)) {
10666                    return true;
10667                }
10668            }
10669            return false;
10670        }
10671
10672        /**
10673         * Adjusts the priority of the given intent filter according to policy.
10674         * <p>
10675         * <ul>
10676         * <li>The priority for non privileged applications is capped to '0'</li>
10677         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10678         * <li>The priority for unbundled updates to privileged applications is capped to the
10679         *      priority defined on the system partition</li>
10680         * </ul>
10681         * <p>
10682         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10683         * allowed to obtain any priority on any action.
10684         */
10685        private void adjustPriority(
10686                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10687            // nothing to do; priority is fine as-is
10688            if (intent.getPriority() <= 0) {
10689                return;
10690            }
10691
10692            final ActivityInfo activityInfo = intent.activity.info;
10693            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10694
10695            final boolean privilegedApp =
10696                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10697            if (!privilegedApp) {
10698                // non-privileged applications can never define a priority >0
10699                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10700                        + " package: " + applicationInfo.packageName
10701                        + " activity: " + intent.activity.className
10702                        + " origPrio: " + intent.getPriority());
10703                intent.setPriority(0);
10704                return;
10705            }
10706
10707            if (systemActivities == null) {
10708                // the system package is not disabled; we're parsing the system partition
10709                if (isProtectedAction(intent)) {
10710                    if (mDeferProtectedFilters) {
10711                        // We can't deal with these just yet. No component should ever obtain a
10712                        // >0 priority for a protected actions, with ONE exception -- the setup
10713                        // wizard. The setup wizard, however, cannot be known until we're able to
10714                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10715                        // until all intent filters have been processed. Chicken, meet egg.
10716                        // Let the filter temporarily have a high priority and rectify the
10717                        // priorities after all system packages have been scanned.
10718                        mProtectedFilters.add(intent);
10719                        if (DEBUG_FILTERS) {
10720                            Slog.i(TAG, "Protected action; save for later;"
10721                                    + " package: " + applicationInfo.packageName
10722                                    + " activity: " + intent.activity.className
10723                                    + " origPrio: " + intent.getPriority());
10724                        }
10725                        return;
10726                    } else {
10727                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10728                            Slog.i(TAG, "No setup wizard;"
10729                                + " All protected intents capped to priority 0");
10730                        }
10731                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10732                            if (DEBUG_FILTERS) {
10733                                Slog.i(TAG, "Found setup wizard;"
10734                                    + " allow priority " + intent.getPriority() + ";"
10735                                    + " package: " + intent.activity.info.packageName
10736                                    + " activity: " + intent.activity.className
10737                                    + " priority: " + intent.getPriority());
10738                            }
10739                            // setup wizard gets whatever it wants
10740                            return;
10741                        }
10742                        Slog.w(TAG, "Protected action; cap priority to 0;"
10743                                + " package: " + intent.activity.info.packageName
10744                                + " activity: " + intent.activity.className
10745                                + " origPrio: " + intent.getPriority());
10746                        intent.setPriority(0);
10747                        return;
10748                    }
10749                }
10750                // privileged apps on the system image get whatever priority they request
10751                return;
10752            }
10753
10754            // privileged app unbundled update ... try to find the same activity
10755            final PackageParser.Activity foundActivity =
10756                    findMatchingActivity(systemActivities, activityInfo);
10757            if (foundActivity == null) {
10758                // this is a new activity; it cannot obtain >0 priority
10759                if (DEBUG_FILTERS) {
10760                    Slog.i(TAG, "New activity; cap priority to 0;"
10761                            + " package: " + applicationInfo.packageName
10762                            + " activity: " + intent.activity.className
10763                            + " origPrio: " + intent.getPriority());
10764                }
10765                intent.setPriority(0);
10766                return;
10767            }
10768
10769            // found activity, now check for filter equivalence
10770
10771            // a shallow copy is enough; we modify the list, not its contents
10772            final List<ActivityIntentInfo> intentListCopy =
10773                    new ArrayList<>(foundActivity.intents);
10774            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10775
10776            // find matching action subsets
10777            final Iterator<String> actionsIterator = intent.actionsIterator();
10778            if (actionsIterator != null) {
10779                getIntentListSubset(
10780                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10781                if (intentListCopy.size() == 0) {
10782                    // no more intents to match; we're not equivalent
10783                    if (DEBUG_FILTERS) {
10784                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10785                                + " package: " + applicationInfo.packageName
10786                                + " activity: " + intent.activity.className
10787                                + " origPrio: " + intent.getPriority());
10788                    }
10789                    intent.setPriority(0);
10790                    return;
10791                }
10792            }
10793
10794            // find matching category subsets
10795            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10796            if (categoriesIterator != null) {
10797                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10798                        categoriesIterator);
10799                if (intentListCopy.size() == 0) {
10800                    // no more intents to match; we're not equivalent
10801                    if (DEBUG_FILTERS) {
10802                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10803                                + " package: " + applicationInfo.packageName
10804                                + " activity: " + intent.activity.className
10805                                + " origPrio: " + intent.getPriority());
10806                    }
10807                    intent.setPriority(0);
10808                    return;
10809                }
10810            }
10811
10812            // find matching schemes subsets
10813            final Iterator<String> schemesIterator = intent.schemesIterator();
10814            if (schemesIterator != null) {
10815                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10816                        schemesIterator);
10817                if (intentListCopy.size() == 0) {
10818                    // no more intents to match; we're not equivalent
10819                    if (DEBUG_FILTERS) {
10820                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10821                                + " package: " + applicationInfo.packageName
10822                                + " activity: " + intent.activity.className
10823                                + " origPrio: " + intent.getPriority());
10824                    }
10825                    intent.setPriority(0);
10826                    return;
10827                }
10828            }
10829
10830            // find matching authorities subsets
10831            final Iterator<IntentFilter.AuthorityEntry>
10832                    authoritiesIterator = intent.authoritiesIterator();
10833            if (authoritiesIterator != null) {
10834                getIntentListSubset(intentListCopy,
10835                        new AuthoritiesIterGenerator(),
10836                        authoritiesIterator);
10837                if (intentListCopy.size() == 0) {
10838                    // no more intents to match; we're not equivalent
10839                    if (DEBUG_FILTERS) {
10840                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10841                                + " package: " + applicationInfo.packageName
10842                                + " activity: " + intent.activity.className
10843                                + " origPrio: " + intent.getPriority());
10844                    }
10845                    intent.setPriority(0);
10846                    return;
10847                }
10848            }
10849
10850            // we found matching filter(s); app gets the max priority of all intents
10851            int cappedPriority = 0;
10852            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10853                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10854            }
10855            if (intent.getPriority() > cappedPriority) {
10856                if (DEBUG_FILTERS) {
10857                    Slog.i(TAG, "Found matching filter(s);"
10858                            + " cap priority to " + cappedPriority + ";"
10859                            + " package: " + applicationInfo.packageName
10860                            + " activity: " + intent.activity.className
10861                            + " origPrio: " + intent.getPriority());
10862                }
10863                intent.setPriority(cappedPriority);
10864                return;
10865            }
10866            // all this for nothing; the requested priority was <= what was on the system
10867        }
10868
10869        public final void addActivity(PackageParser.Activity a, String type) {
10870            mActivities.put(a.getComponentName(), a);
10871            if (DEBUG_SHOW_INFO)
10872                Log.v(
10873                TAG, "  " + type + " " +
10874                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10875            if (DEBUG_SHOW_INFO)
10876                Log.v(TAG, "    Class=" + a.info.name);
10877            final int NI = a.intents.size();
10878            for (int j=0; j<NI; j++) {
10879                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10880                if ("activity".equals(type)) {
10881                    final PackageSetting ps =
10882                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10883                    final List<PackageParser.Activity> systemActivities =
10884                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10885                    adjustPriority(systemActivities, intent);
10886                }
10887                if (DEBUG_SHOW_INFO) {
10888                    Log.v(TAG, "    IntentFilter:");
10889                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10890                }
10891                if (!intent.debugCheck()) {
10892                    Log.w(TAG, "==> For Activity " + a.info.name);
10893                }
10894                addFilter(intent);
10895            }
10896        }
10897
10898        public final void removeActivity(PackageParser.Activity a, String type) {
10899            mActivities.remove(a.getComponentName());
10900            if (DEBUG_SHOW_INFO) {
10901                Log.v(TAG, "  " + type + " "
10902                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10903                                : a.info.name) + ":");
10904                Log.v(TAG, "    Class=" + a.info.name);
10905            }
10906            final int NI = a.intents.size();
10907            for (int j=0; j<NI; j++) {
10908                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10909                if (DEBUG_SHOW_INFO) {
10910                    Log.v(TAG, "    IntentFilter:");
10911                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10912                }
10913                removeFilter(intent);
10914            }
10915        }
10916
10917        @Override
10918        protected boolean allowFilterResult(
10919                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10920            ActivityInfo filterAi = filter.activity.info;
10921            for (int i=dest.size()-1; i>=0; i--) {
10922                ActivityInfo destAi = dest.get(i).activityInfo;
10923                if (destAi.name == filterAi.name
10924                        && destAi.packageName == filterAi.packageName) {
10925                    return false;
10926                }
10927            }
10928            return true;
10929        }
10930
10931        @Override
10932        protected ActivityIntentInfo[] newArray(int size) {
10933            return new ActivityIntentInfo[size];
10934        }
10935
10936        @Override
10937        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10938            if (!sUserManager.exists(userId)) return true;
10939            PackageParser.Package p = filter.activity.owner;
10940            if (p != null) {
10941                PackageSetting ps = (PackageSetting)p.mExtras;
10942                if (ps != null) {
10943                    // System apps are never considered stopped for purposes of
10944                    // filtering, because there may be no way for the user to
10945                    // actually re-launch them.
10946                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10947                            && ps.getStopped(userId);
10948                }
10949            }
10950            return false;
10951        }
10952
10953        @Override
10954        protected boolean isPackageForFilter(String packageName,
10955                PackageParser.ActivityIntentInfo info) {
10956            return packageName.equals(info.activity.owner.packageName);
10957        }
10958
10959        @Override
10960        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10961                int match, int userId) {
10962            if (!sUserManager.exists(userId)) return null;
10963            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10964                return null;
10965            }
10966            final PackageParser.Activity activity = info.activity;
10967            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10968            if (ps == null) {
10969                return null;
10970            }
10971            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10972                    ps.readUserState(userId), userId);
10973            if (ai == null) {
10974                return null;
10975            }
10976            final ResolveInfo res = new ResolveInfo();
10977            res.activityInfo = ai;
10978            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10979                res.filter = info;
10980            }
10981            if (info != null) {
10982                res.handleAllWebDataURI = info.handleAllWebDataURI();
10983            }
10984            res.priority = info.getPriority();
10985            res.preferredOrder = activity.owner.mPreferredOrder;
10986            //System.out.println("Result: " + res.activityInfo.className +
10987            //                   " = " + res.priority);
10988            res.match = match;
10989            res.isDefault = info.hasDefault;
10990            res.labelRes = info.labelRes;
10991            res.nonLocalizedLabel = info.nonLocalizedLabel;
10992            if (userNeedsBadging(userId)) {
10993                res.noResourceId = true;
10994            } else {
10995                res.icon = info.icon;
10996            }
10997            res.iconResourceId = info.icon;
10998            res.system = res.activityInfo.applicationInfo.isSystemApp();
10999            return res;
11000        }
11001
11002        @Override
11003        protected void sortResults(List<ResolveInfo> results) {
11004            Collections.sort(results, mResolvePrioritySorter);
11005        }
11006
11007        @Override
11008        protected void dumpFilter(PrintWriter out, String prefix,
11009                PackageParser.ActivityIntentInfo filter) {
11010            out.print(prefix); out.print(
11011                    Integer.toHexString(System.identityHashCode(filter.activity)));
11012                    out.print(' ');
11013                    filter.activity.printComponentShortName(out);
11014                    out.print(" filter ");
11015                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11016        }
11017
11018        @Override
11019        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11020            return filter.activity;
11021        }
11022
11023        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11024            PackageParser.Activity activity = (PackageParser.Activity)label;
11025            out.print(prefix); out.print(
11026                    Integer.toHexString(System.identityHashCode(activity)));
11027                    out.print(' ');
11028                    activity.printComponentShortName(out);
11029            if (count > 1) {
11030                out.print(" ("); out.print(count); out.print(" filters)");
11031            }
11032            out.println();
11033        }
11034
11035        // Keys are String (activity class name), values are Activity.
11036        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11037                = new ArrayMap<ComponentName, PackageParser.Activity>();
11038        private int mFlags;
11039    }
11040
11041    private final class ServiceIntentResolver
11042            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11043        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11044                boolean defaultOnly, int userId) {
11045            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11046            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11047        }
11048
11049        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11050                int userId) {
11051            if (!sUserManager.exists(userId)) return null;
11052            mFlags = flags;
11053            return super.queryIntent(intent, resolvedType,
11054                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11055        }
11056
11057        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11058                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11059            if (!sUserManager.exists(userId)) return null;
11060            if (packageServices == null) {
11061                return null;
11062            }
11063            mFlags = flags;
11064            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11065            final int N = packageServices.size();
11066            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11067                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11068
11069            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11070            for (int i = 0; i < N; ++i) {
11071                intentFilters = packageServices.get(i).intents;
11072                if (intentFilters != null && intentFilters.size() > 0) {
11073                    PackageParser.ServiceIntentInfo[] array =
11074                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11075                    intentFilters.toArray(array);
11076                    listCut.add(array);
11077                }
11078            }
11079            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11080        }
11081
11082        public final void addService(PackageParser.Service s) {
11083            mServices.put(s.getComponentName(), s);
11084            if (DEBUG_SHOW_INFO) {
11085                Log.v(TAG, "  "
11086                        + (s.info.nonLocalizedLabel != null
11087                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11088                Log.v(TAG, "    Class=" + s.info.name);
11089            }
11090            final int NI = s.intents.size();
11091            int j;
11092            for (j=0; j<NI; j++) {
11093                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11094                if (DEBUG_SHOW_INFO) {
11095                    Log.v(TAG, "    IntentFilter:");
11096                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11097                }
11098                if (!intent.debugCheck()) {
11099                    Log.w(TAG, "==> For Service " + s.info.name);
11100                }
11101                addFilter(intent);
11102            }
11103        }
11104
11105        public final void removeService(PackageParser.Service s) {
11106            mServices.remove(s.getComponentName());
11107            if (DEBUG_SHOW_INFO) {
11108                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11109                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11110                Log.v(TAG, "    Class=" + s.info.name);
11111            }
11112            final int NI = s.intents.size();
11113            int j;
11114            for (j=0; j<NI; j++) {
11115                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11116                if (DEBUG_SHOW_INFO) {
11117                    Log.v(TAG, "    IntentFilter:");
11118                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11119                }
11120                removeFilter(intent);
11121            }
11122        }
11123
11124        @Override
11125        protected boolean allowFilterResult(
11126                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11127            ServiceInfo filterSi = filter.service.info;
11128            for (int i=dest.size()-1; i>=0; i--) {
11129                ServiceInfo destAi = dest.get(i).serviceInfo;
11130                if (destAi.name == filterSi.name
11131                        && destAi.packageName == filterSi.packageName) {
11132                    return false;
11133                }
11134            }
11135            return true;
11136        }
11137
11138        @Override
11139        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11140            return new PackageParser.ServiceIntentInfo[size];
11141        }
11142
11143        @Override
11144        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11145            if (!sUserManager.exists(userId)) return true;
11146            PackageParser.Package p = filter.service.owner;
11147            if (p != null) {
11148                PackageSetting ps = (PackageSetting)p.mExtras;
11149                if (ps != null) {
11150                    // System apps are never considered stopped for purposes of
11151                    // filtering, because there may be no way for the user to
11152                    // actually re-launch them.
11153                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11154                            && ps.getStopped(userId);
11155                }
11156            }
11157            return false;
11158        }
11159
11160        @Override
11161        protected boolean isPackageForFilter(String packageName,
11162                PackageParser.ServiceIntentInfo info) {
11163            return packageName.equals(info.service.owner.packageName);
11164        }
11165
11166        @Override
11167        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11168                int match, int userId) {
11169            if (!sUserManager.exists(userId)) return null;
11170            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11171            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11172                return null;
11173            }
11174            final PackageParser.Service service = info.service;
11175            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11176            if (ps == null) {
11177                return null;
11178            }
11179            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11180                    ps.readUserState(userId), userId);
11181            if (si == null) {
11182                return null;
11183            }
11184            final ResolveInfo res = new ResolveInfo();
11185            res.serviceInfo = si;
11186            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11187                res.filter = filter;
11188            }
11189            res.priority = info.getPriority();
11190            res.preferredOrder = service.owner.mPreferredOrder;
11191            res.match = match;
11192            res.isDefault = info.hasDefault;
11193            res.labelRes = info.labelRes;
11194            res.nonLocalizedLabel = info.nonLocalizedLabel;
11195            res.icon = info.icon;
11196            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11197            return res;
11198        }
11199
11200        @Override
11201        protected void sortResults(List<ResolveInfo> results) {
11202            Collections.sort(results, mResolvePrioritySorter);
11203        }
11204
11205        @Override
11206        protected void dumpFilter(PrintWriter out, String prefix,
11207                PackageParser.ServiceIntentInfo filter) {
11208            out.print(prefix); out.print(
11209                    Integer.toHexString(System.identityHashCode(filter.service)));
11210                    out.print(' ');
11211                    filter.service.printComponentShortName(out);
11212                    out.print(" filter ");
11213                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11214        }
11215
11216        @Override
11217        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11218            return filter.service;
11219        }
11220
11221        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11222            PackageParser.Service service = (PackageParser.Service)label;
11223            out.print(prefix); out.print(
11224                    Integer.toHexString(System.identityHashCode(service)));
11225                    out.print(' ');
11226                    service.printComponentShortName(out);
11227            if (count > 1) {
11228                out.print(" ("); out.print(count); out.print(" filters)");
11229            }
11230            out.println();
11231        }
11232
11233//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11234//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11235//            final List<ResolveInfo> retList = Lists.newArrayList();
11236//            while (i.hasNext()) {
11237//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11238//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11239//                    retList.add(resolveInfo);
11240//                }
11241//            }
11242//            return retList;
11243//        }
11244
11245        // Keys are String (activity class name), values are Activity.
11246        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11247                = new ArrayMap<ComponentName, PackageParser.Service>();
11248        private int mFlags;
11249    };
11250
11251    private final class ProviderIntentResolver
11252            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11253        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11254                boolean defaultOnly, int userId) {
11255            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11256            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11257        }
11258
11259        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11260                int userId) {
11261            if (!sUserManager.exists(userId))
11262                return null;
11263            mFlags = flags;
11264            return super.queryIntent(intent, resolvedType,
11265                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11266        }
11267
11268        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11269                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11270            if (!sUserManager.exists(userId))
11271                return null;
11272            if (packageProviders == null) {
11273                return null;
11274            }
11275            mFlags = flags;
11276            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11277            final int N = packageProviders.size();
11278            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11279                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11280
11281            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11282            for (int i = 0; i < N; ++i) {
11283                intentFilters = packageProviders.get(i).intents;
11284                if (intentFilters != null && intentFilters.size() > 0) {
11285                    PackageParser.ProviderIntentInfo[] array =
11286                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11287                    intentFilters.toArray(array);
11288                    listCut.add(array);
11289                }
11290            }
11291            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11292        }
11293
11294        public final void addProvider(PackageParser.Provider p) {
11295            if (mProviders.containsKey(p.getComponentName())) {
11296                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11297                return;
11298            }
11299
11300            mProviders.put(p.getComponentName(), p);
11301            if (DEBUG_SHOW_INFO) {
11302                Log.v(TAG, "  "
11303                        + (p.info.nonLocalizedLabel != null
11304                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11305                Log.v(TAG, "    Class=" + p.info.name);
11306            }
11307            final int NI = p.intents.size();
11308            int j;
11309            for (j = 0; j < NI; j++) {
11310                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11311                if (DEBUG_SHOW_INFO) {
11312                    Log.v(TAG, "    IntentFilter:");
11313                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11314                }
11315                if (!intent.debugCheck()) {
11316                    Log.w(TAG, "==> For Provider " + p.info.name);
11317                }
11318                addFilter(intent);
11319            }
11320        }
11321
11322        public final void removeProvider(PackageParser.Provider p) {
11323            mProviders.remove(p.getComponentName());
11324            if (DEBUG_SHOW_INFO) {
11325                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11326                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11327                Log.v(TAG, "    Class=" + p.info.name);
11328            }
11329            final int NI = p.intents.size();
11330            int j;
11331            for (j = 0; j < NI; j++) {
11332                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11333                if (DEBUG_SHOW_INFO) {
11334                    Log.v(TAG, "    IntentFilter:");
11335                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11336                }
11337                removeFilter(intent);
11338            }
11339        }
11340
11341        @Override
11342        protected boolean allowFilterResult(
11343                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11344            ProviderInfo filterPi = filter.provider.info;
11345            for (int i = dest.size() - 1; i >= 0; i--) {
11346                ProviderInfo destPi = dest.get(i).providerInfo;
11347                if (destPi.name == filterPi.name
11348                        && destPi.packageName == filterPi.packageName) {
11349                    return false;
11350                }
11351            }
11352            return true;
11353        }
11354
11355        @Override
11356        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11357            return new PackageParser.ProviderIntentInfo[size];
11358        }
11359
11360        @Override
11361        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11362            if (!sUserManager.exists(userId))
11363                return true;
11364            PackageParser.Package p = filter.provider.owner;
11365            if (p != null) {
11366                PackageSetting ps = (PackageSetting) p.mExtras;
11367                if (ps != null) {
11368                    // System apps are never considered stopped for purposes of
11369                    // filtering, because there may be no way for the user to
11370                    // actually re-launch them.
11371                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11372                            && ps.getStopped(userId);
11373                }
11374            }
11375            return false;
11376        }
11377
11378        @Override
11379        protected boolean isPackageForFilter(String packageName,
11380                PackageParser.ProviderIntentInfo info) {
11381            return packageName.equals(info.provider.owner.packageName);
11382        }
11383
11384        @Override
11385        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11386                int match, int userId) {
11387            if (!sUserManager.exists(userId))
11388                return null;
11389            final PackageParser.ProviderIntentInfo info = filter;
11390            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11391                return null;
11392            }
11393            final PackageParser.Provider provider = info.provider;
11394            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11395            if (ps == null) {
11396                return null;
11397            }
11398            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11399                    ps.readUserState(userId), userId);
11400            if (pi == null) {
11401                return null;
11402            }
11403            final ResolveInfo res = new ResolveInfo();
11404            res.providerInfo = pi;
11405            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11406                res.filter = filter;
11407            }
11408            res.priority = info.getPriority();
11409            res.preferredOrder = provider.owner.mPreferredOrder;
11410            res.match = match;
11411            res.isDefault = info.hasDefault;
11412            res.labelRes = info.labelRes;
11413            res.nonLocalizedLabel = info.nonLocalizedLabel;
11414            res.icon = info.icon;
11415            res.system = res.providerInfo.applicationInfo.isSystemApp();
11416            return res;
11417        }
11418
11419        @Override
11420        protected void sortResults(List<ResolveInfo> results) {
11421            Collections.sort(results, mResolvePrioritySorter);
11422        }
11423
11424        @Override
11425        protected void dumpFilter(PrintWriter out, String prefix,
11426                PackageParser.ProviderIntentInfo filter) {
11427            out.print(prefix);
11428            out.print(
11429                    Integer.toHexString(System.identityHashCode(filter.provider)));
11430            out.print(' ');
11431            filter.provider.printComponentShortName(out);
11432            out.print(" filter ");
11433            out.println(Integer.toHexString(System.identityHashCode(filter)));
11434        }
11435
11436        @Override
11437        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11438            return filter.provider;
11439        }
11440
11441        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11442            PackageParser.Provider provider = (PackageParser.Provider)label;
11443            out.print(prefix); out.print(
11444                    Integer.toHexString(System.identityHashCode(provider)));
11445                    out.print(' ');
11446                    provider.printComponentShortName(out);
11447            if (count > 1) {
11448                out.print(" ("); out.print(count); out.print(" filters)");
11449            }
11450            out.println();
11451        }
11452
11453        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11454                = new ArrayMap<ComponentName, PackageParser.Provider>();
11455        private int mFlags;
11456    }
11457
11458    private static final class EphemeralIntentResolver
11459            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveIntentInfo> {
11460        /**
11461         * The result that has the highest defined order. Ordering applies on a
11462         * per-package basis. Mapping is from package name to Pair of order and
11463         * EphemeralResolveInfo.
11464         * <p>
11465         * NOTE: This is implemented as a field variable for convenience and efficiency.
11466         * By having a field variable, we're able to track filter ordering as soon as
11467         * a non-zero order is defined. Otherwise, multiple loops across the result set
11468         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11469         * this needs to be contained entirely within {@link #filterResults()}.
11470         */
11471        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11472
11473        @Override
11474        protected EphemeralResolveIntentInfo[] newArray(int size) {
11475            return new EphemeralResolveIntentInfo[size];
11476        }
11477
11478        @Override
11479        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11480            return true;
11481        }
11482
11483        @Override
11484        protected EphemeralResolveIntentInfo newResult(EphemeralResolveIntentInfo info, int match,
11485                int userId) {
11486            if (!sUserManager.exists(userId)) {
11487                return null;
11488            }
11489            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11490            final Integer order = info.getOrder();
11491            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11492                    mOrderResult.get(packageName);
11493            // ordering is enabled and this item's order isn't high enough
11494            if (lastOrderResult != null && lastOrderResult.first >= order) {
11495                return null;
11496            }
11497            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11498            if (order > 0) {
11499                // non-zero order, enable ordering
11500                mOrderResult.put(packageName, new Pair<>(order, res));
11501            }
11502            return info;
11503        }
11504
11505        @Override
11506        protected void filterResults(List<EphemeralResolveIntentInfo> results) {
11507            // only do work if ordering is enabled [most of the time it won't be]
11508            if (mOrderResult.size() == 0) {
11509                return;
11510            }
11511            int resultSize = results.size();
11512            for (int i = 0; i < resultSize; i++) {
11513                final EphemeralResolveInfo info = results.get(i).getEphemeralResolveInfo();
11514                final String packageName = info.getPackageName();
11515                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11516                if (savedInfo == null) {
11517                    // package doesn't having ordering
11518                    continue;
11519                }
11520                if (savedInfo.second == info) {
11521                    // circled back to the highest ordered item; remove from order list
11522                    mOrderResult.remove(savedInfo);
11523                    if (mOrderResult.size() == 0) {
11524                        // no more ordered items
11525                        break;
11526                    }
11527                    continue;
11528                }
11529                // item has a worse order, remove it from the result list
11530                results.remove(i);
11531                resultSize--;
11532                i--;
11533            }
11534        }
11535    }
11536
11537    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11538            new Comparator<ResolveInfo>() {
11539        public int compare(ResolveInfo r1, ResolveInfo r2) {
11540            int v1 = r1.priority;
11541            int v2 = r2.priority;
11542            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11543            if (v1 != v2) {
11544                return (v1 > v2) ? -1 : 1;
11545            }
11546            v1 = r1.preferredOrder;
11547            v2 = r2.preferredOrder;
11548            if (v1 != v2) {
11549                return (v1 > v2) ? -1 : 1;
11550            }
11551            if (r1.isDefault != r2.isDefault) {
11552                return r1.isDefault ? -1 : 1;
11553            }
11554            v1 = r1.match;
11555            v2 = r2.match;
11556            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11557            if (v1 != v2) {
11558                return (v1 > v2) ? -1 : 1;
11559            }
11560            if (r1.system != r2.system) {
11561                return r1.system ? -1 : 1;
11562            }
11563            if (r1.activityInfo != null) {
11564                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11565            }
11566            if (r1.serviceInfo != null) {
11567                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11568            }
11569            if (r1.providerInfo != null) {
11570                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11571            }
11572            return 0;
11573        }
11574    };
11575
11576    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11577            new Comparator<ProviderInfo>() {
11578        public int compare(ProviderInfo p1, ProviderInfo p2) {
11579            final int v1 = p1.initOrder;
11580            final int v2 = p2.initOrder;
11581            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11582        }
11583    };
11584
11585    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11586            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11587            final int[] userIds) {
11588        mHandler.post(new Runnable() {
11589            @Override
11590            public void run() {
11591                try {
11592                    final IActivityManager am = ActivityManagerNative.getDefault();
11593                    if (am == null) return;
11594                    final int[] resolvedUserIds;
11595                    if (userIds == null) {
11596                        resolvedUserIds = am.getRunningUserIds();
11597                    } else {
11598                        resolvedUserIds = userIds;
11599                    }
11600                    for (int id : resolvedUserIds) {
11601                        final Intent intent = new Intent(action,
11602                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11603                        if (extras != null) {
11604                            intent.putExtras(extras);
11605                        }
11606                        if (targetPkg != null) {
11607                            intent.setPackage(targetPkg);
11608                        }
11609                        // Modify the UID when posting to other users
11610                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11611                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11612                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11613                            intent.putExtra(Intent.EXTRA_UID, uid);
11614                        }
11615                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11616                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11617                        if (DEBUG_BROADCASTS) {
11618                            RuntimeException here = new RuntimeException("here");
11619                            here.fillInStackTrace();
11620                            Slog.d(TAG, "Sending to user " + id + ": "
11621                                    + intent.toShortString(false, true, false, false)
11622                                    + " " + intent.getExtras(), here);
11623                        }
11624                        am.broadcastIntent(null, intent, null, finishedReceiver,
11625                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11626                                null, finishedReceiver != null, false, id);
11627                    }
11628                } catch (RemoteException ex) {
11629                }
11630            }
11631        });
11632    }
11633
11634    /**
11635     * Check if the external storage media is available. This is true if there
11636     * is a mounted external storage medium or if the external storage is
11637     * emulated.
11638     */
11639    private boolean isExternalMediaAvailable() {
11640        return mMediaMounted || Environment.isExternalStorageEmulated();
11641    }
11642
11643    @Override
11644    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11645        // writer
11646        synchronized (mPackages) {
11647            if (!isExternalMediaAvailable()) {
11648                // If the external storage is no longer mounted at this point,
11649                // the caller may not have been able to delete all of this
11650                // packages files and can not delete any more.  Bail.
11651                return null;
11652            }
11653            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11654            if (lastPackage != null) {
11655                pkgs.remove(lastPackage);
11656            }
11657            if (pkgs.size() > 0) {
11658                return pkgs.get(0);
11659            }
11660        }
11661        return null;
11662    }
11663
11664    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11665        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11666                userId, andCode ? 1 : 0, packageName);
11667        if (mSystemReady) {
11668            msg.sendToTarget();
11669        } else {
11670            if (mPostSystemReadyMessages == null) {
11671                mPostSystemReadyMessages = new ArrayList<>();
11672            }
11673            mPostSystemReadyMessages.add(msg);
11674        }
11675    }
11676
11677    void startCleaningPackages() {
11678        // reader
11679        if (!isExternalMediaAvailable()) {
11680            return;
11681        }
11682        synchronized (mPackages) {
11683            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11684                return;
11685            }
11686        }
11687        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11688        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11689        IActivityManager am = ActivityManagerNative.getDefault();
11690        if (am != null) {
11691            try {
11692                am.startService(null, intent, null, mContext.getOpPackageName(),
11693                        UserHandle.USER_SYSTEM);
11694            } catch (RemoteException e) {
11695            }
11696        }
11697    }
11698
11699    @Override
11700    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11701            int installFlags, String installerPackageName, int userId) {
11702        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11703
11704        final int callingUid = Binder.getCallingUid();
11705        enforceCrossUserPermission(callingUid, userId,
11706                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11707
11708        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11709            try {
11710                if (observer != null) {
11711                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11712                }
11713            } catch (RemoteException re) {
11714            }
11715            return;
11716        }
11717
11718        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11719            installFlags |= PackageManager.INSTALL_FROM_ADB;
11720
11721        } else {
11722            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11723            // about installerPackageName.
11724
11725            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11726            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11727        }
11728
11729        UserHandle user;
11730        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11731            user = UserHandle.ALL;
11732        } else {
11733            user = new UserHandle(userId);
11734        }
11735
11736        // Only system components can circumvent runtime permissions when installing.
11737        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11738                && mContext.checkCallingOrSelfPermission(Manifest.permission
11739                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11740            throw new SecurityException("You need the "
11741                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11742                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11743        }
11744
11745        final File originFile = new File(originPath);
11746        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11747
11748        final Message msg = mHandler.obtainMessage(INIT_COPY);
11749        final VerificationInfo verificationInfo = new VerificationInfo(
11750                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11751        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11752                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11753                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11754                null /*certificates*/);
11755        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11756        msg.obj = params;
11757
11758        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11759                System.identityHashCode(msg.obj));
11760        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11761                System.identityHashCode(msg.obj));
11762
11763        mHandler.sendMessage(msg);
11764    }
11765
11766    void installStage(String packageName, File stagedDir, String stagedCid,
11767            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11768            String installerPackageName, int installerUid, UserHandle user,
11769            Certificate[][] certificates) {
11770        if (DEBUG_EPHEMERAL) {
11771            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11772                Slog.d(TAG, "Ephemeral install of " + packageName);
11773            }
11774        }
11775        final VerificationInfo verificationInfo = new VerificationInfo(
11776                sessionParams.originatingUri, sessionParams.referrerUri,
11777                sessionParams.originatingUid, installerUid);
11778
11779        final OriginInfo origin;
11780        if (stagedDir != null) {
11781            origin = OriginInfo.fromStagedFile(stagedDir);
11782        } else {
11783            origin = OriginInfo.fromStagedContainer(stagedCid);
11784        }
11785
11786        final Message msg = mHandler.obtainMessage(INIT_COPY);
11787        final InstallParams params = new InstallParams(origin, null, observer,
11788                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11789                verificationInfo, user, sessionParams.abiOverride,
11790                sessionParams.grantedRuntimePermissions, certificates);
11791        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11792        msg.obj = params;
11793
11794        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11795                System.identityHashCode(msg.obj));
11796        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11797                System.identityHashCode(msg.obj));
11798
11799        mHandler.sendMessage(msg);
11800    }
11801
11802    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11803            int userId) {
11804        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11805        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
11806    }
11807
11808    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
11809            int appId, int... userIds) {
11810        if (ArrayUtils.isEmpty(userIds)) {
11811            return;
11812        }
11813        Bundle extras = new Bundle(1);
11814        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
11815        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
11816
11817        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11818                packageName, extras, 0, null, null, userIds);
11819        if (isSystem) {
11820            mHandler.post(() -> {
11821                        for (int userId : userIds) {
11822                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
11823                        }
11824                    }
11825            );
11826        }
11827    }
11828
11829    /**
11830     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
11831     * automatically without needing an explicit launch.
11832     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
11833     */
11834    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
11835        // If user is not running, the app didn't miss any broadcast
11836        if (!mUserManagerInternal.isUserRunning(userId)) {
11837            return;
11838        }
11839        final IActivityManager am = ActivityManagerNative.getDefault();
11840        try {
11841            // Deliver LOCKED_BOOT_COMPLETED first
11842            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
11843                    .setPackage(packageName);
11844            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
11845            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
11846                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11847
11848            // Deliver BOOT_COMPLETED only if user is unlocked
11849            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
11850                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
11851                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
11852                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11853            }
11854        } catch (RemoteException e) {
11855            throw e.rethrowFromSystemServer();
11856        }
11857    }
11858
11859    @Override
11860    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11861            int userId) {
11862        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11863        PackageSetting pkgSetting;
11864        final int uid = Binder.getCallingUid();
11865        enforceCrossUserPermission(uid, userId,
11866                true /* requireFullPermission */, true /* checkShell */,
11867                "setApplicationHiddenSetting for user " + userId);
11868
11869        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11870            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11871            return false;
11872        }
11873
11874        long callingId = Binder.clearCallingIdentity();
11875        try {
11876            boolean sendAdded = false;
11877            boolean sendRemoved = false;
11878            // writer
11879            synchronized (mPackages) {
11880                pkgSetting = mSettings.mPackages.get(packageName);
11881                if (pkgSetting == null) {
11882                    return false;
11883                }
11884                // Do not allow "android" is being disabled
11885                if ("android".equals(packageName)) {
11886                    Slog.w(TAG, "Cannot hide package: android");
11887                    return false;
11888                }
11889                // Only allow protected packages to hide themselves.
11890                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11891                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11892                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11893                    return false;
11894                }
11895
11896                if (pkgSetting.getHidden(userId) != hidden) {
11897                    pkgSetting.setHidden(hidden, userId);
11898                    mSettings.writePackageRestrictionsLPr(userId);
11899                    if (hidden) {
11900                        sendRemoved = true;
11901                    } else {
11902                        sendAdded = true;
11903                    }
11904                }
11905            }
11906            if (sendAdded) {
11907                sendPackageAddedForUser(packageName, pkgSetting, userId);
11908                return true;
11909            }
11910            if (sendRemoved) {
11911                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11912                        "hiding pkg");
11913                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11914                return true;
11915            }
11916        } finally {
11917            Binder.restoreCallingIdentity(callingId);
11918        }
11919        return false;
11920    }
11921
11922    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11923            int userId) {
11924        final PackageRemovedInfo info = new PackageRemovedInfo();
11925        info.removedPackage = packageName;
11926        info.removedUsers = new int[] {userId};
11927        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11928        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11929    }
11930
11931    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11932        if (pkgList.length > 0) {
11933            Bundle extras = new Bundle(1);
11934            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11935
11936            sendPackageBroadcast(
11937                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11938                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11939                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11940                    new int[] {userId});
11941        }
11942    }
11943
11944    /**
11945     * Returns true if application is not found or there was an error. Otherwise it returns
11946     * the hidden state of the package for the given user.
11947     */
11948    @Override
11949    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11950        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11951        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11952                true /* requireFullPermission */, false /* checkShell */,
11953                "getApplicationHidden for user " + userId);
11954        PackageSetting pkgSetting;
11955        long callingId = Binder.clearCallingIdentity();
11956        try {
11957            // writer
11958            synchronized (mPackages) {
11959                pkgSetting = mSettings.mPackages.get(packageName);
11960                if (pkgSetting == null) {
11961                    return true;
11962                }
11963                return pkgSetting.getHidden(userId);
11964            }
11965        } finally {
11966            Binder.restoreCallingIdentity(callingId);
11967        }
11968    }
11969
11970    /**
11971     * @hide
11972     */
11973    @Override
11974    public int installExistingPackageAsUser(String packageName, int userId) {
11975        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11976                null);
11977        PackageSetting pkgSetting;
11978        final int uid = Binder.getCallingUid();
11979        enforceCrossUserPermission(uid, userId,
11980                true /* requireFullPermission */, true /* checkShell */,
11981                "installExistingPackage for user " + userId);
11982        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11983            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11984        }
11985
11986        long callingId = Binder.clearCallingIdentity();
11987        try {
11988            boolean installed = false;
11989
11990            // writer
11991            synchronized (mPackages) {
11992                pkgSetting = mSettings.mPackages.get(packageName);
11993                if (pkgSetting == null) {
11994                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11995                }
11996                if (!pkgSetting.getInstalled(userId)) {
11997                    pkgSetting.setInstalled(true, userId);
11998                    pkgSetting.setHidden(false, userId);
11999                    mSettings.writePackageRestrictionsLPr(userId);
12000                    installed = true;
12001                }
12002            }
12003
12004            if (installed) {
12005                if (pkgSetting.pkg != null) {
12006                    synchronized (mInstallLock) {
12007                        // We don't need to freeze for a brand new install
12008                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12009                    }
12010                }
12011                sendPackageAddedForUser(packageName, pkgSetting, userId);
12012            }
12013        } finally {
12014            Binder.restoreCallingIdentity(callingId);
12015        }
12016
12017        return PackageManager.INSTALL_SUCCEEDED;
12018    }
12019
12020    boolean isUserRestricted(int userId, String restrictionKey) {
12021        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12022        if (restrictions.getBoolean(restrictionKey, false)) {
12023            Log.w(TAG, "User is restricted: " + restrictionKey);
12024            return true;
12025        }
12026        return false;
12027    }
12028
12029    @Override
12030    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12031            int userId) {
12032        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12033        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12034                true /* requireFullPermission */, true /* checkShell */,
12035                "setPackagesSuspended for user " + userId);
12036
12037        if (ArrayUtils.isEmpty(packageNames)) {
12038            return packageNames;
12039        }
12040
12041        // List of package names for whom the suspended state has changed.
12042        List<String> changedPackages = new ArrayList<>(packageNames.length);
12043        // List of package names for whom the suspended state is not set as requested in this
12044        // method.
12045        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12046        long callingId = Binder.clearCallingIdentity();
12047        try {
12048            for (int i = 0; i < packageNames.length; i++) {
12049                String packageName = packageNames[i];
12050                boolean changed = false;
12051                final int appId;
12052                synchronized (mPackages) {
12053                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12054                    if (pkgSetting == null) {
12055                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12056                                + "\". Skipping suspending/un-suspending.");
12057                        unactionedPackages.add(packageName);
12058                        continue;
12059                    }
12060                    appId = pkgSetting.appId;
12061                    if (pkgSetting.getSuspended(userId) != suspended) {
12062                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12063                            unactionedPackages.add(packageName);
12064                            continue;
12065                        }
12066                        pkgSetting.setSuspended(suspended, userId);
12067                        mSettings.writePackageRestrictionsLPr(userId);
12068                        changed = true;
12069                        changedPackages.add(packageName);
12070                    }
12071                }
12072
12073                if (changed && suspended) {
12074                    killApplication(packageName, UserHandle.getUid(userId, appId),
12075                            "suspending package");
12076                }
12077            }
12078        } finally {
12079            Binder.restoreCallingIdentity(callingId);
12080        }
12081
12082        if (!changedPackages.isEmpty()) {
12083            sendPackagesSuspendedForUser(changedPackages.toArray(
12084                    new String[changedPackages.size()]), userId, suspended);
12085        }
12086
12087        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12088    }
12089
12090    @Override
12091    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12092        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12093                true /* requireFullPermission */, false /* checkShell */,
12094                "isPackageSuspendedForUser for user " + userId);
12095        synchronized (mPackages) {
12096            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12097            if (pkgSetting == null) {
12098                throw new IllegalArgumentException("Unknown target package: " + packageName);
12099            }
12100            return pkgSetting.getSuspended(userId);
12101        }
12102    }
12103
12104    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12105        if (isPackageDeviceAdmin(packageName, userId)) {
12106            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12107                    + "\": has an active device admin");
12108            return false;
12109        }
12110
12111        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12112        if (packageName.equals(activeLauncherPackageName)) {
12113            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12114                    + "\": contains the active launcher");
12115            return false;
12116        }
12117
12118        if (packageName.equals(mRequiredInstallerPackage)) {
12119            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12120                    + "\": required for package installation");
12121            return false;
12122        }
12123
12124        if (packageName.equals(mRequiredUninstallerPackage)) {
12125            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12126                    + "\": required for package uninstallation");
12127            return false;
12128        }
12129
12130        if (packageName.equals(mRequiredVerifierPackage)) {
12131            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12132                    + "\": required for package verification");
12133            return false;
12134        }
12135
12136        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12137            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12138                    + "\": is the default dialer");
12139            return false;
12140        }
12141
12142        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12143            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12144                    + "\": protected package");
12145            return false;
12146        }
12147
12148        return true;
12149    }
12150
12151    private String getActiveLauncherPackageName(int userId) {
12152        Intent intent = new Intent(Intent.ACTION_MAIN);
12153        intent.addCategory(Intent.CATEGORY_HOME);
12154        ResolveInfo resolveInfo = resolveIntent(
12155                intent,
12156                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12157                PackageManager.MATCH_DEFAULT_ONLY,
12158                userId);
12159
12160        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12161    }
12162
12163    private String getDefaultDialerPackageName(int userId) {
12164        synchronized (mPackages) {
12165            return mSettings.getDefaultDialerPackageNameLPw(userId);
12166        }
12167    }
12168
12169    @Override
12170    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12171        mContext.enforceCallingOrSelfPermission(
12172                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12173                "Only package verification agents can verify applications");
12174
12175        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12176        final PackageVerificationResponse response = new PackageVerificationResponse(
12177                verificationCode, Binder.getCallingUid());
12178        msg.arg1 = id;
12179        msg.obj = response;
12180        mHandler.sendMessage(msg);
12181    }
12182
12183    @Override
12184    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12185            long millisecondsToDelay) {
12186        mContext.enforceCallingOrSelfPermission(
12187                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12188                "Only package verification agents can extend verification timeouts");
12189
12190        final PackageVerificationState state = mPendingVerification.get(id);
12191        final PackageVerificationResponse response = new PackageVerificationResponse(
12192                verificationCodeAtTimeout, Binder.getCallingUid());
12193
12194        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12195            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12196        }
12197        if (millisecondsToDelay < 0) {
12198            millisecondsToDelay = 0;
12199        }
12200        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12201                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12202            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12203        }
12204
12205        if ((state != null) && !state.timeoutExtended()) {
12206            state.extendTimeout();
12207
12208            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12209            msg.arg1 = id;
12210            msg.obj = response;
12211            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12212        }
12213    }
12214
12215    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12216            int verificationCode, UserHandle user) {
12217        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12218        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12219        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12220        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12221        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12222
12223        mContext.sendBroadcastAsUser(intent, user,
12224                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12225    }
12226
12227    private ComponentName matchComponentForVerifier(String packageName,
12228            List<ResolveInfo> receivers) {
12229        ActivityInfo targetReceiver = null;
12230
12231        final int NR = receivers.size();
12232        for (int i = 0; i < NR; i++) {
12233            final ResolveInfo info = receivers.get(i);
12234            if (info.activityInfo == null) {
12235                continue;
12236            }
12237
12238            if (packageName.equals(info.activityInfo.packageName)) {
12239                targetReceiver = info.activityInfo;
12240                break;
12241            }
12242        }
12243
12244        if (targetReceiver == null) {
12245            return null;
12246        }
12247
12248        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12249    }
12250
12251    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12252            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12253        if (pkgInfo.verifiers.length == 0) {
12254            return null;
12255        }
12256
12257        final int N = pkgInfo.verifiers.length;
12258        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12259        for (int i = 0; i < N; i++) {
12260            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12261
12262            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12263                    receivers);
12264            if (comp == null) {
12265                continue;
12266            }
12267
12268            final int verifierUid = getUidForVerifier(verifierInfo);
12269            if (verifierUid == -1) {
12270                continue;
12271            }
12272
12273            if (DEBUG_VERIFY) {
12274                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12275                        + " with the correct signature");
12276            }
12277            sufficientVerifiers.add(comp);
12278            verificationState.addSufficientVerifier(verifierUid);
12279        }
12280
12281        return sufficientVerifiers;
12282    }
12283
12284    private int getUidForVerifier(VerifierInfo verifierInfo) {
12285        synchronized (mPackages) {
12286            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12287            if (pkg == null) {
12288                return -1;
12289            } else if (pkg.mSignatures.length != 1) {
12290                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12291                        + " has more than one signature; ignoring");
12292                return -1;
12293            }
12294
12295            /*
12296             * If the public key of the package's signature does not match
12297             * our expected public key, then this is a different package and
12298             * we should skip.
12299             */
12300
12301            final byte[] expectedPublicKey;
12302            try {
12303                final Signature verifierSig = pkg.mSignatures[0];
12304                final PublicKey publicKey = verifierSig.getPublicKey();
12305                expectedPublicKey = publicKey.getEncoded();
12306            } catch (CertificateException e) {
12307                return -1;
12308            }
12309
12310            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12311
12312            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12313                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12314                        + " does not have the expected public key; ignoring");
12315                return -1;
12316            }
12317
12318            return pkg.applicationInfo.uid;
12319        }
12320    }
12321
12322    @Override
12323    public void finishPackageInstall(int token, boolean didLaunch) {
12324        enforceSystemOrRoot("Only the system is allowed to finish installs");
12325
12326        if (DEBUG_INSTALL) {
12327            Slog.v(TAG, "BM finishing package install for " + token);
12328        }
12329        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12330
12331        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12332        mHandler.sendMessage(msg);
12333    }
12334
12335    /**
12336     * Get the verification agent timeout.
12337     *
12338     * @return verification timeout in milliseconds
12339     */
12340    private long getVerificationTimeout() {
12341        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12342                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12343                DEFAULT_VERIFICATION_TIMEOUT);
12344    }
12345
12346    /**
12347     * Get the default verification agent response code.
12348     *
12349     * @return default verification response code
12350     */
12351    private int getDefaultVerificationResponse() {
12352        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12353                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12354                DEFAULT_VERIFICATION_RESPONSE);
12355    }
12356
12357    /**
12358     * Check whether or not package verification has been enabled.
12359     *
12360     * @return true if verification should be performed
12361     */
12362    private boolean isVerificationEnabled(int userId, int installFlags) {
12363        if (!DEFAULT_VERIFY_ENABLE) {
12364            return false;
12365        }
12366        // Ephemeral apps don't get the full verification treatment
12367        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12368            if (DEBUG_EPHEMERAL) {
12369                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12370            }
12371            return false;
12372        }
12373
12374        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12375
12376        // Check if installing from ADB
12377        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12378            // Do not run verification in a test harness environment
12379            if (ActivityManager.isRunningInTestHarness()) {
12380                return false;
12381            }
12382            if (ensureVerifyAppsEnabled) {
12383                return true;
12384            }
12385            // Check if the developer does not want package verification for ADB installs
12386            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12387                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12388                return false;
12389            }
12390        }
12391
12392        if (ensureVerifyAppsEnabled) {
12393            return true;
12394        }
12395
12396        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12397                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12398    }
12399
12400    @Override
12401    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12402            throws RemoteException {
12403        mContext.enforceCallingOrSelfPermission(
12404                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12405                "Only intentfilter verification agents can verify applications");
12406
12407        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12408        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12409                Binder.getCallingUid(), verificationCode, failedDomains);
12410        msg.arg1 = id;
12411        msg.obj = response;
12412        mHandler.sendMessage(msg);
12413    }
12414
12415    @Override
12416    public int getIntentVerificationStatus(String packageName, int userId) {
12417        synchronized (mPackages) {
12418            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12419        }
12420    }
12421
12422    @Override
12423    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12424        mContext.enforceCallingOrSelfPermission(
12425                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12426
12427        boolean result = false;
12428        synchronized (mPackages) {
12429            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12430        }
12431        if (result) {
12432            scheduleWritePackageRestrictionsLocked(userId);
12433        }
12434        return result;
12435    }
12436
12437    @Override
12438    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12439            String packageName) {
12440        synchronized (mPackages) {
12441            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12442        }
12443    }
12444
12445    @Override
12446    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12447        if (TextUtils.isEmpty(packageName)) {
12448            return ParceledListSlice.emptyList();
12449        }
12450        synchronized (mPackages) {
12451            PackageParser.Package pkg = mPackages.get(packageName);
12452            if (pkg == null || pkg.activities == null) {
12453                return ParceledListSlice.emptyList();
12454            }
12455            final int count = pkg.activities.size();
12456            ArrayList<IntentFilter> result = new ArrayList<>();
12457            for (int n=0; n<count; n++) {
12458                PackageParser.Activity activity = pkg.activities.get(n);
12459                if (activity.intents != null && activity.intents.size() > 0) {
12460                    result.addAll(activity.intents);
12461                }
12462            }
12463            return new ParceledListSlice<>(result);
12464        }
12465    }
12466
12467    @Override
12468    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12469        mContext.enforceCallingOrSelfPermission(
12470                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12471
12472        synchronized (mPackages) {
12473            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12474            if (packageName != null) {
12475                result |= updateIntentVerificationStatus(packageName,
12476                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12477                        userId);
12478                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12479                        packageName, userId);
12480            }
12481            return result;
12482        }
12483    }
12484
12485    @Override
12486    public String getDefaultBrowserPackageName(int userId) {
12487        synchronized (mPackages) {
12488            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12489        }
12490    }
12491
12492    /**
12493     * Get the "allow unknown sources" setting.
12494     *
12495     * @return the current "allow unknown sources" setting
12496     */
12497    private int getUnknownSourcesSettings() {
12498        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12499                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12500                -1);
12501    }
12502
12503    @Override
12504    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12505        final int uid = Binder.getCallingUid();
12506        // writer
12507        synchronized (mPackages) {
12508            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12509            if (targetPackageSetting == null) {
12510                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12511            }
12512
12513            PackageSetting installerPackageSetting;
12514            if (installerPackageName != null) {
12515                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12516                if (installerPackageSetting == null) {
12517                    throw new IllegalArgumentException("Unknown installer package: "
12518                            + installerPackageName);
12519                }
12520            } else {
12521                installerPackageSetting = null;
12522            }
12523
12524            Signature[] callerSignature;
12525            Object obj = mSettings.getUserIdLPr(uid);
12526            if (obj != null) {
12527                if (obj instanceof SharedUserSetting) {
12528                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12529                } else if (obj instanceof PackageSetting) {
12530                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12531                } else {
12532                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12533                }
12534            } else {
12535                throw new SecurityException("Unknown calling UID: " + uid);
12536            }
12537
12538            // Verify: can't set installerPackageName to a package that is
12539            // not signed with the same cert as the caller.
12540            if (installerPackageSetting != null) {
12541                if (compareSignatures(callerSignature,
12542                        installerPackageSetting.signatures.mSignatures)
12543                        != PackageManager.SIGNATURE_MATCH) {
12544                    throw new SecurityException(
12545                            "Caller does not have same cert as new installer package "
12546                            + installerPackageName);
12547                }
12548            }
12549
12550            // Verify: if target already has an installer package, it must
12551            // be signed with the same cert as the caller.
12552            if (targetPackageSetting.installerPackageName != null) {
12553                PackageSetting setting = mSettings.mPackages.get(
12554                        targetPackageSetting.installerPackageName);
12555                // If the currently set package isn't valid, then it's always
12556                // okay to change it.
12557                if (setting != null) {
12558                    if (compareSignatures(callerSignature,
12559                            setting.signatures.mSignatures)
12560                            != PackageManager.SIGNATURE_MATCH) {
12561                        throw new SecurityException(
12562                                "Caller does not have same cert as old installer package "
12563                                + targetPackageSetting.installerPackageName);
12564                    }
12565                }
12566            }
12567
12568            // Okay!
12569            targetPackageSetting.installerPackageName = installerPackageName;
12570            if (installerPackageName != null) {
12571                mSettings.mInstallerPackages.add(installerPackageName);
12572            }
12573            scheduleWriteSettingsLocked();
12574        }
12575    }
12576
12577    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12578        // Queue up an async operation since the package installation may take a little while.
12579        mHandler.post(new Runnable() {
12580            public void run() {
12581                mHandler.removeCallbacks(this);
12582                 // Result object to be returned
12583                PackageInstalledInfo res = new PackageInstalledInfo();
12584                res.setReturnCode(currentStatus);
12585                res.uid = -1;
12586                res.pkg = null;
12587                res.removedInfo = null;
12588                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12589                    args.doPreInstall(res.returnCode);
12590                    synchronized (mInstallLock) {
12591                        installPackageTracedLI(args, res);
12592                    }
12593                    args.doPostInstall(res.returnCode, res.uid);
12594                }
12595
12596                // A restore should be performed at this point if (a) the install
12597                // succeeded, (b) the operation is not an update, and (c) the new
12598                // package has not opted out of backup participation.
12599                final boolean update = res.removedInfo != null
12600                        && res.removedInfo.removedPackage != null;
12601                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12602                boolean doRestore = !update
12603                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12604
12605                // Set up the post-install work request bookkeeping.  This will be used
12606                // and cleaned up by the post-install event handling regardless of whether
12607                // there's a restore pass performed.  Token values are >= 1.
12608                int token;
12609                if (mNextInstallToken < 0) mNextInstallToken = 1;
12610                token = mNextInstallToken++;
12611
12612                PostInstallData data = new PostInstallData(args, res);
12613                mRunningInstalls.put(token, data);
12614                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12615
12616                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12617                    // Pass responsibility to the Backup Manager.  It will perform a
12618                    // restore if appropriate, then pass responsibility back to the
12619                    // Package Manager to run the post-install observer callbacks
12620                    // and broadcasts.
12621                    IBackupManager bm = IBackupManager.Stub.asInterface(
12622                            ServiceManager.getService(Context.BACKUP_SERVICE));
12623                    if (bm != null) {
12624                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12625                                + " to BM for possible restore");
12626                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12627                        try {
12628                            // TODO: http://b/22388012
12629                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12630                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12631                            } else {
12632                                doRestore = false;
12633                            }
12634                        } catch (RemoteException e) {
12635                            // can't happen; the backup manager is local
12636                        } catch (Exception e) {
12637                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12638                            doRestore = false;
12639                        }
12640                    } else {
12641                        Slog.e(TAG, "Backup Manager not found!");
12642                        doRestore = false;
12643                    }
12644                }
12645
12646                if (!doRestore) {
12647                    // No restore possible, or the Backup Manager was mysteriously not
12648                    // available -- just fire the post-install work request directly.
12649                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12650
12651                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12652
12653                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12654                    mHandler.sendMessage(msg);
12655                }
12656            }
12657        });
12658    }
12659
12660    /**
12661     * Callback from PackageSettings whenever an app is first transitioned out of the
12662     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12663     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12664     * here whether the app is the target of an ongoing install, and only send the
12665     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12666     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12667     * handling.
12668     */
12669    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12670        // Serialize this with the rest of the install-process message chain.  In the
12671        // restore-at-install case, this Runnable will necessarily run before the
12672        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12673        // are coherent.  In the non-restore case, the app has already completed install
12674        // and been launched through some other means, so it is not in a problematic
12675        // state for observers to see the FIRST_LAUNCH signal.
12676        mHandler.post(new Runnable() {
12677            @Override
12678            public void run() {
12679                for (int i = 0; i < mRunningInstalls.size(); i++) {
12680                    final PostInstallData data = mRunningInstalls.valueAt(i);
12681                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12682                        continue;
12683                    }
12684                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12685                        // right package; but is it for the right user?
12686                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12687                            if (userId == data.res.newUsers[uIndex]) {
12688                                if (DEBUG_BACKUP) {
12689                                    Slog.i(TAG, "Package " + pkgName
12690                                            + " being restored so deferring FIRST_LAUNCH");
12691                                }
12692                                return;
12693                            }
12694                        }
12695                    }
12696                }
12697                // didn't find it, so not being restored
12698                if (DEBUG_BACKUP) {
12699                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12700                }
12701                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12702            }
12703        });
12704    }
12705
12706    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12707        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12708                installerPkg, null, userIds);
12709    }
12710
12711    private abstract class HandlerParams {
12712        private static final int MAX_RETRIES = 4;
12713
12714        /**
12715         * Number of times startCopy() has been attempted and had a non-fatal
12716         * error.
12717         */
12718        private int mRetries = 0;
12719
12720        /** User handle for the user requesting the information or installation. */
12721        private final UserHandle mUser;
12722        String traceMethod;
12723        int traceCookie;
12724
12725        HandlerParams(UserHandle user) {
12726            mUser = user;
12727        }
12728
12729        UserHandle getUser() {
12730            return mUser;
12731        }
12732
12733        HandlerParams setTraceMethod(String traceMethod) {
12734            this.traceMethod = traceMethod;
12735            return this;
12736        }
12737
12738        HandlerParams setTraceCookie(int traceCookie) {
12739            this.traceCookie = traceCookie;
12740            return this;
12741        }
12742
12743        final boolean startCopy() {
12744            boolean res;
12745            try {
12746                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12747
12748                if (++mRetries > MAX_RETRIES) {
12749                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12750                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12751                    handleServiceError();
12752                    return false;
12753                } else {
12754                    handleStartCopy();
12755                    res = true;
12756                }
12757            } catch (RemoteException e) {
12758                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12759                mHandler.sendEmptyMessage(MCS_RECONNECT);
12760                res = false;
12761            }
12762            handleReturnCode();
12763            return res;
12764        }
12765
12766        final void serviceError() {
12767            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12768            handleServiceError();
12769            handleReturnCode();
12770        }
12771
12772        abstract void handleStartCopy() throws RemoteException;
12773        abstract void handleServiceError();
12774        abstract void handleReturnCode();
12775    }
12776
12777    class MeasureParams extends HandlerParams {
12778        private final PackageStats mStats;
12779        private boolean mSuccess;
12780
12781        private final IPackageStatsObserver mObserver;
12782
12783        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12784            super(new UserHandle(stats.userHandle));
12785            mObserver = observer;
12786            mStats = stats;
12787        }
12788
12789        @Override
12790        public String toString() {
12791            return "MeasureParams{"
12792                + Integer.toHexString(System.identityHashCode(this))
12793                + " " + mStats.packageName + "}";
12794        }
12795
12796        @Override
12797        void handleStartCopy() throws RemoteException {
12798            synchronized (mInstallLock) {
12799                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12800            }
12801
12802            if (mSuccess) {
12803                boolean mounted = false;
12804                try {
12805                    final String status = Environment.getExternalStorageState();
12806                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12807                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12808                } catch (Exception e) {
12809                }
12810
12811                if (mounted) {
12812                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12813
12814                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12815                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12816
12817                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12818                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12819
12820                    // Always subtract cache size, since it's a subdirectory
12821                    mStats.externalDataSize -= mStats.externalCacheSize;
12822
12823                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12824                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12825
12826                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12827                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12828                }
12829            }
12830        }
12831
12832        @Override
12833        void handleReturnCode() {
12834            if (mObserver != null) {
12835                try {
12836                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12837                } catch (RemoteException e) {
12838                    Slog.i(TAG, "Observer no longer exists.");
12839                }
12840            }
12841        }
12842
12843        @Override
12844        void handleServiceError() {
12845            Slog.e(TAG, "Could not measure application " + mStats.packageName
12846                            + " external storage");
12847        }
12848    }
12849
12850    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12851            throws RemoteException {
12852        long result = 0;
12853        for (File path : paths) {
12854            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12855        }
12856        return result;
12857    }
12858
12859    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12860        for (File path : paths) {
12861            try {
12862                mcs.clearDirectory(path.getAbsolutePath());
12863            } catch (RemoteException e) {
12864            }
12865        }
12866    }
12867
12868    static class OriginInfo {
12869        /**
12870         * Location where install is coming from, before it has been
12871         * copied/renamed into place. This could be a single monolithic APK
12872         * file, or a cluster directory. This location may be untrusted.
12873         */
12874        final File file;
12875        final String cid;
12876
12877        /**
12878         * Flag indicating that {@link #file} or {@link #cid} has already been
12879         * staged, meaning downstream users don't need to defensively copy the
12880         * contents.
12881         */
12882        final boolean staged;
12883
12884        /**
12885         * Flag indicating that {@link #file} or {@link #cid} is an already
12886         * installed app that is being moved.
12887         */
12888        final boolean existing;
12889
12890        final String resolvedPath;
12891        final File resolvedFile;
12892
12893        static OriginInfo fromNothing() {
12894            return new OriginInfo(null, null, false, false);
12895        }
12896
12897        static OriginInfo fromUntrustedFile(File file) {
12898            return new OriginInfo(file, null, false, false);
12899        }
12900
12901        static OriginInfo fromExistingFile(File file) {
12902            return new OriginInfo(file, null, false, true);
12903        }
12904
12905        static OriginInfo fromStagedFile(File file) {
12906            return new OriginInfo(file, null, true, false);
12907        }
12908
12909        static OriginInfo fromStagedContainer(String cid) {
12910            return new OriginInfo(null, cid, true, false);
12911        }
12912
12913        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12914            this.file = file;
12915            this.cid = cid;
12916            this.staged = staged;
12917            this.existing = existing;
12918
12919            if (cid != null) {
12920                resolvedPath = PackageHelper.getSdDir(cid);
12921                resolvedFile = new File(resolvedPath);
12922            } else if (file != null) {
12923                resolvedPath = file.getAbsolutePath();
12924                resolvedFile = file;
12925            } else {
12926                resolvedPath = null;
12927                resolvedFile = null;
12928            }
12929        }
12930    }
12931
12932    static class MoveInfo {
12933        final int moveId;
12934        final String fromUuid;
12935        final String toUuid;
12936        final String packageName;
12937        final String dataAppName;
12938        final int appId;
12939        final String seinfo;
12940        final int targetSdkVersion;
12941
12942        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12943                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12944            this.moveId = moveId;
12945            this.fromUuid = fromUuid;
12946            this.toUuid = toUuid;
12947            this.packageName = packageName;
12948            this.dataAppName = dataAppName;
12949            this.appId = appId;
12950            this.seinfo = seinfo;
12951            this.targetSdkVersion = targetSdkVersion;
12952        }
12953    }
12954
12955    static class VerificationInfo {
12956        /** A constant used to indicate that a uid value is not present. */
12957        public static final int NO_UID = -1;
12958
12959        /** URI referencing where the package was downloaded from. */
12960        final Uri originatingUri;
12961
12962        /** HTTP referrer URI associated with the originatingURI. */
12963        final Uri referrer;
12964
12965        /** UID of the application that the install request originated from. */
12966        final int originatingUid;
12967
12968        /** UID of application requesting the install */
12969        final int installerUid;
12970
12971        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12972            this.originatingUri = originatingUri;
12973            this.referrer = referrer;
12974            this.originatingUid = originatingUid;
12975            this.installerUid = installerUid;
12976        }
12977    }
12978
12979    class InstallParams extends HandlerParams {
12980        final OriginInfo origin;
12981        final MoveInfo move;
12982        final IPackageInstallObserver2 observer;
12983        int installFlags;
12984        final String installerPackageName;
12985        final String volumeUuid;
12986        private InstallArgs mArgs;
12987        private int mRet;
12988        final String packageAbiOverride;
12989        final String[] grantedRuntimePermissions;
12990        final VerificationInfo verificationInfo;
12991        final Certificate[][] certificates;
12992
12993        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12994                int installFlags, String installerPackageName, String volumeUuid,
12995                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12996                String[] grantedPermissions, Certificate[][] certificates) {
12997            super(user);
12998            this.origin = origin;
12999            this.move = move;
13000            this.observer = observer;
13001            this.installFlags = installFlags;
13002            this.installerPackageName = installerPackageName;
13003            this.volumeUuid = volumeUuid;
13004            this.verificationInfo = verificationInfo;
13005            this.packageAbiOverride = packageAbiOverride;
13006            this.grantedRuntimePermissions = grantedPermissions;
13007            this.certificates = certificates;
13008        }
13009
13010        @Override
13011        public String toString() {
13012            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13013                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13014        }
13015
13016        private int installLocationPolicy(PackageInfoLite pkgLite) {
13017            String packageName = pkgLite.packageName;
13018            int installLocation = pkgLite.installLocation;
13019            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13020            // reader
13021            synchronized (mPackages) {
13022                // Currently installed package which the new package is attempting to replace or
13023                // null if no such package is installed.
13024                PackageParser.Package installedPkg = mPackages.get(packageName);
13025                // Package which currently owns the data which the new package will own if installed.
13026                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13027                // will be null whereas dataOwnerPkg will contain information about the package
13028                // which was uninstalled while keeping its data.
13029                PackageParser.Package dataOwnerPkg = installedPkg;
13030                if (dataOwnerPkg  == null) {
13031                    PackageSetting ps = mSettings.mPackages.get(packageName);
13032                    if (ps != null) {
13033                        dataOwnerPkg = ps.pkg;
13034                    }
13035                }
13036
13037                if (dataOwnerPkg != null) {
13038                    // If installed, the package will get access to data left on the device by its
13039                    // predecessor. As a security measure, this is permited only if this is not a
13040                    // version downgrade or if the predecessor package is marked as debuggable and
13041                    // a downgrade is explicitly requested.
13042                    //
13043                    // On debuggable platform builds, downgrades are permitted even for
13044                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13045                    // not offer security guarantees and thus it's OK to disable some security
13046                    // mechanisms to make debugging/testing easier on those builds. However, even on
13047                    // debuggable builds downgrades of packages are permitted only if requested via
13048                    // installFlags. This is because we aim to keep the behavior of debuggable
13049                    // platform builds as close as possible to the behavior of non-debuggable
13050                    // platform builds.
13051                    final boolean downgradeRequested =
13052                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13053                    final boolean packageDebuggable =
13054                                (dataOwnerPkg.applicationInfo.flags
13055                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13056                    final boolean downgradePermitted =
13057                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13058                    if (!downgradePermitted) {
13059                        try {
13060                            checkDowngrade(dataOwnerPkg, pkgLite);
13061                        } catch (PackageManagerException e) {
13062                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13063                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13064                        }
13065                    }
13066                }
13067
13068                if (installedPkg != null) {
13069                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13070                        // Check for updated system application.
13071                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13072                            if (onSd) {
13073                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13074                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13075                            }
13076                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13077                        } else {
13078                            if (onSd) {
13079                                // Install flag overrides everything.
13080                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13081                            }
13082                            // If current upgrade specifies particular preference
13083                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13084                                // Application explicitly specified internal.
13085                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13086                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13087                                // App explictly prefers external. Let policy decide
13088                            } else {
13089                                // Prefer previous location
13090                                if (isExternal(installedPkg)) {
13091                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13092                                }
13093                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13094                            }
13095                        }
13096                    } else {
13097                        // Invalid install. Return error code
13098                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13099                    }
13100                }
13101            }
13102            // All the special cases have been taken care of.
13103            // Return result based on recommended install location.
13104            if (onSd) {
13105                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13106            }
13107            return pkgLite.recommendedInstallLocation;
13108        }
13109
13110        /*
13111         * Invoke remote method to get package information and install
13112         * location values. Override install location based on default
13113         * policy if needed and then create install arguments based
13114         * on the install location.
13115         */
13116        public void handleStartCopy() throws RemoteException {
13117            int ret = PackageManager.INSTALL_SUCCEEDED;
13118
13119            // If we're already staged, we've firmly committed to an install location
13120            if (origin.staged) {
13121                if (origin.file != null) {
13122                    installFlags |= PackageManager.INSTALL_INTERNAL;
13123                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13124                } else if (origin.cid != null) {
13125                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13126                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13127                } else {
13128                    throw new IllegalStateException("Invalid stage location");
13129                }
13130            }
13131
13132            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13133            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13134            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13135            PackageInfoLite pkgLite = null;
13136
13137            if (onInt && onSd) {
13138                // Check if both bits are set.
13139                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13140                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13141            } else if (onSd && ephemeral) {
13142                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13143                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13144            } else {
13145                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13146                        packageAbiOverride);
13147
13148                if (DEBUG_EPHEMERAL && ephemeral) {
13149                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13150                }
13151
13152                /*
13153                 * If we have too little free space, try to free cache
13154                 * before giving up.
13155                 */
13156                if (!origin.staged && pkgLite.recommendedInstallLocation
13157                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13158                    // TODO: focus freeing disk space on the target device
13159                    final StorageManager storage = StorageManager.from(mContext);
13160                    final long lowThreshold = storage.getStorageLowBytes(
13161                            Environment.getDataDirectory());
13162
13163                    final long sizeBytes = mContainerService.calculateInstalledSize(
13164                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13165
13166                    try {
13167                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13168                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13169                                installFlags, packageAbiOverride);
13170                    } catch (InstallerException e) {
13171                        Slog.w(TAG, "Failed to free cache", e);
13172                    }
13173
13174                    /*
13175                     * The cache free must have deleted the file we
13176                     * downloaded to install.
13177                     *
13178                     * TODO: fix the "freeCache" call to not delete
13179                     *       the file we care about.
13180                     */
13181                    if (pkgLite.recommendedInstallLocation
13182                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13183                        pkgLite.recommendedInstallLocation
13184                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13185                    }
13186                }
13187            }
13188
13189            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13190                int loc = pkgLite.recommendedInstallLocation;
13191                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13192                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13193                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13194                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13195                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13196                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13197                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13198                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13199                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13200                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13201                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13202                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13203                } else {
13204                    // Override with defaults if needed.
13205                    loc = installLocationPolicy(pkgLite);
13206                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13207                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13208                    } else if (!onSd && !onInt) {
13209                        // Override install location with flags
13210                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13211                            // Set the flag to install on external media.
13212                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13213                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13214                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13215                            if (DEBUG_EPHEMERAL) {
13216                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13217                            }
13218                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13219                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13220                                    |PackageManager.INSTALL_INTERNAL);
13221                        } else {
13222                            // Make sure the flag for installing on external
13223                            // media is unset
13224                            installFlags |= PackageManager.INSTALL_INTERNAL;
13225                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13226                        }
13227                    }
13228                }
13229            }
13230
13231            final InstallArgs args = createInstallArgs(this);
13232            mArgs = args;
13233
13234            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13235                // TODO: http://b/22976637
13236                // Apps installed for "all" users use the device owner to verify the app
13237                UserHandle verifierUser = getUser();
13238                if (verifierUser == UserHandle.ALL) {
13239                    verifierUser = UserHandle.SYSTEM;
13240                }
13241
13242                /*
13243                 * Determine if we have any installed package verifiers. If we
13244                 * do, then we'll defer to them to verify the packages.
13245                 */
13246                final int requiredUid = mRequiredVerifierPackage == null ? -1
13247                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13248                                verifierUser.getIdentifier());
13249                if (!origin.existing && requiredUid != -1
13250                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13251                    final Intent verification = new Intent(
13252                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13253                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13254                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13255                            PACKAGE_MIME_TYPE);
13256                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13257
13258                    // Query all live verifiers based on current user state
13259                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13260                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13261
13262                    if (DEBUG_VERIFY) {
13263                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13264                                + verification.toString() + " with " + pkgLite.verifiers.length
13265                                + " optional verifiers");
13266                    }
13267
13268                    final int verificationId = mPendingVerificationToken++;
13269
13270                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13271
13272                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13273                            installerPackageName);
13274
13275                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13276                            installFlags);
13277
13278                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13279                            pkgLite.packageName);
13280
13281                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13282                            pkgLite.versionCode);
13283
13284                    if (verificationInfo != null) {
13285                        if (verificationInfo.originatingUri != null) {
13286                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13287                                    verificationInfo.originatingUri);
13288                        }
13289                        if (verificationInfo.referrer != null) {
13290                            verification.putExtra(Intent.EXTRA_REFERRER,
13291                                    verificationInfo.referrer);
13292                        }
13293                        if (verificationInfo.originatingUid >= 0) {
13294                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13295                                    verificationInfo.originatingUid);
13296                        }
13297                        if (verificationInfo.installerUid >= 0) {
13298                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13299                                    verificationInfo.installerUid);
13300                        }
13301                    }
13302
13303                    final PackageVerificationState verificationState = new PackageVerificationState(
13304                            requiredUid, args);
13305
13306                    mPendingVerification.append(verificationId, verificationState);
13307
13308                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13309                            receivers, verificationState);
13310
13311                    /*
13312                     * If any sufficient verifiers were listed in the package
13313                     * manifest, attempt to ask them.
13314                     */
13315                    if (sufficientVerifiers != null) {
13316                        final int N = sufficientVerifiers.size();
13317                        if (N == 0) {
13318                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13319                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13320                        } else {
13321                            for (int i = 0; i < N; i++) {
13322                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13323
13324                                final Intent sufficientIntent = new Intent(verification);
13325                                sufficientIntent.setComponent(verifierComponent);
13326                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13327                            }
13328                        }
13329                    }
13330
13331                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13332                            mRequiredVerifierPackage, receivers);
13333                    if (ret == PackageManager.INSTALL_SUCCEEDED
13334                            && mRequiredVerifierPackage != null) {
13335                        Trace.asyncTraceBegin(
13336                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13337                        /*
13338                         * Send the intent to the required verification agent,
13339                         * but only start the verification timeout after the
13340                         * target BroadcastReceivers have run.
13341                         */
13342                        verification.setComponent(requiredVerifierComponent);
13343                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13344                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13345                                new BroadcastReceiver() {
13346                                    @Override
13347                                    public void onReceive(Context context, Intent intent) {
13348                                        final Message msg = mHandler
13349                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13350                                        msg.arg1 = verificationId;
13351                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13352                                    }
13353                                }, null, 0, null, null);
13354
13355                        /*
13356                         * We don't want the copy to proceed until verification
13357                         * succeeds, so null out this field.
13358                         */
13359                        mArgs = null;
13360                    }
13361                } else {
13362                    /*
13363                     * No package verification is enabled, so immediately start
13364                     * the remote call to initiate copy using temporary file.
13365                     */
13366                    ret = args.copyApk(mContainerService, true);
13367                }
13368            }
13369
13370            mRet = ret;
13371        }
13372
13373        @Override
13374        void handleReturnCode() {
13375            // If mArgs is null, then MCS couldn't be reached. When it
13376            // reconnects, it will try again to install. At that point, this
13377            // will succeed.
13378            if (mArgs != null) {
13379                processPendingInstall(mArgs, mRet);
13380            }
13381        }
13382
13383        @Override
13384        void handleServiceError() {
13385            mArgs = createInstallArgs(this);
13386            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13387        }
13388
13389        public boolean isForwardLocked() {
13390            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13391        }
13392    }
13393
13394    /**
13395     * Used during creation of InstallArgs
13396     *
13397     * @param installFlags package installation flags
13398     * @return true if should be installed on external storage
13399     */
13400    private static boolean installOnExternalAsec(int installFlags) {
13401        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13402            return false;
13403        }
13404        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13405            return true;
13406        }
13407        return false;
13408    }
13409
13410    /**
13411     * Used during creation of InstallArgs
13412     *
13413     * @param installFlags package installation flags
13414     * @return true if should be installed as forward locked
13415     */
13416    private static boolean installForwardLocked(int installFlags) {
13417        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13418    }
13419
13420    private InstallArgs createInstallArgs(InstallParams params) {
13421        if (params.move != null) {
13422            return new MoveInstallArgs(params);
13423        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13424            return new AsecInstallArgs(params);
13425        } else {
13426            return new FileInstallArgs(params);
13427        }
13428    }
13429
13430    /**
13431     * Create args that describe an existing installed package. Typically used
13432     * when cleaning up old installs, or used as a move source.
13433     */
13434    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13435            String resourcePath, String[] instructionSets) {
13436        final boolean isInAsec;
13437        if (installOnExternalAsec(installFlags)) {
13438            /* Apps on SD card are always in ASEC containers. */
13439            isInAsec = true;
13440        } else if (installForwardLocked(installFlags)
13441                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13442            /*
13443             * Forward-locked apps are only in ASEC containers if they're the
13444             * new style
13445             */
13446            isInAsec = true;
13447        } else {
13448            isInAsec = false;
13449        }
13450
13451        if (isInAsec) {
13452            return new AsecInstallArgs(codePath, instructionSets,
13453                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13454        } else {
13455            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13456        }
13457    }
13458
13459    static abstract class InstallArgs {
13460        /** @see InstallParams#origin */
13461        final OriginInfo origin;
13462        /** @see InstallParams#move */
13463        final MoveInfo move;
13464
13465        final IPackageInstallObserver2 observer;
13466        // Always refers to PackageManager flags only
13467        final int installFlags;
13468        final String installerPackageName;
13469        final String volumeUuid;
13470        final UserHandle user;
13471        final String abiOverride;
13472        final String[] installGrantPermissions;
13473        /** If non-null, drop an async trace when the install completes */
13474        final String traceMethod;
13475        final int traceCookie;
13476        final Certificate[][] certificates;
13477
13478        // The list of instruction sets supported by this app. This is currently
13479        // only used during the rmdex() phase to clean up resources. We can get rid of this
13480        // if we move dex files under the common app path.
13481        /* nullable */ String[] instructionSets;
13482
13483        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13484                int installFlags, String installerPackageName, String volumeUuid,
13485                UserHandle user, String[] instructionSets,
13486                String abiOverride, String[] installGrantPermissions,
13487                String traceMethod, int traceCookie, Certificate[][] certificates) {
13488            this.origin = origin;
13489            this.move = move;
13490            this.installFlags = installFlags;
13491            this.observer = observer;
13492            this.installerPackageName = installerPackageName;
13493            this.volumeUuid = volumeUuid;
13494            this.user = user;
13495            this.instructionSets = instructionSets;
13496            this.abiOverride = abiOverride;
13497            this.installGrantPermissions = installGrantPermissions;
13498            this.traceMethod = traceMethod;
13499            this.traceCookie = traceCookie;
13500            this.certificates = certificates;
13501        }
13502
13503        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13504        abstract int doPreInstall(int status);
13505
13506        /**
13507         * Rename package into final resting place. All paths on the given
13508         * scanned package should be updated to reflect the rename.
13509         */
13510        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13511        abstract int doPostInstall(int status, int uid);
13512
13513        /** @see PackageSettingBase#codePathString */
13514        abstract String getCodePath();
13515        /** @see PackageSettingBase#resourcePathString */
13516        abstract String getResourcePath();
13517
13518        // Need installer lock especially for dex file removal.
13519        abstract void cleanUpResourcesLI();
13520        abstract boolean doPostDeleteLI(boolean delete);
13521
13522        /**
13523         * Called before the source arguments are copied. This is used mostly
13524         * for MoveParams when it needs to read the source file to put it in the
13525         * destination.
13526         */
13527        int doPreCopy() {
13528            return PackageManager.INSTALL_SUCCEEDED;
13529        }
13530
13531        /**
13532         * Called after the source arguments are copied. This is used mostly for
13533         * MoveParams when it needs to read the source file to put it in the
13534         * destination.
13535         */
13536        int doPostCopy(int uid) {
13537            return PackageManager.INSTALL_SUCCEEDED;
13538        }
13539
13540        protected boolean isFwdLocked() {
13541            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13542        }
13543
13544        protected boolean isExternalAsec() {
13545            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13546        }
13547
13548        protected boolean isEphemeral() {
13549            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13550        }
13551
13552        UserHandle getUser() {
13553            return user;
13554        }
13555    }
13556
13557    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13558        if (!allCodePaths.isEmpty()) {
13559            if (instructionSets == null) {
13560                throw new IllegalStateException("instructionSet == null");
13561            }
13562            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13563            for (String codePath : allCodePaths) {
13564                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13565                    try {
13566                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13567                    } catch (InstallerException ignored) {
13568                    }
13569                }
13570            }
13571        }
13572    }
13573
13574    /**
13575     * Logic to handle installation of non-ASEC applications, including copying
13576     * and renaming logic.
13577     */
13578    class FileInstallArgs extends InstallArgs {
13579        private File codeFile;
13580        private File resourceFile;
13581
13582        // Example topology:
13583        // /data/app/com.example/base.apk
13584        // /data/app/com.example/split_foo.apk
13585        // /data/app/com.example/lib/arm/libfoo.so
13586        // /data/app/com.example/lib/arm64/libfoo.so
13587        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13588
13589        /** New install */
13590        FileInstallArgs(InstallParams params) {
13591            super(params.origin, params.move, params.observer, params.installFlags,
13592                    params.installerPackageName, params.volumeUuid,
13593                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13594                    params.grantedRuntimePermissions,
13595                    params.traceMethod, params.traceCookie, params.certificates);
13596            if (isFwdLocked()) {
13597                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13598            }
13599        }
13600
13601        /** Existing install */
13602        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13603            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13604                    null, null, null, 0, null /*certificates*/);
13605            this.codeFile = (codePath != null) ? new File(codePath) : null;
13606            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13607        }
13608
13609        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13610            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13611            try {
13612                return doCopyApk(imcs, temp);
13613            } finally {
13614                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13615            }
13616        }
13617
13618        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13619            if (origin.staged) {
13620                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13621                codeFile = origin.file;
13622                resourceFile = origin.file;
13623                return PackageManager.INSTALL_SUCCEEDED;
13624            }
13625
13626            try {
13627                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13628                final File tempDir =
13629                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13630                codeFile = tempDir;
13631                resourceFile = tempDir;
13632            } catch (IOException e) {
13633                Slog.w(TAG, "Failed to create copy file: " + e);
13634                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13635            }
13636
13637            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13638                @Override
13639                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13640                    if (!FileUtils.isValidExtFilename(name)) {
13641                        throw new IllegalArgumentException("Invalid filename: " + name);
13642                    }
13643                    try {
13644                        final File file = new File(codeFile, name);
13645                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13646                                O_RDWR | O_CREAT, 0644);
13647                        Os.chmod(file.getAbsolutePath(), 0644);
13648                        return new ParcelFileDescriptor(fd);
13649                    } catch (ErrnoException e) {
13650                        throw new RemoteException("Failed to open: " + e.getMessage());
13651                    }
13652                }
13653            };
13654
13655            int ret = PackageManager.INSTALL_SUCCEEDED;
13656            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13657            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13658                Slog.e(TAG, "Failed to copy package");
13659                return ret;
13660            }
13661
13662            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13663            NativeLibraryHelper.Handle handle = null;
13664            try {
13665                handle = NativeLibraryHelper.Handle.create(codeFile);
13666                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13667                        abiOverride);
13668            } catch (IOException e) {
13669                Slog.e(TAG, "Copying native libraries failed", e);
13670                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13671            } finally {
13672                IoUtils.closeQuietly(handle);
13673            }
13674
13675            return ret;
13676        }
13677
13678        int doPreInstall(int status) {
13679            if (status != PackageManager.INSTALL_SUCCEEDED) {
13680                cleanUp();
13681            }
13682            return status;
13683        }
13684
13685        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13686            if (status != PackageManager.INSTALL_SUCCEEDED) {
13687                cleanUp();
13688                return false;
13689            }
13690
13691            final File targetDir = codeFile.getParentFile();
13692            final File beforeCodeFile = codeFile;
13693            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13694
13695            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13696            try {
13697                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13698            } catch (ErrnoException e) {
13699                Slog.w(TAG, "Failed to rename", e);
13700                return false;
13701            }
13702
13703            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13704                Slog.w(TAG, "Failed to restorecon");
13705                return false;
13706            }
13707
13708            // Reflect the rename internally
13709            codeFile = afterCodeFile;
13710            resourceFile = afterCodeFile;
13711
13712            // Reflect the rename in scanned details
13713            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13714            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13715                    afterCodeFile, pkg.baseCodePath));
13716            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13717                    afterCodeFile, pkg.splitCodePaths));
13718
13719            // Reflect the rename in app info
13720            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13721            pkg.setApplicationInfoCodePath(pkg.codePath);
13722            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13723            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13724            pkg.setApplicationInfoResourcePath(pkg.codePath);
13725            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13726            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13727
13728            return true;
13729        }
13730
13731        int doPostInstall(int status, int uid) {
13732            if (status != PackageManager.INSTALL_SUCCEEDED) {
13733                cleanUp();
13734            }
13735            return status;
13736        }
13737
13738        @Override
13739        String getCodePath() {
13740            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13741        }
13742
13743        @Override
13744        String getResourcePath() {
13745            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13746        }
13747
13748        private boolean cleanUp() {
13749            if (codeFile == null || !codeFile.exists()) {
13750                return false;
13751            }
13752
13753            removeCodePathLI(codeFile);
13754
13755            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13756                resourceFile.delete();
13757            }
13758
13759            return true;
13760        }
13761
13762        void cleanUpResourcesLI() {
13763            // Try enumerating all code paths before deleting
13764            List<String> allCodePaths = Collections.EMPTY_LIST;
13765            if (codeFile != null && codeFile.exists()) {
13766                try {
13767                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13768                    allCodePaths = pkg.getAllCodePaths();
13769                } catch (PackageParserException e) {
13770                    // Ignored; we tried our best
13771                }
13772            }
13773
13774            cleanUp();
13775            removeDexFiles(allCodePaths, instructionSets);
13776        }
13777
13778        boolean doPostDeleteLI(boolean delete) {
13779            // XXX err, shouldn't we respect the delete flag?
13780            cleanUpResourcesLI();
13781            return true;
13782        }
13783    }
13784
13785    private boolean isAsecExternal(String cid) {
13786        final String asecPath = PackageHelper.getSdFilesystem(cid);
13787        return !asecPath.startsWith(mAsecInternalPath);
13788    }
13789
13790    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13791            PackageManagerException {
13792        if (copyRet < 0) {
13793            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13794                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13795                throw new PackageManagerException(copyRet, message);
13796            }
13797        }
13798    }
13799
13800    /**
13801     * Extract the MountService "container ID" from the full code path of an
13802     * .apk.
13803     */
13804    static String cidFromCodePath(String fullCodePath) {
13805        int eidx = fullCodePath.lastIndexOf("/");
13806        String subStr1 = fullCodePath.substring(0, eidx);
13807        int sidx = subStr1.lastIndexOf("/");
13808        return subStr1.substring(sidx+1, eidx);
13809    }
13810
13811    /**
13812     * Logic to handle installation of ASEC applications, including copying and
13813     * renaming logic.
13814     */
13815    class AsecInstallArgs extends InstallArgs {
13816        static final String RES_FILE_NAME = "pkg.apk";
13817        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13818
13819        String cid;
13820        String packagePath;
13821        String resourcePath;
13822
13823        /** New install */
13824        AsecInstallArgs(InstallParams params) {
13825            super(params.origin, params.move, params.observer, params.installFlags,
13826                    params.installerPackageName, params.volumeUuid,
13827                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13828                    params.grantedRuntimePermissions,
13829                    params.traceMethod, params.traceCookie, params.certificates);
13830        }
13831
13832        /** Existing install */
13833        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13834                        boolean isExternal, boolean isForwardLocked) {
13835            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13836              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13837                    instructionSets, null, null, null, 0, null /*certificates*/);
13838            // Hackily pretend we're still looking at a full code path
13839            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13840                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13841            }
13842
13843            // Extract cid from fullCodePath
13844            int eidx = fullCodePath.lastIndexOf("/");
13845            String subStr1 = fullCodePath.substring(0, eidx);
13846            int sidx = subStr1.lastIndexOf("/");
13847            cid = subStr1.substring(sidx+1, eidx);
13848            setMountPath(subStr1);
13849        }
13850
13851        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13852            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13853              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13854                    instructionSets, null, null, null, 0, null /*certificates*/);
13855            this.cid = cid;
13856            setMountPath(PackageHelper.getSdDir(cid));
13857        }
13858
13859        void createCopyFile() {
13860            cid = mInstallerService.allocateExternalStageCidLegacy();
13861        }
13862
13863        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13864            if (origin.staged && origin.cid != null) {
13865                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13866                cid = origin.cid;
13867                setMountPath(PackageHelper.getSdDir(cid));
13868                return PackageManager.INSTALL_SUCCEEDED;
13869            }
13870
13871            if (temp) {
13872                createCopyFile();
13873            } else {
13874                /*
13875                 * Pre-emptively destroy the container since it's destroyed if
13876                 * copying fails due to it existing anyway.
13877                 */
13878                PackageHelper.destroySdDir(cid);
13879            }
13880
13881            final String newMountPath = imcs.copyPackageToContainer(
13882                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13883                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13884
13885            if (newMountPath != null) {
13886                setMountPath(newMountPath);
13887                return PackageManager.INSTALL_SUCCEEDED;
13888            } else {
13889                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13890            }
13891        }
13892
13893        @Override
13894        String getCodePath() {
13895            return packagePath;
13896        }
13897
13898        @Override
13899        String getResourcePath() {
13900            return resourcePath;
13901        }
13902
13903        int doPreInstall(int status) {
13904            if (status != PackageManager.INSTALL_SUCCEEDED) {
13905                // Destroy container
13906                PackageHelper.destroySdDir(cid);
13907            } else {
13908                boolean mounted = PackageHelper.isContainerMounted(cid);
13909                if (!mounted) {
13910                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13911                            Process.SYSTEM_UID);
13912                    if (newMountPath != null) {
13913                        setMountPath(newMountPath);
13914                    } else {
13915                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13916                    }
13917                }
13918            }
13919            return status;
13920        }
13921
13922        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13923            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13924            String newMountPath = null;
13925            if (PackageHelper.isContainerMounted(cid)) {
13926                // Unmount the container
13927                if (!PackageHelper.unMountSdDir(cid)) {
13928                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13929                    return false;
13930                }
13931            }
13932            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13933                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13934                        " which might be stale. Will try to clean up.");
13935                // Clean up the stale container and proceed to recreate.
13936                if (!PackageHelper.destroySdDir(newCacheId)) {
13937                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13938                    return false;
13939                }
13940                // Successfully cleaned up stale container. Try to rename again.
13941                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13942                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13943                            + " inspite of cleaning it up.");
13944                    return false;
13945                }
13946            }
13947            if (!PackageHelper.isContainerMounted(newCacheId)) {
13948                Slog.w(TAG, "Mounting container " + newCacheId);
13949                newMountPath = PackageHelper.mountSdDir(newCacheId,
13950                        getEncryptKey(), Process.SYSTEM_UID);
13951            } else {
13952                newMountPath = PackageHelper.getSdDir(newCacheId);
13953            }
13954            if (newMountPath == null) {
13955                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13956                return false;
13957            }
13958            Log.i(TAG, "Succesfully renamed " + cid +
13959                    " to " + newCacheId +
13960                    " at new path: " + newMountPath);
13961            cid = newCacheId;
13962
13963            final File beforeCodeFile = new File(packagePath);
13964            setMountPath(newMountPath);
13965            final File afterCodeFile = new File(packagePath);
13966
13967            // Reflect the rename in scanned details
13968            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13969            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13970                    afterCodeFile, pkg.baseCodePath));
13971            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13972                    afterCodeFile, pkg.splitCodePaths));
13973
13974            // Reflect the rename in app info
13975            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13976            pkg.setApplicationInfoCodePath(pkg.codePath);
13977            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13978            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13979            pkg.setApplicationInfoResourcePath(pkg.codePath);
13980            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13981            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13982
13983            return true;
13984        }
13985
13986        private void setMountPath(String mountPath) {
13987            final File mountFile = new File(mountPath);
13988
13989            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13990            if (monolithicFile.exists()) {
13991                packagePath = monolithicFile.getAbsolutePath();
13992                if (isFwdLocked()) {
13993                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13994                } else {
13995                    resourcePath = packagePath;
13996                }
13997            } else {
13998                packagePath = mountFile.getAbsolutePath();
13999                resourcePath = packagePath;
14000            }
14001        }
14002
14003        int doPostInstall(int status, int uid) {
14004            if (status != PackageManager.INSTALL_SUCCEEDED) {
14005                cleanUp();
14006            } else {
14007                final int groupOwner;
14008                final String protectedFile;
14009                if (isFwdLocked()) {
14010                    groupOwner = UserHandle.getSharedAppGid(uid);
14011                    protectedFile = RES_FILE_NAME;
14012                } else {
14013                    groupOwner = -1;
14014                    protectedFile = null;
14015                }
14016
14017                if (uid < Process.FIRST_APPLICATION_UID
14018                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14019                    Slog.e(TAG, "Failed to finalize " + cid);
14020                    PackageHelper.destroySdDir(cid);
14021                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14022                }
14023
14024                boolean mounted = PackageHelper.isContainerMounted(cid);
14025                if (!mounted) {
14026                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14027                }
14028            }
14029            return status;
14030        }
14031
14032        private void cleanUp() {
14033            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14034
14035            // Destroy secure container
14036            PackageHelper.destroySdDir(cid);
14037        }
14038
14039        private List<String> getAllCodePaths() {
14040            final File codeFile = new File(getCodePath());
14041            if (codeFile != null && codeFile.exists()) {
14042                try {
14043                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14044                    return pkg.getAllCodePaths();
14045                } catch (PackageParserException e) {
14046                    // Ignored; we tried our best
14047                }
14048            }
14049            return Collections.EMPTY_LIST;
14050        }
14051
14052        void cleanUpResourcesLI() {
14053            // Enumerate all code paths before deleting
14054            cleanUpResourcesLI(getAllCodePaths());
14055        }
14056
14057        private void cleanUpResourcesLI(List<String> allCodePaths) {
14058            cleanUp();
14059            removeDexFiles(allCodePaths, instructionSets);
14060        }
14061
14062        String getPackageName() {
14063            return getAsecPackageName(cid);
14064        }
14065
14066        boolean doPostDeleteLI(boolean delete) {
14067            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14068            final List<String> allCodePaths = getAllCodePaths();
14069            boolean mounted = PackageHelper.isContainerMounted(cid);
14070            if (mounted) {
14071                // Unmount first
14072                if (PackageHelper.unMountSdDir(cid)) {
14073                    mounted = false;
14074                }
14075            }
14076            if (!mounted && delete) {
14077                cleanUpResourcesLI(allCodePaths);
14078            }
14079            return !mounted;
14080        }
14081
14082        @Override
14083        int doPreCopy() {
14084            if (isFwdLocked()) {
14085                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14086                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14087                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14088                }
14089            }
14090
14091            return PackageManager.INSTALL_SUCCEEDED;
14092        }
14093
14094        @Override
14095        int doPostCopy(int uid) {
14096            if (isFwdLocked()) {
14097                if (uid < Process.FIRST_APPLICATION_UID
14098                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14099                                RES_FILE_NAME)) {
14100                    Slog.e(TAG, "Failed to finalize " + cid);
14101                    PackageHelper.destroySdDir(cid);
14102                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14103                }
14104            }
14105
14106            return PackageManager.INSTALL_SUCCEEDED;
14107        }
14108    }
14109
14110    /**
14111     * Logic to handle movement of existing installed applications.
14112     */
14113    class MoveInstallArgs extends InstallArgs {
14114        private File codeFile;
14115        private File resourceFile;
14116
14117        /** New install */
14118        MoveInstallArgs(InstallParams params) {
14119            super(params.origin, params.move, params.observer, params.installFlags,
14120                    params.installerPackageName, params.volumeUuid,
14121                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14122                    params.grantedRuntimePermissions,
14123                    params.traceMethod, params.traceCookie, params.certificates);
14124        }
14125
14126        int copyApk(IMediaContainerService imcs, boolean temp) {
14127            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14128                    + move.fromUuid + " to " + move.toUuid);
14129            synchronized (mInstaller) {
14130                try {
14131                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14132                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14133                } catch (InstallerException e) {
14134                    Slog.w(TAG, "Failed to move app", e);
14135                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14136                }
14137            }
14138
14139            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14140            resourceFile = codeFile;
14141            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14142
14143            return PackageManager.INSTALL_SUCCEEDED;
14144        }
14145
14146        int doPreInstall(int status) {
14147            if (status != PackageManager.INSTALL_SUCCEEDED) {
14148                cleanUp(move.toUuid);
14149            }
14150            return status;
14151        }
14152
14153        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14154            if (status != PackageManager.INSTALL_SUCCEEDED) {
14155                cleanUp(move.toUuid);
14156                return false;
14157            }
14158
14159            // Reflect the move in app info
14160            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14161            pkg.setApplicationInfoCodePath(pkg.codePath);
14162            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14163            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14164            pkg.setApplicationInfoResourcePath(pkg.codePath);
14165            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14166            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14167
14168            return true;
14169        }
14170
14171        int doPostInstall(int status, int uid) {
14172            if (status == PackageManager.INSTALL_SUCCEEDED) {
14173                cleanUp(move.fromUuid);
14174            } else {
14175                cleanUp(move.toUuid);
14176            }
14177            return status;
14178        }
14179
14180        @Override
14181        String getCodePath() {
14182            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14183        }
14184
14185        @Override
14186        String getResourcePath() {
14187            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14188        }
14189
14190        private boolean cleanUp(String volumeUuid) {
14191            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14192                    move.dataAppName);
14193            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14194            final int[] userIds = sUserManager.getUserIds();
14195            synchronized (mInstallLock) {
14196                // Clean up both app data and code
14197                // All package moves are frozen until finished
14198                for (int userId : userIds) {
14199                    try {
14200                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14201                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14202                    } catch (InstallerException e) {
14203                        Slog.w(TAG, String.valueOf(e));
14204                    }
14205                }
14206                removeCodePathLI(codeFile);
14207            }
14208            return true;
14209        }
14210
14211        void cleanUpResourcesLI() {
14212            throw new UnsupportedOperationException();
14213        }
14214
14215        boolean doPostDeleteLI(boolean delete) {
14216            throw new UnsupportedOperationException();
14217        }
14218    }
14219
14220    static String getAsecPackageName(String packageCid) {
14221        int idx = packageCid.lastIndexOf("-");
14222        if (idx == -1) {
14223            return packageCid;
14224        }
14225        return packageCid.substring(0, idx);
14226    }
14227
14228    // Utility method used to create code paths based on package name and available index.
14229    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14230        String idxStr = "";
14231        int idx = 1;
14232        // Fall back to default value of idx=1 if prefix is not
14233        // part of oldCodePath
14234        if (oldCodePath != null) {
14235            String subStr = oldCodePath;
14236            // Drop the suffix right away
14237            if (suffix != null && subStr.endsWith(suffix)) {
14238                subStr = subStr.substring(0, subStr.length() - suffix.length());
14239            }
14240            // If oldCodePath already contains prefix find out the
14241            // ending index to either increment or decrement.
14242            int sidx = subStr.lastIndexOf(prefix);
14243            if (sidx != -1) {
14244                subStr = subStr.substring(sidx + prefix.length());
14245                if (subStr != null) {
14246                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14247                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14248                    }
14249                    try {
14250                        idx = Integer.parseInt(subStr);
14251                        if (idx <= 1) {
14252                            idx++;
14253                        } else {
14254                            idx--;
14255                        }
14256                    } catch(NumberFormatException e) {
14257                    }
14258                }
14259            }
14260        }
14261        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14262        return prefix + idxStr;
14263    }
14264
14265    private File getNextCodePath(File targetDir, String packageName) {
14266        File result;
14267        SecureRandom random = new SecureRandom();
14268        byte[] bytes = new byte[16];
14269        do {
14270            random.nextBytes(bytes);
14271            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14272            result = new File(targetDir, packageName + "-" + suffix);
14273        } while (result.exists());
14274        return result;
14275    }
14276
14277    // Utility method that returns the relative package path with respect
14278    // to the installation directory. Like say for /data/data/com.test-1.apk
14279    // string com.test-1 is returned.
14280    static String deriveCodePathName(String codePath) {
14281        if (codePath == null) {
14282            return null;
14283        }
14284        final File codeFile = new File(codePath);
14285        final String name = codeFile.getName();
14286        if (codeFile.isDirectory()) {
14287            return name;
14288        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14289            final int lastDot = name.lastIndexOf('.');
14290            return name.substring(0, lastDot);
14291        } else {
14292            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14293            return null;
14294        }
14295    }
14296
14297    static class PackageInstalledInfo {
14298        String name;
14299        int uid;
14300        // The set of users that originally had this package installed.
14301        int[] origUsers;
14302        // The set of users that now have this package installed.
14303        int[] newUsers;
14304        PackageParser.Package pkg;
14305        int returnCode;
14306        String returnMsg;
14307        PackageRemovedInfo removedInfo;
14308        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14309
14310        public void setError(int code, String msg) {
14311            setReturnCode(code);
14312            setReturnMessage(msg);
14313            Slog.w(TAG, msg);
14314        }
14315
14316        public void setError(String msg, PackageParserException e) {
14317            setReturnCode(e.error);
14318            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14319            Slog.w(TAG, msg, e);
14320        }
14321
14322        public void setError(String msg, PackageManagerException e) {
14323            returnCode = e.error;
14324            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14325            Slog.w(TAG, msg, e);
14326        }
14327
14328        public void setReturnCode(int returnCode) {
14329            this.returnCode = returnCode;
14330            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14331            for (int i = 0; i < childCount; i++) {
14332                addedChildPackages.valueAt(i).returnCode = returnCode;
14333            }
14334        }
14335
14336        private void setReturnMessage(String returnMsg) {
14337            this.returnMsg = returnMsg;
14338            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14339            for (int i = 0; i < childCount; i++) {
14340                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14341            }
14342        }
14343
14344        // In some error cases we want to convey more info back to the observer
14345        String origPackage;
14346        String origPermission;
14347    }
14348
14349    /*
14350     * Install a non-existing package.
14351     */
14352    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14353            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14354            PackageInstalledInfo res) {
14355        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14356
14357        // Remember this for later, in case we need to rollback this install
14358        String pkgName = pkg.packageName;
14359
14360        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14361
14362        synchronized(mPackages) {
14363            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14364            if (renamedPackage != null) {
14365                // A package with the same name is already installed, though
14366                // it has been renamed to an older name.  The package we
14367                // are trying to install should be installed as an update to
14368                // the existing one, but that has not been requested, so bail.
14369                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14370                        + " without first uninstalling package running as "
14371                        + renamedPackage);
14372                return;
14373            }
14374            if (mPackages.containsKey(pkgName)) {
14375                // Don't allow installation over an existing package with the same name.
14376                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14377                        + " without first uninstalling.");
14378                return;
14379            }
14380        }
14381
14382        try {
14383            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14384                    System.currentTimeMillis(), user);
14385
14386            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14387
14388            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14389                prepareAppDataAfterInstallLIF(newPackage);
14390
14391            } else {
14392                // Remove package from internal structures, but keep around any
14393                // data that might have already existed
14394                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14395                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14396            }
14397        } catch (PackageManagerException e) {
14398            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14399        }
14400
14401        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14402    }
14403
14404    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14405        // Can't rotate keys during boot or if sharedUser.
14406        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14407                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14408            return false;
14409        }
14410        // app is using upgradeKeySets; make sure all are valid
14411        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14412        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14413        for (int i = 0; i < upgradeKeySets.length; i++) {
14414            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14415                Slog.wtf(TAG, "Package "
14416                         + (oldPs.name != null ? oldPs.name : "<null>")
14417                         + " contains upgrade-key-set reference to unknown key-set: "
14418                         + upgradeKeySets[i]
14419                         + " reverting to signatures check.");
14420                return false;
14421            }
14422        }
14423        return true;
14424    }
14425
14426    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14427        // Upgrade keysets are being used.  Determine if new package has a superset of the
14428        // required keys.
14429        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14430        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14431        for (int i = 0; i < upgradeKeySets.length; i++) {
14432            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14433            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14434                return true;
14435            }
14436        }
14437        return false;
14438    }
14439
14440    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14441        try (DigestInputStream digestStream =
14442                new DigestInputStream(new FileInputStream(file), digest)) {
14443            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14444        }
14445    }
14446
14447    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14448            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14449        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14450
14451        final PackageParser.Package oldPackage;
14452        final String pkgName = pkg.packageName;
14453        final int[] allUsers;
14454        final int[] installedUsers;
14455
14456        synchronized(mPackages) {
14457            oldPackage = mPackages.get(pkgName);
14458            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14459
14460            // don't allow upgrade to target a release SDK from a pre-release SDK
14461            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14462                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14463            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14464                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14465            if (oldTargetsPreRelease
14466                    && !newTargetsPreRelease
14467                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14468                Slog.w(TAG, "Can't install package targeting released sdk");
14469                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14470                return;
14471            }
14472
14473            // don't allow an upgrade from full to ephemeral
14474            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14475            if (isEphemeral && !oldIsEphemeral) {
14476                // can't downgrade from full to ephemeral
14477                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14478                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14479                return;
14480            }
14481
14482            // verify signatures are valid
14483            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14484            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14485                if (!checkUpgradeKeySetLP(ps, pkg)) {
14486                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14487                            "New package not signed by keys specified by upgrade-keysets: "
14488                                    + pkgName);
14489                    return;
14490                }
14491            } else {
14492                // default to original signature matching
14493                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14494                        != PackageManager.SIGNATURE_MATCH) {
14495                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14496                            "New package has a different signature: " + pkgName);
14497                    return;
14498                }
14499            }
14500
14501            // don't allow a system upgrade unless the upgrade hash matches
14502            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14503                byte[] digestBytes = null;
14504                try {
14505                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14506                    updateDigest(digest, new File(pkg.baseCodePath));
14507                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14508                        for (String path : pkg.splitCodePaths) {
14509                            updateDigest(digest, new File(path));
14510                        }
14511                    }
14512                    digestBytes = digest.digest();
14513                } catch (NoSuchAlgorithmException | IOException e) {
14514                    res.setError(INSTALL_FAILED_INVALID_APK,
14515                            "Could not compute hash: " + pkgName);
14516                    return;
14517                }
14518                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14519                    res.setError(INSTALL_FAILED_INVALID_APK,
14520                            "New package fails restrict-update check: " + pkgName);
14521                    return;
14522                }
14523                // retain upgrade restriction
14524                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14525            }
14526
14527            // Check for shared user id changes
14528            String invalidPackageName =
14529                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14530            if (invalidPackageName != null) {
14531                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14532                        "Package " + invalidPackageName + " tried to change user "
14533                                + oldPackage.mSharedUserId);
14534                return;
14535            }
14536
14537            // In case of rollback, remember per-user/profile install state
14538            allUsers = sUserManager.getUserIds();
14539            installedUsers = ps.queryInstalledUsers(allUsers, true);
14540        }
14541
14542        // Update what is removed
14543        res.removedInfo = new PackageRemovedInfo();
14544        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14545        res.removedInfo.removedPackage = oldPackage.packageName;
14546        res.removedInfo.isUpdate = true;
14547        res.removedInfo.origUsers = installedUsers;
14548        final int childCount = (oldPackage.childPackages != null)
14549                ? oldPackage.childPackages.size() : 0;
14550        for (int i = 0; i < childCount; i++) {
14551            boolean childPackageUpdated = false;
14552            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14553            if (res.addedChildPackages != null) {
14554                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14555                if (childRes != null) {
14556                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14557                    childRes.removedInfo.removedPackage = childPkg.packageName;
14558                    childRes.removedInfo.isUpdate = true;
14559                    childPackageUpdated = true;
14560                }
14561            }
14562            if (!childPackageUpdated) {
14563                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14564                childRemovedRes.removedPackage = childPkg.packageName;
14565                childRemovedRes.isUpdate = false;
14566                childRemovedRes.dataRemoved = true;
14567                synchronized (mPackages) {
14568                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14569                    if (childPs != null) {
14570                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14571                    }
14572                }
14573                if (res.removedInfo.removedChildPackages == null) {
14574                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14575                }
14576                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14577            }
14578        }
14579
14580        boolean sysPkg = (isSystemApp(oldPackage));
14581        if (sysPkg) {
14582            // Set the system/privileged flags as needed
14583            final boolean privileged =
14584                    (oldPackage.applicationInfo.privateFlags
14585                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14586            final int systemPolicyFlags = policyFlags
14587                    | PackageParser.PARSE_IS_SYSTEM
14588                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14589
14590            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14591                    user, allUsers, installerPackageName, res);
14592        } else {
14593            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14594                    user, allUsers, installerPackageName, res);
14595        }
14596    }
14597
14598    public List<String> getPreviousCodePaths(String packageName) {
14599        final PackageSetting ps = mSettings.mPackages.get(packageName);
14600        final List<String> result = new ArrayList<String>();
14601        if (ps != null && ps.oldCodePaths != null) {
14602            result.addAll(ps.oldCodePaths);
14603        }
14604        return result;
14605    }
14606
14607    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14608            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14609            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14610        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14611                + deletedPackage);
14612
14613        String pkgName = deletedPackage.packageName;
14614        boolean deletedPkg = true;
14615        boolean addedPkg = false;
14616        boolean updatedSettings = false;
14617        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14618        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14619                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14620
14621        final long origUpdateTime = (pkg.mExtras != null)
14622                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14623
14624        // First delete the existing package while retaining the data directory
14625        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14626                res.removedInfo, true, pkg)) {
14627            // If the existing package wasn't successfully deleted
14628            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14629            deletedPkg = false;
14630        } else {
14631            // Successfully deleted the old package; proceed with replace.
14632
14633            // If deleted package lived in a container, give users a chance to
14634            // relinquish resources before killing.
14635            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14636                if (DEBUG_INSTALL) {
14637                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14638                }
14639                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14640                final ArrayList<String> pkgList = new ArrayList<String>(1);
14641                pkgList.add(deletedPackage.applicationInfo.packageName);
14642                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14643            }
14644
14645            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14646                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14647            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14648
14649            try {
14650                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14651                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14652                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14653
14654                // Update the in-memory copy of the previous code paths.
14655                PackageSetting ps = mSettings.mPackages.get(pkgName);
14656                if (!killApp) {
14657                    if (ps.oldCodePaths == null) {
14658                        ps.oldCodePaths = new ArraySet<>();
14659                    }
14660                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14661                    if (deletedPackage.splitCodePaths != null) {
14662                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14663                    }
14664                } else {
14665                    ps.oldCodePaths = null;
14666                }
14667                if (ps.childPackageNames != null) {
14668                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14669                        final String childPkgName = ps.childPackageNames.get(i);
14670                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14671                        childPs.oldCodePaths = ps.oldCodePaths;
14672                    }
14673                }
14674                prepareAppDataAfterInstallLIF(newPackage);
14675                addedPkg = true;
14676            } catch (PackageManagerException e) {
14677                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14678            }
14679        }
14680
14681        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14682            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14683
14684            // Revert all internal state mutations and added folders for the failed install
14685            if (addedPkg) {
14686                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14687                        res.removedInfo, true, null);
14688            }
14689
14690            // Restore the old package
14691            if (deletedPkg) {
14692                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14693                File restoreFile = new File(deletedPackage.codePath);
14694                // Parse old package
14695                boolean oldExternal = isExternal(deletedPackage);
14696                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14697                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14698                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14699                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14700                try {
14701                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14702                            null);
14703                } catch (PackageManagerException e) {
14704                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14705                            + e.getMessage());
14706                    return;
14707                }
14708
14709                synchronized (mPackages) {
14710                    // Ensure the installer package name up to date
14711                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14712
14713                    // Update permissions for restored package
14714                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14715
14716                    mSettings.writeLPr();
14717                }
14718
14719                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14720            }
14721        } else {
14722            synchronized (mPackages) {
14723                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14724                if (ps != null) {
14725                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14726                    if (res.removedInfo.removedChildPackages != null) {
14727                        final int childCount = res.removedInfo.removedChildPackages.size();
14728                        // Iterate in reverse as we may modify the collection
14729                        for (int i = childCount - 1; i >= 0; i--) {
14730                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14731                            if (res.addedChildPackages.containsKey(childPackageName)) {
14732                                res.removedInfo.removedChildPackages.removeAt(i);
14733                            } else {
14734                                PackageRemovedInfo childInfo = res.removedInfo
14735                                        .removedChildPackages.valueAt(i);
14736                                childInfo.removedForAllUsers = mPackages.get(
14737                                        childInfo.removedPackage) == null;
14738                            }
14739                        }
14740                    }
14741                }
14742            }
14743        }
14744    }
14745
14746    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14747            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14748            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14749        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14750                + ", old=" + deletedPackage);
14751
14752        final boolean disabledSystem;
14753
14754        // Remove existing system package
14755        removePackageLI(deletedPackage, true);
14756
14757        synchronized (mPackages) {
14758            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14759        }
14760        if (!disabledSystem) {
14761            // We didn't need to disable the .apk as a current system package,
14762            // which means we are replacing another update that is already
14763            // installed.  We need to make sure to delete the older one's .apk.
14764            res.removedInfo.args = createInstallArgsForExisting(0,
14765                    deletedPackage.applicationInfo.getCodePath(),
14766                    deletedPackage.applicationInfo.getResourcePath(),
14767                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14768        } else {
14769            res.removedInfo.args = null;
14770        }
14771
14772        // Successfully disabled the old package. Now proceed with re-installation
14773        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14774                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14775        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14776
14777        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14778        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14779                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14780
14781        PackageParser.Package newPackage = null;
14782        try {
14783            // Add the package to the internal data structures
14784            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14785
14786            // Set the update and install times
14787            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14788            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14789                    System.currentTimeMillis());
14790
14791            // Update the package dynamic state if succeeded
14792            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14793                // Now that the install succeeded make sure we remove data
14794                // directories for any child package the update removed.
14795                final int deletedChildCount = (deletedPackage.childPackages != null)
14796                        ? deletedPackage.childPackages.size() : 0;
14797                final int newChildCount = (newPackage.childPackages != null)
14798                        ? newPackage.childPackages.size() : 0;
14799                for (int i = 0; i < deletedChildCount; i++) {
14800                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14801                    boolean childPackageDeleted = true;
14802                    for (int j = 0; j < newChildCount; j++) {
14803                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14804                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14805                            childPackageDeleted = false;
14806                            break;
14807                        }
14808                    }
14809                    if (childPackageDeleted) {
14810                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14811                                deletedChildPkg.packageName);
14812                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14813                            PackageRemovedInfo removedChildRes = res.removedInfo
14814                                    .removedChildPackages.get(deletedChildPkg.packageName);
14815                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14816                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14817                        }
14818                    }
14819                }
14820
14821                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14822                prepareAppDataAfterInstallLIF(newPackage);
14823            }
14824        } catch (PackageManagerException e) {
14825            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14826            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14827        }
14828
14829        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14830            // Re installation failed. Restore old information
14831            // Remove new pkg information
14832            if (newPackage != null) {
14833                removeInstalledPackageLI(newPackage, true);
14834            }
14835            // Add back the old system package
14836            try {
14837                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14838            } catch (PackageManagerException e) {
14839                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14840            }
14841
14842            synchronized (mPackages) {
14843                if (disabledSystem) {
14844                    enableSystemPackageLPw(deletedPackage);
14845                }
14846
14847                // Ensure the installer package name up to date
14848                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14849
14850                // Update permissions for restored package
14851                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14852
14853                mSettings.writeLPr();
14854            }
14855
14856            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14857                    + " after failed upgrade");
14858        }
14859    }
14860
14861    /**
14862     * Checks whether the parent or any of the child packages have a change shared
14863     * user. For a package to be a valid update the shred users of the parent and
14864     * the children should match. We may later support changing child shared users.
14865     * @param oldPkg The updated package.
14866     * @param newPkg The update package.
14867     * @return The shared user that change between the versions.
14868     */
14869    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14870            PackageParser.Package newPkg) {
14871        // Check parent shared user
14872        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14873            return newPkg.packageName;
14874        }
14875        // Check child shared users
14876        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14877        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14878        for (int i = 0; i < newChildCount; i++) {
14879            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14880            // If this child was present, did it have the same shared user?
14881            for (int j = 0; j < oldChildCount; j++) {
14882                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14883                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14884                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14885                    return newChildPkg.packageName;
14886                }
14887            }
14888        }
14889        return null;
14890    }
14891
14892    private void removeNativeBinariesLI(PackageSetting ps) {
14893        // Remove the lib path for the parent package
14894        if (ps != null) {
14895            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14896            // Remove the lib path for the child packages
14897            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14898            for (int i = 0; i < childCount; i++) {
14899                PackageSetting childPs = null;
14900                synchronized (mPackages) {
14901                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14902                }
14903                if (childPs != null) {
14904                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14905                            .legacyNativeLibraryPathString);
14906                }
14907            }
14908        }
14909    }
14910
14911    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14912        // Enable the parent package
14913        mSettings.enableSystemPackageLPw(pkg.packageName);
14914        // Enable the child packages
14915        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14916        for (int i = 0; i < childCount; i++) {
14917            PackageParser.Package childPkg = pkg.childPackages.get(i);
14918            mSettings.enableSystemPackageLPw(childPkg.packageName);
14919        }
14920    }
14921
14922    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14923            PackageParser.Package newPkg) {
14924        // Disable the parent package (parent always replaced)
14925        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14926        // Disable the child packages
14927        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14928        for (int i = 0; i < childCount; i++) {
14929            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14930            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14931            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14932        }
14933        return disabled;
14934    }
14935
14936    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14937            String installerPackageName) {
14938        // Enable the parent package
14939        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14940        // Enable the child packages
14941        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14942        for (int i = 0; i < childCount; i++) {
14943            PackageParser.Package childPkg = pkg.childPackages.get(i);
14944            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14945        }
14946    }
14947
14948    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14949        // Collect all used permissions in the UID
14950        ArraySet<String> usedPermissions = new ArraySet<>();
14951        final int packageCount = su.packages.size();
14952        for (int i = 0; i < packageCount; i++) {
14953            PackageSetting ps = su.packages.valueAt(i);
14954            if (ps.pkg == null) {
14955                continue;
14956            }
14957            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14958            for (int j = 0; j < requestedPermCount; j++) {
14959                String permission = ps.pkg.requestedPermissions.get(j);
14960                BasePermission bp = mSettings.mPermissions.get(permission);
14961                if (bp != null) {
14962                    usedPermissions.add(permission);
14963                }
14964            }
14965        }
14966
14967        PermissionsState permissionsState = su.getPermissionsState();
14968        // Prune install permissions
14969        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14970        final int installPermCount = installPermStates.size();
14971        for (int i = installPermCount - 1; i >= 0;  i--) {
14972            PermissionState permissionState = installPermStates.get(i);
14973            if (!usedPermissions.contains(permissionState.getName())) {
14974                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14975                if (bp != null) {
14976                    permissionsState.revokeInstallPermission(bp);
14977                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14978                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14979                }
14980            }
14981        }
14982
14983        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14984
14985        // Prune runtime permissions
14986        for (int userId : allUserIds) {
14987            List<PermissionState> runtimePermStates = permissionsState
14988                    .getRuntimePermissionStates(userId);
14989            final int runtimePermCount = runtimePermStates.size();
14990            for (int i = runtimePermCount - 1; i >= 0; i--) {
14991                PermissionState permissionState = runtimePermStates.get(i);
14992                if (!usedPermissions.contains(permissionState.getName())) {
14993                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14994                    if (bp != null) {
14995                        permissionsState.revokeRuntimePermission(bp, userId);
14996                        permissionsState.updatePermissionFlags(bp, userId,
14997                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14998                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14999                                runtimePermissionChangedUserIds, userId);
15000                    }
15001                }
15002            }
15003        }
15004
15005        return runtimePermissionChangedUserIds;
15006    }
15007
15008    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15009            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15010        // Update the parent package setting
15011        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15012                res, user);
15013        // Update the child packages setting
15014        final int childCount = (newPackage.childPackages != null)
15015                ? newPackage.childPackages.size() : 0;
15016        for (int i = 0; i < childCount; i++) {
15017            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15018            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15019            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15020                    childRes.origUsers, childRes, user);
15021        }
15022    }
15023
15024    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15025            String installerPackageName, int[] allUsers, int[] installedForUsers,
15026            PackageInstalledInfo res, UserHandle user) {
15027        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15028
15029        String pkgName = newPackage.packageName;
15030        synchronized (mPackages) {
15031            //write settings. the installStatus will be incomplete at this stage.
15032            //note that the new package setting would have already been
15033            //added to mPackages. It hasn't been persisted yet.
15034            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15035            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15036            mSettings.writeLPr();
15037            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15038        }
15039
15040        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15041        synchronized (mPackages) {
15042            updatePermissionsLPw(newPackage.packageName, newPackage,
15043                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15044                            ? UPDATE_PERMISSIONS_ALL : 0));
15045            // For system-bundled packages, we assume that installing an upgraded version
15046            // of the package implies that the user actually wants to run that new code,
15047            // so we enable the package.
15048            PackageSetting ps = mSettings.mPackages.get(pkgName);
15049            final int userId = user.getIdentifier();
15050            if (ps != null) {
15051                if (isSystemApp(newPackage)) {
15052                    if (DEBUG_INSTALL) {
15053                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15054                    }
15055                    // Enable system package for requested users
15056                    if (res.origUsers != null) {
15057                        for (int origUserId : res.origUsers) {
15058                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15059                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15060                                        origUserId, installerPackageName);
15061                            }
15062                        }
15063                    }
15064                    // Also convey the prior install/uninstall state
15065                    if (allUsers != null && installedForUsers != null) {
15066                        for (int currentUserId : allUsers) {
15067                            final boolean installed = ArrayUtils.contains(
15068                                    installedForUsers, currentUserId);
15069                            if (DEBUG_INSTALL) {
15070                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15071                            }
15072                            ps.setInstalled(installed, currentUserId);
15073                        }
15074                        // these install state changes will be persisted in the
15075                        // upcoming call to mSettings.writeLPr().
15076                    }
15077                }
15078                // It's implied that when a user requests installation, they want the app to be
15079                // installed and enabled.
15080                if (userId != UserHandle.USER_ALL) {
15081                    ps.setInstalled(true, userId);
15082                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15083                }
15084            }
15085            res.name = pkgName;
15086            res.uid = newPackage.applicationInfo.uid;
15087            res.pkg = newPackage;
15088            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15089            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15090            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15091            //to update install status
15092            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15093            mSettings.writeLPr();
15094            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15095        }
15096
15097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15098    }
15099
15100    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15101        try {
15102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15103            installPackageLI(args, res);
15104        } finally {
15105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15106        }
15107    }
15108
15109    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15110        final int installFlags = args.installFlags;
15111        final String installerPackageName = args.installerPackageName;
15112        final String volumeUuid = args.volumeUuid;
15113        final File tmpPackageFile = new File(args.getCodePath());
15114        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15115        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15116                || (args.volumeUuid != null));
15117        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15118        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15119        boolean replace = false;
15120        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15121        if (args.move != null) {
15122            // moving a complete application; perform an initial scan on the new install location
15123            scanFlags |= SCAN_INITIAL;
15124        }
15125        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15126            scanFlags |= SCAN_DONT_KILL_APP;
15127        }
15128
15129        // Result object to be returned
15130        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15131
15132        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15133
15134        // Sanity check
15135        if (ephemeral && (forwardLocked || onExternal)) {
15136            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15137                    + " external=" + onExternal);
15138            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15139            return;
15140        }
15141
15142        // Retrieve PackageSettings and parse package
15143        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15144                | PackageParser.PARSE_ENFORCE_CODE
15145                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15146                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15147                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15148                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15149        PackageParser pp = new PackageParser();
15150        pp.setSeparateProcesses(mSeparateProcesses);
15151        pp.setDisplayMetrics(mMetrics);
15152
15153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15154        final PackageParser.Package pkg;
15155        try {
15156            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15157        } catch (PackageParserException e) {
15158            res.setError("Failed parse during installPackageLI", e);
15159            return;
15160        } finally {
15161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15162        }
15163
15164        // If we are installing a clustered package add results for the children
15165        if (pkg.childPackages != null) {
15166            synchronized (mPackages) {
15167                final int childCount = pkg.childPackages.size();
15168                for (int i = 0; i < childCount; i++) {
15169                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15170                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15171                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15172                    childRes.pkg = childPkg;
15173                    childRes.name = childPkg.packageName;
15174                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15175                    if (childPs != null) {
15176                        childRes.origUsers = childPs.queryInstalledUsers(
15177                                sUserManager.getUserIds(), true);
15178                    }
15179                    if ((mPackages.containsKey(childPkg.packageName))) {
15180                        childRes.removedInfo = new PackageRemovedInfo();
15181                        childRes.removedInfo.removedPackage = childPkg.packageName;
15182                    }
15183                    if (res.addedChildPackages == null) {
15184                        res.addedChildPackages = new ArrayMap<>();
15185                    }
15186                    res.addedChildPackages.put(childPkg.packageName, childRes);
15187                }
15188            }
15189        }
15190
15191        // If package doesn't declare API override, mark that we have an install
15192        // time CPU ABI override.
15193        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15194            pkg.cpuAbiOverride = args.abiOverride;
15195        }
15196
15197        String pkgName = res.name = pkg.packageName;
15198        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15199            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15200                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15201                return;
15202            }
15203        }
15204
15205        try {
15206            // either use what we've been given or parse directly from the APK
15207            if (args.certificates != null) {
15208                try {
15209                    PackageParser.populateCertificates(pkg, args.certificates);
15210                } catch (PackageParserException e) {
15211                    // there was something wrong with the certificates we were given;
15212                    // try to pull them from the APK
15213                    PackageParser.collectCertificates(pkg, parseFlags);
15214                }
15215            } else {
15216                PackageParser.collectCertificates(pkg, parseFlags);
15217            }
15218        } catch (PackageParserException e) {
15219            res.setError("Failed collect during installPackageLI", e);
15220            return;
15221        }
15222
15223        // Get rid of all references to package scan path via parser.
15224        pp = null;
15225        String oldCodePath = null;
15226        boolean systemApp = false;
15227        synchronized (mPackages) {
15228            // Check if installing already existing package
15229            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15230                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15231                if (pkg.mOriginalPackages != null
15232                        && pkg.mOriginalPackages.contains(oldName)
15233                        && mPackages.containsKey(oldName)) {
15234                    // This package is derived from an original package,
15235                    // and this device has been updating from that original
15236                    // name.  We must continue using the original name, so
15237                    // rename the new package here.
15238                    pkg.setPackageName(oldName);
15239                    pkgName = pkg.packageName;
15240                    replace = true;
15241                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15242                            + oldName + " pkgName=" + pkgName);
15243                } else if (mPackages.containsKey(pkgName)) {
15244                    // This package, under its official name, already exists
15245                    // on the device; we should replace it.
15246                    replace = true;
15247                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15248                }
15249
15250                // Child packages are installed through the parent package
15251                if (pkg.parentPackage != null) {
15252                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15253                            "Package " + pkg.packageName + " is child of package "
15254                                    + pkg.parentPackage.parentPackage + ". Child packages "
15255                                    + "can be updated only through the parent package.");
15256                    return;
15257                }
15258
15259                if (replace) {
15260                    // Prevent apps opting out from runtime permissions
15261                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15262                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15263                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15264                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15265                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15266                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15267                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15268                                        + " doesn't support runtime permissions but the old"
15269                                        + " target SDK " + oldTargetSdk + " does.");
15270                        return;
15271                    }
15272
15273                    // Prevent installing of child packages
15274                    if (oldPackage.parentPackage != null) {
15275                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15276                                "Package " + pkg.packageName + " is child of package "
15277                                        + oldPackage.parentPackage + ". Child packages "
15278                                        + "can be updated only through the parent package.");
15279                        return;
15280                    }
15281                }
15282            }
15283
15284            PackageSetting ps = mSettings.mPackages.get(pkgName);
15285            if (ps != null) {
15286                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15287
15288                // Quick sanity check that we're signed correctly if updating;
15289                // we'll check this again later when scanning, but we want to
15290                // bail early here before tripping over redefined permissions.
15291                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15292                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15293                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15294                                + pkg.packageName + " upgrade keys do not match the "
15295                                + "previously installed version");
15296                        return;
15297                    }
15298                } else {
15299                    try {
15300                        verifySignaturesLP(ps, pkg);
15301                    } catch (PackageManagerException e) {
15302                        res.setError(e.error, e.getMessage());
15303                        return;
15304                    }
15305                }
15306
15307                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15308                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15309                    systemApp = (ps.pkg.applicationInfo.flags &
15310                            ApplicationInfo.FLAG_SYSTEM) != 0;
15311                }
15312                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15313            }
15314
15315            // Check whether the newly-scanned package wants to define an already-defined perm
15316            int N = pkg.permissions.size();
15317            for (int i = N-1; i >= 0; i--) {
15318                PackageParser.Permission perm = pkg.permissions.get(i);
15319                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15320                if (bp != null) {
15321                    // If the defining package is signed with our cert, it's okay.  This
15322                    // also includes the "updating the same package" case, of course.
15323                    // "updating same package" could also involve key-rotation.
15324                    final boolean sigsOk;
15325                    if (bp.sourcePackage.equals(pkg.packageName)
15326                            && (bp.packageSetting instanceof PackageSetting)
15327                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15328                                    scanFlags))) {
15329                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15330                    } else {
15331                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15332                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15333                    }
15334                    if (!sigsOk) {
15335                        // If the owning package is the system itself, we log but allow
15336                        // install to proceed; we fail the install on all other permission
15337                        // redefinitions.
15338                        if (!bp.sourcePackage.equals("android")) {
15339                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15340                                    + pkg.packageName + " attempting to redeclare permission "
15341                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15342                            res.origPermission = perm.info.name;
15343                            res.origPackage = bp.sourcePackage;
15344                            return;
15345                        } else {
15346                            Slog.w(TAG, "Package " + pkg.packageName
15347                                    + " attempting to redeclare system permission "
15348                                    + perm.info.name + "; ignoring new declaration");
15349                            pkg.permissions.remove(i);
15350                        }
15351                    }
15352                }
15353            }
15354        }
15355
15356        if (systemApp) {
15357            if (onExternal) {
15358                // Abort update; system app can't be replaced with app on sdcard
15359                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15360                        "Cannot install updates to system apps on sdcard");
15361                return;
15362            } else if (ephemeral) {
15363                // Abort update; system app can't be replaced with an ephemeral app
15364                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15365                        "Cannot update a system app with an ephemeral app");
15366                return;
15367            }
15368        }
15369
15370        if (args.move != null) {
15371            // We did an in-place move, so dex is ready to roll
15372            scanFlags |= SCAN_NO_DEX;
15373            scanFlags |= SCAN_MOVE;
15374
15375            synchronized (mPackages) {
15376                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15377                if (ps == null) {
15378                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15379                            "Missing settings for moved package " + pkgName);
15380                }
15381
15382                // We moved the entire application as-is, so bring over the
15383                // previously derived ABI information.
15384                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15385                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15386            }
15387
15388        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15389            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15390            scanFlags |= SCAN_NO_DEX;
15391
15392            try {
15393                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15394                    args.abiOverride : pkg.cpuAbiOverride);
15395                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15396                        true /*extractLibs*/, mAppLib32InstallDir);
15397            } catch (PackageManagerException pme) {
15398                Slog.e(TAG, "Error deriving application ABI", pme);
15399                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15400                return;
15401            }
15402
15403            // Shared libraries for the package need to be updated.
15404            synchronized (mPackages) {
15405                try {
15406                    updateSharedLibrariesLPr(pkg, null);
15407                } catch (PackageManagerException e) {
15408                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15409                }
15410            }
15411            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15412            // Do not run PackageDexOptimizer through the local performDexOpt
15413            // method because `pkg` may not be in `mPackages` yet.
15414            //
15415            // Also, don't fail application installs if the dexopt step fails.
15416            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15417                    null /* instructionSets */, false /* checkProfiles */,
15418                    getCompilerFilterForReason(REASON_INSTALL),
15419                    getOrCreateCompilerPackageStats(pkg));
15420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15421
15422            // Notify BackgroundDexOptService that the package has been changed.
15423            // If this is an update of a package which used to fail to compile,
15424            // BDOS will remove it from its blacklist.
15425            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15426        }
15427
15428        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15429            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15430            return;
15431        }
15432
15433        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15434
15435        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15436                "installPackageLI")) {
15437            if (replace) {
15438                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15439                        installerPackageName, res);
15440            } else {
15441                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15442                        args.user, installerPackageName, volumeUuid, res);
15443            }
15444        }
15445        synchronized (mPackages) {
15446            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15447            if (ps != null) {
15448                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15449            }
15450
15451            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15452            for (int i = 0; i < childCount; i++) {
15453                PackageParser.Package childPkg = pkg.childPackages.get(i);
15454                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15455                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15456                if (childPs != null) {
15457                    childRes.newUsers = childPs.queryInstalledUsers(
15458                            sUserManager.getUserIds(), true);
15459                }
15460            }
15461        }
15462    }
15463
15464    private void startIntentFilterVerifications(int userId, boolean replacing,
15465            PackageParser.Package pkg) {
15466        if (mIntentFilterVerifierComponent == null) {
15467            Slog.w(TAG, "No IntentFilter verification will not be done as "
15468                    + "there is no IntentFilterVerifier available!");
15469            return;
15470        }
15471
15472        final int verifierUid = getPackageUid(
15473                mIntentFilterVerifierComponent.getPackageName(),
15474                MATCH_DEBUG_TRIAGED_MISSING,
15475                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15476
15477        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15478        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15479        mHandler.sendMessage(msg);
15480
15481        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15482        for (int i = 0; i < childCount; i++) {
15483            PackageParser.Package childPkg = pkg.childPackages.get(i);
15484            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15485            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15486            mHandler.sendMessage(msg);
15487        }
15488    }
15489
15490    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15491            PackageParser.Package pkg) {
15492        int size = pkg.activities.size();
15493        if (size == 0) {
15494            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15495                    "No activity, so no need to verify any IntentFilter!");
15496            return;
15497        }
15498
15499        final boolean hasDomainURLs = hasDomainURLs(pkg);
15500        if (!hasDomainURLs) {
15501            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15502                    "No domain URLs, so no need to verify any IntentFilter!");
15503            return;
15504        }
15505
15506        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15507                + " if any IntentFilter from the " + size
15508                + " Activities needs verification ...");
15509
15510        int count = 0;
15511        final String packageName = pkg.packageName;
15512
15513        synchronized (mPackages) {
15514            // If this is a new install and we see that we've already run verification for this
15515            // package, we have nothing to do: it means the state was restored from backup.
15516            if (!replacing) {
15517                IntentFilterVerificationInfo ivi =
15518                        mSettings.getIntentFilterVerificationLPr(packageName);
15519                if (ivi != null) {
15520                    if (DEBUG_DOMAIN_VERIFICATION) {
15521                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15522                                + ivi.getStatusString());
15523                    }
15524                    return;
15525                }
15526            }
15527
15528            // If any filters need to be verified, then all need to be.
15529            boolean needToVerify = false;
15530            for (PackageParser.Activity a : pkg.activities) {
15531                for (ActivityIntentInfo filter : a.intents) {
15532                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15533                        if (DEBUG_DOMAIN_VERIFICATION) {
15534                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15535                        }
15536                        needToVerify = true;
15537                        break;
15538                    }
15539                }
15540            }
15541
15542            if (needToVerify) {
15543                final int verificationId = mIntentFilterVerificationToken++;
15544                for (PackageParser.Activity a : pkg.activities) {
15545                    for (ActivityIntentInfo filter : a.intents) {
15546                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15547                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15548                                    "Verification needed for IntentFilter:" + filter.toString());
15549                            mIntentFilterVerifier.addOneIntentFilterVerification(
15550                                    verifierUid, userId, verificationId, filter, packageName);
15551                            count++;
15552                        }
15553                    }
15554                }
15555            }
15556        }
15557
15558        if (count > 0) {
15559            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15560                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15561                    +  " for userId:" + userId);
15562            mIntentFilterVerifier.startVerifications(userId);
15563        } else {
15564            if (DEBUG_DOMAIN_VERIFICATION) {
15565                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15566            }
15567        }
15568    }
15569
15570    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15571        final ComponentName cn  = filter.activity.getComponentName();
15572        final String packageName = cn.getPackageName();
15573
15574        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15575                packageName);
15576        if (ivi == null) {
15577            return true;
15578        }
15579        int status = ivi.getStatus();
15580        switch (status) {
15581            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15582            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15583                return true;
15584
15585            default:
15586                // Nothing to do
15587                return false;
15588        }
15589    }
15590
15591    private static boolean isMultiArch(ApplicationInfo info) {
15592        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15593    }
15594
15595    private static boolean isExternal(PackageParser.Package pkg) {
15596        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15597    }
15598
15599    private static boolean isExternal(PackageSetting ps) {
15600        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15601    }
15602
15603    private static boolean isEphemeral(PackageParser.Package pkg) {
15604        return pkg.applicationInfo.isEphemeralApp();
15605    }
15606
15607    private static boolean isEphemeral(PackageSetting ps) {
15608        return ps.pkg != null && isEphemeral(ps.pkg);
15609    }
15610
15611    private static boolean isSystemApp(PackageParser.Package pkg) {
15612        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15613    }
15614
15615    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15616        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15617    }
15618
15619    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15620        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15621    }
15622
15623    private static boolean isSystemApp(PackageSetting ps) {
15624        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15625    }
15626
15627    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15628        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15629    }
15630
15631    private int packageFlagsToInstallFlags(PackageSetting ps) {
15632        int installFlags = 0;
15633        if (isEphemeral(ps)) {
15634            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15635        }
15636        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15637            // This existing package was an external ASEC install when we have
15638            // the external flag without a UUID
15639            installFlags |= PackageManager.INSTALL_EXTERNAL;
15640        }
15641        if (ps.isForwardLocked()) {
15642            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15643        }
15644        return installFlags;
15645    }
15646
15647    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15648        if (isExternal(pkg)) {
15649            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15650                return StorageManager.UUID_PRIMARY_PHYSICAL;
15651            } else {
15652                return pkg.volumeUuid;
15653            }
15654        } else {
15655            return StorageManager.UUID_PRIVATE_INTERNAL;
15656        }
15657    }
15658
15659    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15660        if (isExternal(pkg)) {
15661            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15662                return mSettings.getExternalVersion();
15663            } else {
15664                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15665            }
15666        } else {
15667            return mSettings.getInternalVersion();
15668        }
15669    }
15670
15671    private void deleteTempPackageFiles() {
15672        final FilenameFilter filter = new FilenameFilter() {
15673            public boolean accept(File dir, String name) {
15674                return name.startsWith("vmdl") && name.endsWith(".tmp");
15675            }
15676        };
15677        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15678            file.delete();
15679        }
15680    }
15681
15682    @Override
15683    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15684            int flags) {
15685        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15686                flags);
15687    }
15688
15689    @Override
15690    public void deletePackage(final String packageName,
15691            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15692        mContext.enforceCallingOrSelfPermission(
15693                android.Manifest.permission.DELETE_PACKAGES, null);
15694        Preconditions.checkNotNull(packageName);
15695        Preconditions.checkNotNull(observer);
15696        final int uid = Binder.getCallingUid();
15697        if (!isOrphaned(packageName)
15698                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15699            try {
15700                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15701                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15702                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15703                observer.onUserActionRequired(intent);
15704            } catch (RemoteException re) {
15705            }
15706            return;
15707        }
15708        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15709        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15710        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15711            mContext.enforceCallingOrSelfPermission(
15712                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15713                    "deletePackage for user " + userId);
15714        }
15715
15716        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15717            try {
15718                observer.onPackageDeleted(packageName,
15719                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15720            } catch (RemoteException re) {
15721            }
15722            return;
15723        }
15724
15725        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15726            try {
15727                observer.onPackageDeleted(packageName,
15728                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15729            } catch (RemoteException re) {
15730            }
15731            return;
15732        }
15733
15734        if (DEBUG_REMOVE) {
15735            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15736                    + " deleteAllUsers: " + deleteAllUsers );
15737        }
15738        // Queue up an async operation since the package deletion may take a little while.
15739        mHandler.post(new Runnable() {
15740            public void run() {
15741                mHandler.removeCallbacks(this);
15742                int returnCode;
15743                if (!deleteAllUsers) {
15744                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15745                } else {
15746                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15747                    // If nobody is blocking uninstall, proceed with delete for all users
15748                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15749                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15750                    } else {
15751                        // Otherwise uninstall individually for users with blockUninstalls=false
15752                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15753                        for (int userId : users) {
15754                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15755                                returnCode = deletePackageX(packageName, userId, userFlags);
15756                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15757                                    Slog.w(TAG, "Package delete failed for user " + userId
15758                                            + ", returnCode " + returnCode);
15759                                }
15760                            }
15761                        }
15762                        // The app has only been marked uninstalled for certain users.
15763                        // We still need to report that delete was blocked
15764                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15765                    }
15766                }
15767                try {
15768                    observer.onPackageDeleted(packageName, returnCode, null);
15769                } catch (RemoteException e) {
15770                    Log.i(TAG, "Observer no longer exists.");
15771                } //end catch
15772            } //end run
15773        });
15774    }
15775
15776    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15777        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15778              || callingUid == Process.SYSTEM_UID) {
15779            return true;
15780        }
15781        final int callingUserId = UserHandle.getUserId(callingUid);
15782        // If the caller installed the pkgName, then allow it to silently uninstall.
15783        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15784            return true;
15785        }
15786
15787        // Allow package verifier to silently uninstall.
15788        if (mRequiredVerifierPackage != null &&
15789                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15790            return true;
15791        }
15792
15793        // Allow package uninstaller to silently uninstall.
15794        if (mRequiredUninstallerPackage != null &&
15795                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15796            return true;
15797        }
15798
15799        // Allow storage manager to silently uninstall.
15800        if (mStorageManagerPackage != null &&
15801                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15802            return true;
15803        }
15804        return false;
15805    }
15806
15807    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15808        int[] result = EMPTY_INT_ARRAY;
15809        for (int userId : userIds) {
15810            if (getBlockUninstallForUser(packageName, userId)) {
15811                result = ArrayUtils.appendInt(result, userId);
15812            }
15813        }
15814        return result;
15815    }
15816
15817    @Override
15818    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15819        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15820    }
15821
15822    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15823        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15824                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15825        try {
15826            if (dpm != null) {
15827                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15828                        /* callingUserOnly =*/ false);
15829                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15830                        : deviceOwnerComponentName.getPackageName();
15831                // Does the package contains the device owner?
15832                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15833                // this check is probably not needed, since DO should be registered as a device
15834                // admin on some user too. (Original bug for this: b/17657954)
15835                if (packageName.equals(deviceOwnerPackageName)) {
15836                    return true;
15837                }
15838                // Does it contain a device admin for any user?
15839                int[] users;
15840                if (userId == UserHandle.USER_ALL) {
15841                    users = sUserManager.getUserIds();
15842                } else {
15843                    users = new int[]{userId};
15844                }
15845                for (int i = 0; i < users.length; ++i) {
15846                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15847                        return true;
15848                    }
15849                }
15850            }
15851        } catch (RemoteException e) {
15852        }
15853        return false;
15854    }
15855
15856    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15857        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15858    }
15859
15860    /**
15861     *  This method is an internal method that could be get invoked either
15862     *  to delete an installed package or to clean up a failed installation.
15863     *  After deleting an installed package, a broadcast is sent to notify any
15864     *  listeners that the package has been removed. For cleaning up a failed
15865     *  installation, the broadcast is not necessary since the package's
15866     *  installation wouldn't have sent the initial broadcast either
15867     *  The key steps in deleting a package are
15868     *  deleting the package information in internal structures like mPackages,
15869     *  deleting the packages base directories through installd
15870     *  updating mSettings to reflect current status
15871     *  persisting settings for later use
15872     *  sending a broadcast if necessary
15873     */
15874    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15875        final PackageRemovedInfo info = new PackageRemovedInfo();
15876        final boolean res;
15877
15878        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15879                ? UserHandle.USER_ALL : userId;
15880
15881        if (isPackageDeviceAdmin(packageName, removeUser)) {
15882            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15883            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15884        }
15885
15886        PackageSetting uninstalledPs = null;
15887
15888        // for the uninstall-updates case and restricted profiles, remember the per-
15889        // user handle installed state
15890        int[] allUsers;
15891        synchronized (mPackages) {
15892            uninstalledPs = mSettings.mPackages.get(packageName);
15893            if (uninstalledPs == null) {
15894                Slog.w(TAG, "Not removing non-existent package " + packageName);
15895                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15896            }
15897            allUsers = sUserManager.getUserIds();
15898            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15899        }
15900
15901        final int freezeUser;
15902        if (isUpdatedSystemApp(uninstalledPs)
15903                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15904            // We're downgrading a system app, which will apply to all users, so
15905            // freeze them all during the downgrade
15906            freezeUser = UserHandle.USER_ALL;
15907        } else {
15908            freezeUser = removeUser;
15909        }
15910
15911        synchronized (mInstallLock) {
15912            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15913            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15914                    deleteFlags, "deletePackageX")) {
15915                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15916                        deleteFlags | REMOVE_CHATTY, info, true, null);
15917            }
15918            synchronized (mPackages) {
15919                if (res) {
15920                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15921                }
15922            }
15923        }
15924
15925        if (res) {
15926            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15927            info.sendPackageRemovedBroadcasts(killApp);
15928            info.sendSystemPackageUpdatedBroadcasts();
15929            info.sendSystemPackageAppearedBroadcasts();
15930        }
15931        // Force a gc here.
15932        Runtime.getRuntime().gc();
15933        // Delete the resources here after sending the broadcast to let
15934        // other processes clean up before deleting resources.
15935        if (info.args != null) {
15936            synchronized (mInstallLock) {
15937                info.args.doPostDeleteLI(true);
15938            }
15939        }
15940
15941        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15942    }
15943
15944    class PackageRemovedInfo {
15945        String removedPackage;
15946        int uid = -1;
15947        int removedAppId = -1;
15948        int[] origUsers;
15949        int[] removedUsers = null;
15950        boolean isRemovedPackageSystemUpdate = false;
15951        boolean isUpdate;
15952        boolean dataRemoved;
15953        boolean removedForAllUsers;
15954        // Clean up resources deleted packages.
15955        InstallArgs args = null;
15956        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15957        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15958
15959        void sendPackageRemovedBroadcasts(boolean killApp) {
15960            sendPackageRemovedBroadcastInternal(killApp);
15961            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15962            for (int i = 0; i < childCount; i++) {
15963                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15964                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15965            }
15966        }
15967
15968        void sendSystemPackageUpdatedBroadcasts() {
15969            if (isRemovedPackageSystemUpdate) {
15970                sendSystemPackageUpdatedBroadcastsInternal();
15971                final int childCount = (removedChildPackages != null)
15972                        ? removedChildPackages.size() : 0;
15973                for (int i = 0; i < childCount; i++) {
15974                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15975                    if (childInfo.isRemovedPackageSystemUpdate) {
15976                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15977                    }
15978                }
15979            }
15980        }
15981
15982        void sendSystemPackageAppearedBroadcasts() {
15983            final int packageCount = (appearedChildPackages != null)
15984                    ? appearedChildPackages.size() : 0;
15985            for (int i = 0; i < packageCount; i++) {
15986                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15987                sendPackageAddedForNewUsers(installedInfo.name, true,
15988                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
15989            }
15990        }
15991
15992        private void sendSystemPackageUpdatedBroadcastsInternal() {
15993            Bundle extras = new Bundle(2);
15994            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15995            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15996            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15997                    extras, 0, null, null, null);
15998            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15999                    extras, 0, null, null, null);
16000            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16001                    null, 0, removedPackage, null, null);
16002        }
16003
16004        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16005            Bundle extras = new Bundle(2);
16006            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16007            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16008            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16009            if (isUpdate || isRemovedPackageSystemUpdate) {
16010                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16011            }
16012            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16013            if (removedPackage != null) {
16014                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16015                        extras, 0, null, null, removedUsers);
16016                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16017                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16018                            removedPackage, extras, 0, null, null, removedUsers);
16019                }
16020            }
16021            if (removedAppId >= 0) {
16022                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16023                        removedUsers);
16024            }
16025        }
16026    }
16027
16028    /*
16029     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16030     * flag is not set, the data directory is removed as well.
16031     * make sure this flag is set for partially installed apps. If not its meaningless to
16032     * delete a partially installed application.
16033     */
16034    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16035            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16036        String packageName = ps.name;
16037        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16038        // Retrieve object to delete permissions for shared user later on
16039        final PackageParser.Package deletedPkg;
16040        final PackageSetting deletedPs;
16041        // reader
16042        synchronized (mPackages) {
16043            deletedPkg = mPackages.get(packageName);
16044            deletedPs = mSettings.mPackages.get(packageName);
16045            if (outInfo != null) {
16046                outInfo.removedPackage = packageName;
16047                outInfo.removedUsers = deletedPs != null
16048                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16049                        : null;
16050            }
16051        }
16052
16053        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16054
16055        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16056            final PackageParser.Package resolvedPkg;
16057            if (deletedPkg != null) {
16058                resolvedPkg = deletedPkg;
16059            } else {
16060                // We don't have a parsed package when it lives on an ejected
16061                // adopted storage device, so fake something together
16062                resolvedPkg = new PackageParser.Package(ps.name);
16063                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16064            }
16065            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16066                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16067            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16068            if (outInfo != null) {
16069                outInfo.dataRemoved = true;
16070            }
16071            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16072        }
16073
16074        // writer
16075        synchronized (mPackages) {
16076            if (deletedPs != null) {
16077                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16078                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16079                    clearDefaultBrowserIfNeeded(packageName);
16080                    if (outInfo != null) {
16081                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16082                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16083                    }
16084                    updatePermissionsLPw(deletedPs.name, null, 0);
16085                    if (deletedPs.sharedUser != null) {
16086                        // Remove permissions associated with package. Since runtime
16087                        // permissions are per user we have to kill the removed package
16088                        // or packages running under the shared user of the removed
16089                        // package if revoking the permissions requested only by the removed
16090                        // package is successful and this causes a change in gids.
16091                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16092                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16093                                    userId);
16094                            if (userIdToKill == UserHandle.USER_ALL
16095                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16096                                // If gids changed for this user, kill all affected packages.
16097                                mHandler.post(new Runnable() {
16098                                    @Override
16099                                    public void run() {
16100                                        // This has to happen with no lock held.
16101                                        killApplication(deletedPs.name, deletedPs.appId,
16102                                                KILL_APP_REASON_GIDS_CHANGED);
16103                                    }
16104                                });
16105                                break;
16106                            }
16107                        }
16108                    }
16109                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16110                }
16111                // make sure to preserve per-user disabled state if this removal was just
16112                // a downgrade of a system app to the factory package
16113                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16114                    if (DEBUG_REMOVE) {
16115                        Slog.d(TAG, "Propagating install state across downgrade");
16116                    }
16117                    for (int userId : allUserHandles) {
16118                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16119                        if (DEBUG_REMOVE) {
16120                            Slog.d(TAG, "    user " + userId + " => " + installed);
16121                        }
16122                        ps.setInstalled(installed, userId);
16123                    }
16124                }
16125            }
16126            // can downgrade to reader
16127            if (writeSettings) {
16128                // Save settings now
16129                mSettings.writeLPr();
16130            }
16131        }
16132        if (outInfo != null) {
16133            // A user ID was deleted here. Go through all users and remove it
16134            // from KeyStore.
16135            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16136        }
16137    }
16138
16139    static boolean locationIsPrivileged(File path) {
16140        try {
16141            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16142                    .getCanonicalPath();
16143            return path.getCanonicalPath().startsWith(privilegedAppDir);
16144        } catch (IOException e) {
16145            Slog.e(TAG, "Unable to access code path " + path);
16146        }
16147        return false;
16148    }
16149
16150    /*
16151     * Tries to delete system package.
16152     */
16153    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16154            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16155            boolean writeSettings) {
16156        if (deletedPs.parentPackageName != null) {
16157            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16158            return false;
16159        }
16160
16161        final boolean applyUserRestrictions
16162                = (allUserHandles != null) && (outInfo.origUsers != null);
16163        final PackageSetting disabledPs;
16164        // Confirm if the system package has been updated
16165        // An updated system app can be deleted. This will also have to restore
16166        // the system pkg from system partition
16167        // reader
16168        synchronized (mPackages) {
16169            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16170        }
16171
16172        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16173                + " disabledPs=" + disabledPs);
16174
16175        if (disabledPs == null) {
16176            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16177            return false;
16178        } else if (DEBUG_REMOVE) {
16179            Slog.d(TAG, "Deleting system pkg from data partition");
16180        }
16181
16182        if (DEBUG_REMOVE) {
16183            if (applyUserRestrictions) {
16184                Slog.d(TAG, "Remembering install states:");
16185                for (int userId : allUserHandles) {
16186                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16187                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16188                }
16189            }
16190        }
16191
16192        // Delete the updated package
16193        outInfo.isRemovedPackageSystemUpdate = true;
16194        if (outInfo.removedChildPackages != null) {
16195            final int childCount = (deletedPs.childPackageNames != null)
16196                    ? deletedPs.childPackageNames.size() : 0;
16197            for (int i = 0; i < childCount; i++) {
16198                String childPackageName = deletedPs.childPackageNames.get(i);
16199                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16200                        .contains(childPackageName)) {
16201                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16202                            childPackageName);
16203                    if (childInfo != null) {
16204                        childInfo.isRemovedPackageSystemUpdate = true;
16205                    }
16206                }
16207            }
16208        }
16209
16210        if (disabledPs.versionCode < deletedPs.versionCode) {
16211            // Delete data for downgrades
16212            flags &= ~PackageManager.DELETE_KEEP_DATA;
16213        } else {
16214            // Preserve data by setting flag
16215            flags |= PackageManager.DELETE_KEEP_DATA;
16216        }
16217
16218        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16219                outInfo, writeSettings, disabledPs.pkg);
16220        if (!ret) {
16221            return false;
16222        }
16223
16224        // writer
16225        synchronized (mPackages) {
16226            // Reinstate the old system package
16227            enableSystemPackageLPw(disabledPs.pkg);
16228            // Remove any native libraries from the upgraded package.
16229            removeNativeBinariesLI(deletedPs);
16230        }
16231
16232        // Install the system package
16233        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16234        int parseFlags = mDefParseFlags
16235                | PackageParser.PARSE_MUST_BE_APK
16236                | PackageParser.PARSE_IS_SYSTEM
16237                | PackageParser.PARSE_IS_SYSTEM_DIR;
16238        if (locationIsPrivileged(disabledPs.codePath)) {
16239            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16240        }
16241
16242        final PackageParser.Package newPkg;
16243        try {
16244            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16245        } catch (PackageManagerException e) {
16246            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16247                    + e.getMessage());
16248            return false;
16249        }
16250        try {
16251            // update shared libraries for the newly re-installed system package
16252            updateSharedLibrariesLPr(newPkg, null);
16253        } catch (PackageManagerException e) {
16254            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16255        }
16256
16257        prepareAppDataAfterInstallLIF(newPkg);
16258
16259        // writer
16260        synchronized (mPackages) {
16261            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16262
16263            // Propagate the permissions state as we do not want to drop on the floor
16264            // runtime permissions. The update permissions method below will take
16265            // care of removing obsolete permissions and grant install permissions.
16266            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16267            updatePermissionsLPw(newPkg.packageName, newPkg,
16268                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16269
16270            if (applyUserRestrictions) {
16271                if (DEBUG_REMOVE) {
16272                    Slog.d(TAG, "Propagating install state across reinstall");
16273                }
16274                for (int userId : allUserHandles) {
16275                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16276                    if (DEBUG_REMOVE) {
16277                        Slog.d(TAG, "    user " + userId + " => " + installed);
16278                    }
16279                    ps.setInstalled(installed, userId);
16280
16281                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16282                }
16283                // Regardless of writeSettings we need to ensure that this restriction
16284                // state propagation is persisted
16285                mSettings.writeAllUsersPackageRestrictionsLPr();
16286            }
16287            // can downgrade to reader here
16288            if (writeSettings) {
16289                mSettings.writeLPr();
16290            }
16291        }
16292        return true;
16293    }
16294
16295    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16296            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16297            PackageRemovedInfo outInfo, boolean writeSettings,
16298            PackageParser.Package replacingPackage) {
16299        synchronized (mPackages) {
16300            if (outInfo != null) {
16301                outInfo.uid = ps.appId;
16302            }
16303
16304            if (outInfo != null && outInfo.removedChildPackages != null) {
16305                final int childCount = (ps.childPackageNames != null)
16306                        ? ps.childPackageNames.size() : 0;
16307                for (int i = 0; i < childCount; i++) {
16308                    String childPackageName = ps.childPackageNames.get(i);
16309                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16310                    if (childPs == null) {
16311                        return false;
16312                    }
16313                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16314                            childPackageName);
16315                    if (childInfo != null) {
16316                        childInfo.uid = childPs.appId;
16317                    }
16318                }
16319            }
16320        }
16321
16322        // Delete package data from internal structures and also remove data if flag is set
16323        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16324
16325        // Delete the child packages data
16326        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16327        for (int i = 0; i < childCount; i++) {
16328            PackageSetting childPs;
16329            synchronized (mPackages) {
16330                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16331            }
16332            if (childPs != null) {
16333                PackageRemovedInfo childOutInfo = (outInfo != null
16334                        && outInfo.removedChildPackages != null)
16335                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16336                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16337                        && (replacingPackage != null
16338                        && !replacingPackage.hasChildPackage(childPs.name))
16339                        ? flags & ~DELETE_KEEP_DATA : flags;
16340                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16341                        deleteFlags, writeSettings);
16342            }
16343        }
16344
16345        // Delete application code and resources only for parent packages
16346        if (ps.parentPackageName == null) {
16347            if (deleteCodeAndResources && (outInfo != null)) {
16348                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16349                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16350                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16351            }
16352        }
16353
16354        return true;
16355    }
16356
16357    @Override
16358    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16359            int userId) {
16360        mContext.enforceCallingOrSelfPermission(
16361                android.Manifest.permission.DELETE_PACKAGES, null);
16362        synchronized (mPackages) {
16363            PackageSetting ps = mSettings.mPackages.get(packageName);
16364            if (ps == null) {
16365                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16366                return false;
16367            }
16368            if (!ps.getInstalled(userId)) {
16369                // Can't block uninstall for an app that is not installed or enabled.
16370                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16371                return false;
16372            }
16373            ps.setBlockUninstall(blockUninstall, userId);
16374            mSettings.writePackageRestrictionsLPr(userId);
16375        }
16376        return true;
16377    }
16378
16379    @Override
16380    public boolean getBlockUninstallForUser(String packageName, int userId) {
16381        synchronized (mPackages) {
16382            PackageSetting ps = mSettings.mPackages.get(packageName);
16383            if (ps == null) {
16384                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16385                return false;
16386            }
16387            return ps.getBlockUninstall(userId);
16388        }
16389    }
16390
16391    @Override
16392    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16393        int callingUid = Binder.getCallingUid();
16394        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16395            throw new SecurityException(
16396                    "setRequiredForSystemUser can only be run by the system or root");
16397        }
16398        synchronized (mPackages) {
16399            PackageSetting ps = mSettings.mPackages.get(packageName);
16400            if (ps == null) {
16401                Log.w(TAG, "Package doesn't exist: " + packageName);
16402                return false;
16403            }
16404            if (systemUserApp) {
16405                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16406            } else {
16407                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16408            }
16409            mSettings.writeLPr();
16410        }
16411        return true;
16412    }
16413
16414    /*
16415     * This method handles package deletion in general
16416     */
16417    private boolean deletePackageLIF(String packageName, UserHandle user,
16418            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16419            PackageRemovedInfo outInfo, boolean writeSettings,
16420            PackageParser.Package replacingPackage) {
16421        if (packageName == null) {
16422            Slog.w(TAG, "Attempt to delete null packageName.");
16423            return false;
16424        }
16425
16426        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16427
16428        PackageSetting ps;
16429
16430        synchronized (mPackages) {
16431            ps = mSettings.mPackages.get(packageName);
16432            if (ps == null) {
16433                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16434                return false;
16435            }
16436
16437            if (ps.parentPackageName != null && (!isSystemApp(ps)
16438                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16439                if (DEBUG_REMOVE) {
16440                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16441                            + ((user == null) ? UserHandle.USER_ALL : user));
16442                }
16443                final int removedUserId = (user != null) ? user.getIdentifier()
16444                        : UserHandle.USER_ALL;
16445                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16446                    return false;
16447                }
16448                markPackageUninstalledForUserLPw(ps, user);
16449                scheduleWritePackageRestrictionsLocked(user);
16450                return true;
16451            }
16452        }
16453
16454        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16455                && user.getIdentifier() != UserHandle.USER_ALL)) {
16456            // The caller is asking that the package only be deleted for a single
16457            // user.  To do this, we just mark its uninstalled state and delete
16458            // its data. If this is a system app, we only allow this to happen if
16459            // they have set the special DELETE_SYSTEM_APP which requests different
16460            // semantics than normal for uninstalling system apps.
16461            markPackageUninstalledForUserLPw(ps, user);
16462
16463            if (!isSystemApp(ps)) {
16464                // Do not uninstall the APK if an app should be cached
16465                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16466                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16467                    // Other user still have this package installed, so all
16468                    // we need to do is clear this user's data and save that
16469                    // it is uninstalled.
16470                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16471                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16472                        return false;
16473                    }
16474                    scheduleWritePackageRestrictionsLocked(user);
16475                    return true;
16476                } else {
16477                    // We need to set it back to 'installed' so the uninstall
16478                    // broadcasts will be sent correctly.
16479                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16480                    ps.setInstalled(true, user.getIdentifier());
16481                }
16482            } else {
16483                // This is a system app, so we assume that the
16484                // other users still have this package installed, so all
16485                // we need to do is clear this user's data and save that
16486                // it is uninstalled.
16487                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16488                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16489                    return false;
16490                }
16491                scheduleWritePackageRestrictionsLocked(user);
16492                return true;
16493            }
16494        }
16495
16496        // If we are deleting a composite package for all users, keep track
16497        // of result for each child.
16498        if (ps.childPackageNames != null && outInfo != null) {
16499            synchronized (mPackages) {
16500                final int childCount = ps.childPackageNames.size();
16501                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16502                for (int i = 0; i < childCount; i++) {
16503                    String childPackageName = ps.childPackageNames.get(i);
16504                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16505                    childInfo.removedPackage = childPackageName;
16506                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16507                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16508                    if (childPs != null) {
16509                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16510                    }
16511                }
16512            }
16513        }
16514
16515        boolean ret = false;
16516        if (isSystemApp(ps)) {
16517            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16518            // When an updated system application is deleted we delete the existing resources
16519            // as well and fall back to existing code in system partition
16520            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16521        } else {
16522            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16523            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16524                    outInfo, writeSettings, replacingPackage);
16525        }
16526
16527        // Take a note whether we deleted the package for all users
16528        if (outInfo != null) {
16529            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16530            if (outInfo.removedChildPackages != null) {
16531                synchronized (mPackages) {
16532                    final int childCount = outInfo.removedChildPackages.size();
16533                    for (int i = 0; i < childCount; i++) {
16534                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16535                        if (childInfo != null) {
16536                            childInfo.removedForAllUsers = mPackages.get(
16537                                    childInfo.removedPackage) == null;
16538                        }
16539                    }
16540                }
16541            }
16542            // If we uninstalled an update to a system app there may be some
16543            // child packages that appeared as they are declared in the system
16544            // app but were not declared in the update.
16545            if (isSystemApp(ps)) {
16546                synchronized (mPackages) {
16547                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16548                    final int childCount = (updatedPs.childPackageNames != null)
16549                            ? updatedPs.childPackageNames.size() : 0;
16550                    for (int i = 0; i < childCount; i++) {
16551                        String childPackageName = updatedPs.childPackageNames.get(i);
16552                        if (outInfo.removedChildPackages == null
16553                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16554                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16555                            if (childPs == null) {
16556                                continue;
16557                            }
16558                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16559                            installRes.name = childPackageName;
16560                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16561                            installRes.pkg = mPackages.get(childPackageName);
16562                            installRes.uid = childPs.pkg.applicationInfo.uid;
16563                            if (outInfo.appearedChildPackages == null) {
16564                                outInfo.appearedChildPackages = new ArrayMap<>();
16565                            }
16566                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16567                        }
16568                    }
16569                }
16570            }
16571        }
16572
16573        return ret;
16574    }
16575
16576    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16577        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16578                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16579        for (int nextUserId : userIds) {
16580            if (DEBUG_REMOVE) {
16581                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16582            }
16583            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16584                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16585                    false /*hidden*/, false /*suspended*/, null, null, null,
16586                    false /*blockUninstall*/,
16587                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16588        }
16589    }
16590
16591    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16592            PackageRemovedInfo outInfo) {
16593        final PackageParser.Package pkg;
16594        synchronized (mPackages) {
16595            pkg = mPackages.get(ps.name);
16596        }
16597
16598        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16599                : new int[] {userId};
16600        for (int nextUserId : userIds) {
16601            if (DEBUG_REMOVE) {
16602                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16603                        + nextUserId);
16604            }
16605
16606            destroyAppDataLIF(pkg, userId,
16607                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16608            destroyAppProfilesLIF(pkg, userId);
16609            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16610            schedulePackageCleaning(ps.name, nextUserId, false);
16611            synchronized (mPackages) {
16612                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16613                    scheduleWritePackageRestrictionsLocked(nextUserId);
16614                }
16615                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16616            }
16617        }
16618
16619        if (outInfo != null) {
16620            outInfo.removedPackage = ps.name;
16621            outInfo.removedAppId = ps.appId;
16622            outInfo.removedUsers = userIds;
16623        }
16624
16625        return true;
16626    }
16627
16628    private final class ClearStorageConnection implements ServiceConnection {
16629        IMediaContainerService mContainerService;
16630
16631        @Override
16632        public void onServiceConnected(ComponentName name, IBinder service) {
16633            synchronized (this) {
16634                mContainerService = IMediaContainerService.Stub
16635                        .asInterface(Binder.allowBlocking(service));
16636                notifyAll();
16637            }
16638        }
16639
16640        @Override
16641        public void onServiceDisconnected(ComponentName name) {
16642        }
16643    }
16644
16645    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16646        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16647
16648        final boolean mounted;
16649        if (Environment.isExternalStorageEmulated()) {
16650            mounted = true;
16651        } else {
16652            final String status = Environment.getExternalStorageState();
16653
16654            mounted = status.equals(Environment.MEDIA_MOUNTED)
16655                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16656        }
16657
16658        if (!mounted) {
16659            return;
16660        }
16661
16662        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16663        int[] users;
16664        if (userId == UserHandle.USER_ALL) {
16665            users = sUserManager.getUserIds();
16666        } else {
16667            users = new int[] { userId };
16668        }
16669        final ClearStorageConnection conn = new ClearStorageConnection();
16670        if (mContext.bindServiceAsUser(
16671                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16672            try {
16673                for (int curUser : users) {
16674                    long timeout = SystemClock.uptimeMillis() + 5000;
16675                    synchronized (conn) {
16676                        long now;
16677                        while (conn.mContainerService == null &&
16678                                (now = SystemClock.uptimeMillis()) < timeout) {
16679                            try {
16680                                conn.wait(timeout - now);
16681                            } catch (InterruptedException e) {
16682                            }
16683                        }
16684                    }
16685                    if (conn.mContainerService == null) {
16686                        return;
16687                    }
16688
16689                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16690                    clearDirectory(conn.mContainerService,
16691                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16692                    if (allData) {
16693                        clearDirectory(conn.mContainerService,
16694                                userEnv.buildExternalStorageAppDataDirs(packageName));
16695                        clearDirectory(conn.mContainerService,
16696                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16697                    }
16698                }
16699            } finally {
16700                mContext.unbindService(conn);
16701            }
16702        }
16703    }
16704
16705    @Override
16706    public void clearApplicationProfileData(String packageName) {
16707        enforceSystemOrRoot("Only the system can clear all profile data");
16708
16709        final PackageParser.Package pkg;
16710        synchronized (mPackages) {
16711            pkg = mPackages.get(packageName);
16712        }
16713
16714        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16715            synchronized (mInstallLock) {
16716                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16717                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16718                        true /* removeBaseMarker */);
16719            }
16720        }
16721    }
16722
16723    @Override
16724    public void clearApplicationUserData(final String packageName,
16725            final IPackageDataObserver observer, final int userId) {
16726        mContext.enforceCallingOrSelfPermission(
16727                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16728
16729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16730                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16731
16732        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16733            throw new SecurityException("Cannot clear data for a protected package: "
16734                    + packageName);
16735        }
16736        // Queue up an async operation since the package deletion may take a little while.
16737        mHandler.post(new Runnable() {
16738            public void run() {
16739                mHandler.removeCallbacks(this);
16740                final boolean succeeded;
16741                try (PackageFreezer freezer = freezePackage(packageName,
16742                        "clearApplicationUserData")) {
16743                    synchronized (mInstallLock) {
16744                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16745                    }
16746                    clearExternalStorageDataSync(packageName, userId, true);
16747                }
16748                if (succeeded) {
16749                    // invoke DeviceStorageMonitor's update method to clear any notifications
16750                    DeviceStorageMonitorInternal dsm = LocalServices
16751                            .getService(DeviceStorageMonitorInternal.class);
16752                    if (dsm != null) {
16753                        dsm.checkMemory();
16754                    }
16755                }
16756                if(observer != null) {
16757                    try {
16758                        observer.onRemoveCompleted(packageName, succeeded);
16759                    } catch (RemoteException e) {
16760                        Log.i(TAG, "Observer no longer exists.");
16761                    }
16762                } //end if observer
16763            } //end run
16764        });
16765    }
16766
16767    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16768        if (packageName == null) {
16769            Slog.w(TAG, "Attempt to delete null packageName.");
16770            return false;
16771        }
16772
16773        // Try finding details about the requested package
16774        PackageParser.Package pkg;
16775        synchronized (mPackages) {
16776            pkg = mPackages.get(packageName);
16777            if (pkg == null) {
16778                final PackageSetting ps = mSettings.mPackages.get(packageName);
16779                if (ps != null) {
16780                    pkg = ps.pkg;
16781                }
16782            }
16783
16784            if (pkg == null) {
16785                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16786                return false;
16787            }
16788
16789            PackageSetting ps = (PackageSetting) pkg.mExtras;
16790            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16791        }
16792
16793        clearAppDataLIF(pkg, userId,
16794                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16795
16796        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16797        removeKeystoreDataIfNeeded(userId, appId);
16798
16799        UserManagerInternal umInternal = getUserManagerInternal();
16800        final int flags;
16801        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16802            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16803        } else if (umInternal.isUserRunning(userId)) {
16804            flags = StorageManager.FLAG_STORAGE_DE;
16805        } else {
16806            flags = 0;
16807        }
16808        prepareAppDataContentsLIF(pkg, userId, flags);
16809
16810        return true;
16811    }
16812
16813    /**
16814     * Reverts user permission state changes (permissions and flags) in
16815     * all packages for a given user.
16816     *
16817     * @param userId The device user for which to do a reset.
16818     */
16819    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16820        final int packageCount = mPackages.size();
16821        for (int i = 0; i < packageCount; i++) {
16822            PackageParser.Package pkg = mPackages.valueAt(i);
16823            PackageSetting ps = (PackageSetting) pkg.mExtras;
16824            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16825        }
16826    }
16827
16828    private void resetNetworkPolicies(int userId) {
16829        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16830    }
16831
16832    /**
16833     * Reverts user permission state changes (permissions and flags).
16834     *
16835     * @param ps The package for which to reset.
16836     * @param userId The device user for which to do a reset.
16837     */
16838    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16839            final PackageSetting ps, final int userId) {
16840        if (ps.pkg == null) {
16841            return;
16842        }
16843
16844        // These are flags that can change base on user actions.
16845        final int userSettableMask = FLAG_PERMISSION_USER_SET
16846                | FLAG_PERMISSION_USER_FIXED
16847                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16848                | FLAG_PERMISSION_REVIEW_REQUIRED;
16849
16850        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16851                | FLAG_PERMISSION_POLICY_FIXED;
16852
16853        boolean writeInstallPermissions = false;
16854        boolean writeRuntimePermissions = false;
16855
16856        final int permissionCount = ps.pkg.requestedPermissions.size();
16857        for (int i = 0; i < permissionCount; i++) {
16858            String permission = ps.pkg.requestedPermissions.get(i);
16859
16860            BasePermission bp = mSettings.mPermissions.get(permission);
16861            if (bp == null) {
16862                continue;
16863            }
16864
16865            // If shared user we just reset the state to which only this app contributed.
16866            if (ps.sharedUser != null) {
16867                boolean used = false;
16868                final int packageCount = ps.sharedUser.packages.size();
16869                for (int j = 0; j < packageCount; j++) {
16870                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16871                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16872                            && pkg.pkg.requestedPermissions.contains(permission)) {
16873                        used = true;
16874                        break;
16875                    }
16876                }
16877                if (used) {
16878                    continue;
16879                }
16880            }
16881
16882            PermissionsState permissionsState = ps.getPermissionsState();
16883
16884            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16885
16886            // Always clear the user settable flags.
16887            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16888                    bp.name) != null;
16889            // If permission review is enabled and this is a legacy app, mark the
16890            // permission as requiring a review as this is the initial state.
16891            int flags = 0;
16892            if (mPermissionReviewRequired
16893                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16894                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16895            }
16896            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16897                if (hasInstallState) {
16898                    writeInstallPermissions = true;
16899                } else {
16900                    writeRuntimePermissions = true;
16901                }
16902            }
16903
16904            // Below is only runtime permission handling.
16905            if (!bp.isRuntime()) {
16906                continue;
16907            }
16908
16909            // Never clobber system or policy.
16910            if ((oldFlags & policyOrSystemFlags) != 0) {
16911                continue;
16912            }
16913
16914            // If this permission was granted by default, make sure it is.
16915            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16916                if (permissionsState.grantRuntimePermission(bp, userId)
16917                        != PERMISSION_OPERATION_FAILURE) {
16918                    writeRuntimePermissions = true;
16919                }
16920            // If permission review is enabled the permissions for a legacy apps
16921            // are represented as constantly granted runtime ones, so don't revoke.
16922            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16923                // Otherwise, reset the permission.
16924                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16925                switch (revokeResult) {
16926                    case PERMISSION_OPERATION_SUCCESS:
16927                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16928                        writeRuntimePermissions = true;
16929                        final int appId = ps.appId;
16930                        mHandler.post(new Runnable() {
16931                            @Override
16932                            public void run() {
16933                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16934                            }
16935                        });
16936                    } break;
16937                }
16938            }
16939        }
16940
16941        // Synchronously write as we are taking permissions away.
16942        if (writeRuntimePermissions) {
16943            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16944        }
16945
16946        // Synchronously write as we are taking permissions away.
16947        if (writeInstallPermissions) {
16948            mSettings.writeLPr();
16949        }
16950    }
16951
16952    /**
16953     * Remove entries from the keystore daemon. Will only remove it if the
16954     * {@code appId} is valid.
16955     */
16956    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16957        if (appId < 0) {
16958            return;
16959        }
16960
16961        final KeyStore keyStore = KeyStore.getInstance();
16962        if (keyStore != null) {
16963            if (userId == UserHandle.USER_ALL) {
16964                for (final int individual : sUserManager.getUserIds()) {
16965                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16966                }
16967            } else {
16968                keyStore.clearUid(UserHandle.getUid(userId, appId));
16969            }
16970        } else {
16971            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16972        }
16973    }
16974
16975    @Override
16976    public void deleteApplicationCacheFiles(final String packageName,
16977            final IPackageDataObserver observer) {
16978        final int userId = UserHandle.getCallingUserId();
16979        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16980    }
16981
16982    @Override
16983    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16984            final IPackageDataObserver observer) {
16985        mContext.enforceCallingOrSelfPermission(
16986                android.Manifest.permission.DELETE_CACHE_FILES, null);
16987        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16988                /* requireFullPermission= */ true, /* checkShell= */ false,
16989                "delete application cache files");
16990
16991        final PackageParser.Package pkg;
16992        synchronized (mPackages) {
16993            pkg = mPackages.get(packageName);
16994        }
16995
16996        // Queue up an async operation since the package deletion may take a little while.
16997        mHandler.post(new Runnable() {
16998            public void run() {
16999                synchronized (mInstallLock) {
17000                    final int flags = StorageManager.FLAG_STORAGE_DE
17001                            | StorageManager.FLAG_STORAGE_CE;
17002                    // We're only clearing cache files, so we don't care if the
17003                    // app is unfrozen and still able to run
17004                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17005                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17006                }
17007                clearExternalStorageDataSync(packageName, userId, false);
17008                if (observer != null) {
17009                    try {
17010                        observer.onRemoveCompleted(packageName, true);
17011                    } catch (RemoteException e) {
17012                        Log.i(TAG, "Observer no longer exists.");
17013                    }
17014                }
17015            }
17016        });
17017    }
17018
17019    @Override
17020    public void getPackageSizeInfo(final String packageName, int userHandle,
17021            final IPackageStatsObserver observer) {
17022        mContext.enforceCallingOrSelfPermission(
17023                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17024        if (packageName == null) {
17025            throw new IllegalArgumentException("Attempt to get size of null packageName");
17026        }
17027
17028        PackageStats stats = new PackageStats(packageName, userHandle);
17029
17030        /*
17031         * Queue up an async operation since the package measurement may take a
17032         * little while.
17033         */
17034        Message msg = mHandler.obtainMessage(INIT_COPY);
17035        msg.obj = new MeasureParams(stats, observer);
17036        mHandler.sendMessage(msg);
17037    }
17038
17039    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17040        final PackageSetting ps;
17041        synchronized (mPackages) {
17042            ps = mSettings.mPackages.get(packageName);
17043            if (ps == null) {
17044                Slog.w(TAG, "Failed to find settings for " + packageName);
17045                return false;
17046            }
17047        }
17048        try {
17049            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17050                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17051                    ps.getCeDataInode(userId), ps.codePathString, stats);
17052        } catch (InstallerException e) {
17053            Slog.w(TAG, String.valueOf(e));
17054            return false;
17055        }
17056
17057        // For now, ignore code size of packages on system partition
17058        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17059            stats.codeSize = 0;
17060        }
17061
17062        return true;
17063    }
17064
17065    private int getUidTargetSdkVersionLockedLPr(int uid) {
17066        Object obj = mSettings.getUserIdLPr(uid);
17067        if (obj instanceof SharedUserSetting) {
17068            final SharedUserSetting sus = (SharedUserSetting) obj;
17069            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17070            final Iterator<PackageSetting> it = sus.packages.iterator();
17071            while (it.hasNext()) {
17072                final PackageSetting ps = it.next();
17073                if (ps.pkg != null) {
17074                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17075                    if (v < vers) vers = v;
17076                }
17077            }
17078            return vers;
17079        } else if (obj instanceof PackageSetting) {
17080            final PackageSetting ps = (PackageSetting) obj;
17081            if (ps.pkg != null) {
17082                return ps.pkg.applicationInfo.targetSdkVersion;
17083            }
17084        }
17085        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17086    }
17087
17088    @Override
17089    public void addPreferredActivity(IntentFilter filter, int match,
17090            ComponentName[] set, ComponentName activity, int userId) {
17091        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17092                "Adding preferred");
17093    }
17094
17095    private void addPreferredActivityInternal(IntentFilter filter, int match,
17096            ComponentName[] set, ComponentName activity, boolean always, int userId,
17097            String opname) {
17098        // writer
17099        int callingUid = Binder.getCallingUid();
17100        enforceCrossUserPermission(callingUid, userId,
17101                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17102        if (filter.countActions() == 0) {
17103            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17104            return;
17105        }
17106        synchronized (mPackages) {
17107            if (mContext.checkCallingOrSelfPermission(
17108                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17109                    != PackageManager.PERMISSION_GRANTED) {
17110                if (getUidTargetSdkVersionLockedLPr(callingUid)
17111                        < Build.VERSION_CODES.FROYO) {
17112                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17113                            + callingUid);
17114                    return;
17115                }
17116                mContext.enforceCallingOrSelfPermission(
17117                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17118            }
17119
17120            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17121            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17122                    + userId + ":");
17123            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17124            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17125            scheduleWritePackageRestrictionsLocked(userId);
17126            postPreferredActivityChangedBroadcast(userId);
17127        }
17128    }
17129
17130    private void postPreferredActivityChangedBroadcast(int userId) {
17131        mHandler.post(() -> {
17132            final IActivityManager am = ActivityManagerNative.getDefault();
17133            if (am == null) {
17134                return;
17135            }
17136
17137            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17138            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17139            try {
17140                am.broadcastIntent(null, intent, null, null,
17141                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17142                        null, false, false, userId);
17143            } catch (RemoteException e) {
17144            }
17145        });
17146    }
17147
17148    @Override
17149    public void replacePreferredActivity(IntentFilter filter, int match,
17150            ComponentName[] set, ComponentName activity, int userId) {
17151        if (filter.countActions() != 1) {
17152            throw new IllegalArgumentException(
17153                    "replacePreferredActivity expects filter to have only 1 action.");
17154        }
17155        if (filter.countDataAuthorities() != 0
17156                || filter.countDataPaths() != 0
17157                || filter.countDataSchemes() > 1
17158                || filter.countDataTypes() != 0) {
17159            throw new IllegalArgumentException(
17160                    "replacePreferredActivity expects filter to have no data authorities, " +
17161                    "paths, or types; and at most one scheme.");
17162        }
17163
17164        final int callingUid = Binder.getCallingUid();
17165        enforceCrossUserPermission(callingUid, userId,
17166                true /* requireFullPermission */, false /* checkShell */,
17167                "replace preferred activity");
17168        synchronized (mPackages) {
17169            if (mContext.checkCallingOrSelfPermission(
17170                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17171                    != PackageManager.PERMISSION_GRANTED) {
17172                if (getUidTargetSdkVersionLockedLPr(callingUid)
17173                        < Build.VERSION_CODES.FROYO) {
17174                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17175                            + Binder.getCallingUid());
17176                    return;
17177                }
17178                mContext.enforceCallingOrSelfPermission(
17179                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17180            }
17181
17182            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17183            if (pir != null) {
17184                // Get all of the existing entries that exactly match this filter.
17185                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17186                if (existing != null && existing.size() == 1) {
17187                    PreferredActivity cur = existing.get(0);
17188                    if (DEBUG_PREFERRED) {
17189                        Slog.i(TAG, "Checking replace of preferred:");
17190                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17191                        if (!cur.mPref.mAlways) {
17192                            Slog.i(TAG, "  -- CUR; not mAlways!");
17193                        } else {
17194                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17195                            Slog.i(TAG, "  -- CUR: mSet="
17196                                    + Arrays.toString(cur.mPref.mSetComponents));
17197                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17198                            Slog.i(TAG, "  -- NEW: mMatch="
17199                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17200                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17201                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17202                        }
17203                    }
17204                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17205                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17206                            && cur.mPref.sameSet(set)) {
17207                        // Setting the preferred activity to what it happens to be already
17208                        if (DEBUG_PREFERRED) {
17209                            Slog.i(TAG, "Replacing with same preferred activity "
17210                                    + cur.mPref.mShortComponent + " for user "
17211                                    + userId + ":");
17212                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17213                        }
17214                        return;
17215                    }
17216                }
17217
17218                if (existing != null) {
17219                    if (DEBUG_PREFERRED) {
17220                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17221                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17222                    }
17223                    for (int i = 0; i < existing.size(); i++) {
17224                        PreferredActivity pa = existing.get(i);
17225                        if (DEBUG_PREFERRED) {
17226                            Slog.i(TAG, "Removing existing preferred activity "
17227                                    + pa.mPref.mComponent + ":");
17228                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17229                        }
17230                        pir.removeFilter(pa);
17231                    }
17232                }
17233            }
17234            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17235                    "Replacing preferred");
17236        }
17237    }
17238
17239    @Override
17240    public void clearPackagePreferredActivities(String packageName) {
17241        final int uid = Binder.getCallingUid();
17242        // writer
17243        synchronized (mPackages) {
17244            PackageParser.Package pkg = mPackages.get(packageName);
17245            if (pkg == null || pkg.applicationInfo.uid != uid) {
17246                if (mContext.checkCallingOrSelfPermission(
17247                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17248                        != PackageManager.PERMISSION_GRANTED) {
17249                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17250                            < Build.VERSION_CODES.FROYO) {
17251                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17252                                + Binder.getCallingUid());
17253                        return;
17254                    }
17255                    mContext.enforceCallingOrSelfPermission(
17256                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17257                }
17258            }
17259
17260            int user = UserHandle.getCallingUserId();
17261            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17262                scheduleWritePackageRestrictionsLocked(user);
17263            }
17264        }
17265    }
17266
17267    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17268    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17269        ArrayList<PreferredActivity> removed = null;
17270        boolean changed = false;
17271        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17272            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17273            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17274            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17275                continue;
17276            }
17277            Iterator<PreferredActivity> it = pir.filterIterator();
17278            while (it.hasNext()) {
17279                PreferredActivity pa = it.next();
17280                // Mark entry for removal only if it matches the package name
17281                // and the entry is of type "always".
17282                if (packageName == null ||
17283                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17284                                && pa.mPref.mAlways)) {
17285                    if (removed == null) {
17286                        removed = new ArrayList<PreferredActivity>();
17287                    }
17288                    removed.add(pa);
17289                }
17290            }
17291            if (removed != null) {
17292                for (int j=0; j<removed.size(); j++) {
17293                    PreferredActivity pa = removed.get(j);
17294                    pir.removeFilter(pa);
17295                }
17296                changed = true;
17297            }
17298        }
17299        if (changed) {
17300            postPreferredActivityChangedBroadcast(userId);
17301        }
17302        return changed;
17303    }
17304
17305    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17306    private void clearIntentFilterVerificationsLPw(int userId) {
17307        final int packageCount = mPackages.size();
17308        for (int i = 0; i < packageCount; i++) {
17309            PackageParser.Package pkg = mPackages.valueAt(i);
17310            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17311        }
17312    }
17313
17314    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17315    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17316        if (userId == UserHandle.USER_ALL) {
17317            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17318                    sUserManager.getUserIds())) {
17319                for (int oneUserId : sUserManager.getUserIds()) {
17320                    scheduleWritePackageRestrictionsLocked(oneUserId);
17321                }
17322            }
17323        } else {
17324            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17325                scheduleWritePackageRestrictionsLocked(userId);
17326            }
17327        }
17328    }
17329
17330    void clearDefaultBrowserIfNeeded(String packageName) {
17331        for (int oneUserId : sUserManager.getUserIds()) {
17332            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17333            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17334            if (packageName.equals(defaultBrowserPackageName)) {
17335                setDefaultBrowserPackageName(null, oneUserId);
17336            }
17337        }
17338    }
17339
17340    @Override
17341    public void resetApplicationPreferences(int userId) {
17342        mContext.enforceCallingOrSelfPermission(
17343                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17344        final long identity = Binder.clearCallingIdentity();
17345        // writer
17346        try {
17347            synchronized (mPackages) {
17348                clearPackagePreferredActivitiesLPw(null, userId);
17349                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17350                // TODO: We have to reset the default SMS and Phone. This requires
17351                // significant refactoring to keep all default apps in the package
17352                // manager (cleaner but more work) or have the services provide
17353                // callbacks to the package manager to request a default app reset.
17354                applyFactoryDefaultBrowserLPw(userId);
17355                clearIntentFilterVerificationsLPw(userId);
17356                primeDomainVerificationsLPw(userId);
17357                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17358                scheduleWritePackageRestrictionsLocked(userId);
17359            }
17360            resetNetworkPolicies(userId);
17361        } finally {
17362            Binder.restoreCallingIdentity(identity);
17363        }
17364    }
17365
17366    @Override
17367    public int getPreferredActivities(List<IntentFilter> outFilters,
17368            List<ComponentName> outActivities, String packageName) {
17369
17370        int num = 0;
17371        final int userId = UserHandle.getCallingUserId();
17372        // reader
17373        synchronized (mPackages) {
17374            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17375            if (pir != null) {
17376                final Iterator<PreferredActivity> it = pir.filterIterator();
17377                while (it.hasNext()) {
17378                    final PreferredActivity pa = it.next();
17379                    if (packageName == null
17380                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17381                                    && pa.mPref.mAlways)) {
17382                        if (outFilters != null) {
17383                            outFilters.add(new IntentFilter(pa));
17384                        }
17385                        if (outActivities != null) {
17386                            outActivities.add(pa.mPref.mComponent);
17387                        }
17388                    }
17389                }
17390            }
17391        }
17392
17393        return num;
17394    }
17395
17396    @Override
17397    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17398            int userId) {
17399        int callingUid = Binder.getCallingUid();
17400        if (callingUid != Process.SYSTEM_UID) {
17401            throw new SecurityException(
17402                    "addPersistentPreferredActivity can only be run by the system");
17403        }
17404        if (filter.countActions() == 0) {
17405            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17406            return;
17407        }
17408        synchronized (mPackages) {
17409            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17410                    ":");
17411            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17412            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17413                    new PersistentPreferredActivity(filter, activity));
17414            scheduleWritePackageRestrictionsLocked(userId);
17415            postPreferredActivityChangedBroadcast(userId);
17416        }
17417    }
17418
17419    @Override
17420    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17421        int callingUid = Binder.getCallingUid();
17422        if (callingUid != Process.SYSTEM_UID) {
17423            throw new SecurityException(
17424                    "clearPackagePersistentPreferredActivities can only be run by the system");
17425        }
17426        ArrayList<PersistentPreferredActivity> removed = null;
17427        boolean changed = false;
17428        synchronized (mPackages) {
17429            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17430                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17431                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17432                        .valueAt(i);
17433                if (userId != thisUserId) {
17434                    continue;
17435                }
17436                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17437                while (it.hasNext()) {
17438                    PersistentPreferredActivity ppa = it.next();
17439                    // Mark entry for removal only if it matches the package name.
17440                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17441                        if (removed == null) {
17442                            removed = new ArrayList<PersistentPreferredActivity>();
17443                        }
17444                        removed.add(ppa);
17445                    }
17446                }
17447                if (removed != null) {
17448                    for (int j=0; j<removed.size(); j++) {
17449                        PersistentPreferredActivity ppa = removed.get(j);
17450                        ppir.removeFilter(ppa);
17451                    }
17452                    changed = true;
17453                }
17454            }
17455
17456            if (changed) {
17457                scheduleWritePackageRestrictionsLocked(userId);
17458                postPreferredActivityChangedBroadcast(userId);
17459            }
17460        }
17461    }
17462
17463    /**
17464     * Common machinery for picking apart a restored XML blob and passing
17465     * it to a caller-supplied functor to be applied to the running system.
17466     */
17467    private void restoreFromXml(XmlPullParser parser, int userId,
17468            String expectedStartTag, BlobXmlRestorer functor)
17469            throws IOException, XmlPullParserException {
17470        int type;
17471        while ((type = parser.next()) != XmlPullParser.START_TAG
17472                && type != XmlPullParser.END_DOCUMENT) {
17473        }
17474        if (type != XmlPullParser.START_TAG) {
17475            // oops didn't find a start tag?!
17476            if (DEBUG_BACKUP) {
17477                Slog.e(TAG, "Didn't find start tag during restore");
17478            }
17479            return;
17480        }
17481Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17482        // this is supposed to be TAG_PREFERRED_BACKUP
17483        if (!expectedStartTag.equals(parser.getName())) {
17484            if (DEBUG_BACKUP) {
17485                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17486            }
17487            return;
17488        }
17489
17490        // skip interfering stuff, then we're aligned with the backing implementation
17491        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17492Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17493        functor.apply(parser, userId);
17494    }
17495
17496    private interface BlobXmlRestorer {
17497        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17498    }
17499
17500    /**
17501     * Non-Binder method, support for the backup/restore mechanism: write the
17502     * full set of preferred activities in its canonical XML format.  Returns the
17503     * XML output as a byte array, or null if there is none.
17504     */
17505    @Override
17506    public byte[] getPreferredActivityBackup(int userId) {
17507        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17508            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17509        }
17510
17511        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17512        try {
17513            final XmlSerializer serializer = new FastXmlSerializer();
17514            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17515            serializer.startDocument(null, true);
17516            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17517
17518            synchronized (mPackages) {
17519                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17520            }
17521
17522            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17523            serializer.endDocument();
17524            serializer.flush();
17525        } catch (Exception e) {
17526            if (DEBUG_BACKUP) {
17527                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17528            }
17529            return null;
17530        }
17531
17532        return dataStream.toByteArray();
17533    }
17534
17535    @Override
17536    public void restorePreferredActivities(byte[] backup, int userId) {
17537        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17538            throw new SecurityException("Only the system may call restorePreferredActivities()");
17539        }
17540
17541        try {
17542            final XmlPullParser parser = Xml.newPullParser();
17543            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17544            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17545                    new BlobXmlRestorer() {
17546                        @Override
17547                        public void apply(XmlPullParser parser, int userId)
17548                                throws XmlPullParserException, IOException {
17549                            synchronized (mPackages) {
17550                                mSettings.readPreferredActivitiesLPw(parser, userId);
17551                            }
17552                        }
17553                    } );
17554        } catch (Exception e) {
17555            if (DEBUG_BACKUP) {
17556                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17557            }
17558        }
17559    }
17560
17561    /**
17562     * Non-Binder method, support for the backup/restore mechanism: write the
17563     * default browser (etc) settings in its canonical XML format.  Returns the default
17564     * browser XML representation as a byte array, or null if there is none.
17565     */
17566    @Override
17567    public byte[] getDefaultAppsBackup(int userId) {
17568        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17569            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17570        }
17571
17572        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17573        try {
17574            final XmlSerializer serializer = new FastXmlSerializer();
17575            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17576            serializer.startDocument(null, true);
17577            serializer.startTag(null, TAG_DEFAULT_APPS);
17578
17579            synchronized (mPackages) {
17580                mSettings.writeDefaultAppsLPr(serializer, userId);
17581            }
17582
17583            serializer.endTag(null, TAG_DEFAULT_APPS);
17584            serializer.endDocument();
17585            serializer.flush();
17586        } catch (Exception e) {
17587            if (DEBUG_BACKUP) {
17588                Slog.e(TAG, "Unable to write default apps for backup", e);
17589            }
17590            return null;
17591        }
17592
17593        return dataStream.toByteArray();
17594    }
17595
17596    @Override
17597    public void restoreDefaultApps(byte[] backup, int userId) {
17598        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17599            throw new SecurityException("Only the system may call restoreDefaultApps()");
17600        }
17601
17602        try {
17603            final XmlPullParser parser = Xml.newPullParser();
17604            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17605            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17606                    new BlobXmlRestorer() {
17607                        @Override
17608                        public void apply(XmlPullParser parser, int userId)
17609                                throws XmlPullParserException, IOException {
17610                            synchronized (mPackages) {
17611                                mSettings.readDefaultAppsLPw(parser, userId);
17612                            }
17613                        }
17614                    } );
17615        } catch (Exception e) {
17616            if (DEBUG_BACKUP) {
17617                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17618            }
17619        }
17620    }
17621
17622    @Override
17623    public byte[] getIntentFilterVerificationBackup(int userId) {
17624        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17625            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17626        }
17627
17628        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17629        try {
17630            final XmlSerializer serializer = new FastXmlSerializer();
17631            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17632            serializer.startDocument(null, true);
17633            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17634
17635            synchronized (mPackages) {
17636                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17637            }
17638
17639            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17640            serializer.endDocument();
17641            serializer.flush();
17642        } catch (Exception e) {
17643            if (DEBUG_BACKUP) {
17644                Slog.e(TAG, "Unable to write default apps for backup", e);
17645            }
17646            return null;
17647        }
17648
17649        return dataStream.toByteArray();
17650    }
17651
17652    @Override
17653    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17654        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17655            throw new SecurityException("Only the system may call restorePreferredActivities()");
17656        }
17657
17658        try {
17659            final XmlPullParser parser = Xml.newPullParser();
17660            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17661            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17662                    new BlobXmlRestorer() {
17663                        @Override
17664                        public void apply(XmlPullParser parser, int userId)
17665                                throws XmlPullParserException, IOException {
17666                            synchronized (mPackages) {
17667                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17668                                mSettings.writeLPr();
17669                            }
17670                        }
17671                    } );
17672        } catch (Exception e) {
17673            if (DEBUG_BACKUP) {
17674                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17675            }
17676        }
17677    }
17678
17679    @Override
17680    public byte[] getPermissionGrantBackup(int userId) {
17681        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17682            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17683        }
17684
17685        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17686        try {
17687            final XmlSerializer serializer = new FastXmlSerializer();
17688            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17689            serializer.startDocument(null, true);
17690            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17691
17692            synchronized (mPackages) {
17693                serializeRuntimePermissionGrantsLPr(serializer, userId);
17694            }
17695
17696            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17697            serializer.endDocument();
17698            serializer.flush();
17699        } catch (Exception e) {
17700            if (DEBUG_BACKUP) {
17701                Slog.e(TAG, "Unable to write default apps for backup", e);
17702            }
17703            return null;
17704        }
17705
17706        return dataStream.toByteArray();
17707    }
17708
17709    @Override
17710    public void restorePermissionGrants(byte[] backup, int userId) {
17711        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17712            throw new SecurityException("Only the system may call restorePermissionGrants()");
17713        }
17714
17715        try {
17716            final XmlPullParser parser = Xml.newPullParser();
17717            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17718            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17719                    new BlobXmlRestorer() {
17720                        @Override
17721                        public void apply(XmlPullParser parser, int userId)
17722                                throws XmlPullParserException, IOException {
17723                            synchronized (mPackages) {
17724                                processRestoredPermissionGrantsLPr(parser, userId);
17725                            }
17726                        }
17727                    } );
17728        } catch (Exception e) {
17729            if (DEBUG_BACKUP) {
17730                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17731            }
17732        }
17733    }
17734
17735    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17736            throws IOException {
17737        serializer.startTag(null, TAG_ALL_GRANTS);
17738
17739        final int N = mSettings.mPackages.size();
17740        for (int i = 0; i < N; i++) {
17741            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17742            boolean pkgGrantsKnown = false;
17743
17744            PermissionsState packagePerms = ps.getPermissionsState();
17745
17746            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17747                final int grantFlags = state.getFlags();
17748                // only look at grants that are not system/policy fixed
17749                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17750                    final boolean isGranted = state.isGranted();
17751                    // And only back up the user-twiddled state bits
17752                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17753                        final String packageName = mSettings.mPackages.keyAt(i);
17754                        if (!pkgGrantsKnown) {
17755                            serializer.startTag(null, TAG_GRANT);
17756                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17757                            pkgGrantsKnown = true;
17758                        }
17759
17760                        final boolean userSet =
17761                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17762                        final boolean userFixed =
17763                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17764                        final boolean revoke =
17765                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17766
17767                        serializer.startTag(null, TAG_PERMISSION);
17768                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17769                        if (isGranted) {
17770                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17771                        }
17772                        if (userSet) {
17773                            serializer.attribute(null, ATTR_USER_SET, "true");
17774                        }
17775                        if (userFixed) {
17776                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17777                        }
17778                        if (revoke) {
17779                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17780                        }
17781                        serializer.endTag(null, TAG_PERMISSION);
17782                    }
17783                }
17784            }
17785
17786            if (pkgGrantsKnown) {
17787                serializer.endTag(null, TAG_GRANT);
17788            }
17789        }
17790
17791        serializer.endTag(null, TAG_ALL_GRANTS);
17792    }
17793
17794    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17795            throws XmlPullParserException, IOException {
17796        String pkgName = null;
17797        int outerDepth = parser.getDepth();
17798        int type;
17799        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17800                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17801            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17802                continue;
17803            }
17804
17805            final String tagName = parser.getName();
17806            if (tagName.equals(TAG_GRANT)) {
17807                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17808                if (DEBUG_BACKUP) {
17809                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17810                }
17811            } else if (tagName.equals(TAG_PERMISSION)) {
17812
17813                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17814                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17815
17816                int newFlagSet = 0;
17817                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17818                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17819                }
17820                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17821                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17822                }
17823                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17824                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17825                }
17826                if (DEBUG_BACKUP) {
17827                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17828                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17829                }
17830                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17831                if (ps != null) {
17832                    // Already installed so we apply the grant immediately
17833                    if (DEBUG_BACKUP) {
17834                        Slog.v(TAG, "        + already installed; applying");
17835                    }
17836                    PermissionsState perms = ps.getPermissionsState();
17837                    BasePermission bp = mSettings.mPermissions.get(permName);
17838                    if (bp != null) {
17839                        if (isGranted) {
17840                            perms.grantRuntimePermission(bp, userId);
17841                        }
17842                        if (newFlagSet != 0) {
17843                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17844                        }
17845                    }
17846                } else {
17847                    // Need to wait for post-restore install to apply the grant
17848                    if (DEBUG_BACKUP) {
17849                        Slog.v(TAG, "        - not yet installed; saving for later");
17850                    }
17851                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17852                            isGranted, newFlagSet, userId);
17853                }
17854            } else {
17855                PackageManagerService.reportSettingsProblem(Log.WARN,
17856                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17857                XmlUtils.skipCurrentTag(parser);
17858            }
17859        }
17860
17861        scheduleWriteSettingsLocked();
17862        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17863    }
17864
17865    @Override
17866    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17867            int sourceUserId, int targetUserId, int flags) {
17868        mContext.enforceCallingOrSelfPermission(
17869                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17870        int callingUid = Binder.getCallingUid();
17871        enforceOwnerRights(ownerPackage, callingUid);
17872        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17873        if (intentFilter.countActions() == 0) {
17874            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17875            return;
17876        }
17877        synchronized (mPackages) {
17878            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17879                    ownerPackage, targetUserId, flags);
17880            CrossProfileIntentResolver resolver =
17881                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17882            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17883            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17884            if (existing != null) {
17885                int size = existing.size();
17886                for (int i = 0; i < size; i++) {
17887                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17888                        return;
17889                    }
17890                }
17891            }
17892            resolver.addFilter(newFilter);
17893            scheduleWritePackageRestrictionsLocked(sourceUserId);
17894        }
17895    }
17896
17897    @Override
17898    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17899        mContext.enforceCallingOrSelfPermission(
17900                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17901        int callingUid = Binder.getCallingUid();
17902        enforceOwnerRights(ownerPackage, callingUid);
17903        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17904        synchronized (mPackages) {
17905            CrossProfileIntentResolver resolver =
17906                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17907            ArraySet<CrossProfileIntentFilter> set =
17908                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17909            for (CrossProfileIntentFilter filter : set) {
17910                if (filter.getOwnerPackage().equals(ownerPackage)) {
17911                    resolver.removeFilter(filter);
17912                }
17913            }
17914            scheduleWritePackageRestrictionsLocked(sourceUserId);
17915        }
17916    }
17917
17918    // Enforcing that callingUid is owning pkg on userId
17919    private void enforceOwnerRights(String pkg, int callingUid) {
17920        // The system owns everything.
17921        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17922            return;
17923        }
17924        int callingUserId = UserHandle.getUserId(callingUid);
17925        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17926        if (pi == null) {
17927            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17928                    + callingUserId);
17929        }
17930        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17931            throw new SecurityException("Calling uid " + callingUid
17932                    + " does not own package " + pkg);
17933        }
17934    }
17935
17936    @Override
17937    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17938        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17939    }
17940
17941    private Intent getHomeIntent() {
17942        Intent intent = new Intent(Intent.ACTION_MAIN);
17943        intent.addCategory(Intent.CATEGORY_HOME);
17944        intent.addCategory(Intent.CATEGORY_DEFAULT);
17945        return intent;
17946    }
17947
17948    private IntentFilter getHomeFilter() {
17949        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17950        filter.addCategory(Intent.CATEGORY_HOME);
17951        filter.addCategory(Intent.CATEGORY_DEFAULT);
17952        return filter;
17953    }
17954
17955    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17956            int userId) {
17957        Intent intent  = getHomeIntent();
17958        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17959                PackageManager.GET_META_DATA, userId);
17960        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17961                true, false, false, userId);
17962
17963        allHomeCandidates.clear();
17964        if (list != null) {
17965            for (ResolveInfo ri : list) {
17966                allHomeCandidates.add(ri);
17967            }
17968        }
17969        return (preferred == null || preferred.activityInfo == null)
17970                ? null
17971                : new ComponentName(preferred.activityInfo.packageName,
17972                        preferred.activityInfo.name);
17973    }
17974
17975    @Override
17976    public void setHomeActivity(ComponentName comp, int userId) {
17977        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17978        getHomeActivitiesAsUser(homeActivities, userId);
17979
17980        boolean found = false;
17981
17982        final int size = homeActivities.size();
17983        final ComponentName[] set = new ComponentName[size];
17984        for (int i = 0; i < size; i++) {
17985            final ResolveInfo candidate = homeActivities.get(i);
17986            final ActivityInfo info = candidate.activityInfo;
17987            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17988            set[i] = activityName;
17989            if (!found && activityName.equals(comp)) {
17990                found = true;
17991            }
17992        }
17993        if (!found) {
17994            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17995                    + userId);
17996        }
17997        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17998                set, comp, userId);
17999    }
18000
18001    private @Nullable String getSetupWizardPackageName() {
18002        final Intent intent = new Intent(Intent.ACTION_MAIN);
18003        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18004
18005        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18006                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18007                        | MATCH_DISABLED_COMPONENTS,
18008                UserHandle.myUserId());
18009        if (matches.size() == 1) {
18010            return matches.get(0).getComponentInfo().packageName;
18011        } else {
18012            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18013                    + ": matches=" + matches);
18014            return null;
18015        }
18016    }
18017
18018    private @Nullable String getStorageManagerPackageName() {
18019        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18020
18021        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18022                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18023                        | MATCH_DISABLED_COMPONENTS,
18024                UserHandle.myUserId());
18025        if (matches.size() == 1) {
18026            return matches.get(0).getComponentInfo().packageName;
18027        } else {
18028            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18029                    + matches.size() + ": matches=" + matches);
18030            return null;
18031        }
18032    }
18033
18034    @Override
18035    public void setApplicationEnabledSetting(String appPackageName,
18036            int newState, int flags, int userId, String callingPackage) {
18037        if (!sUserManager.exists(userId)) return;
18038        if (callingPackage == null) {
18039            callingPackage = Integer.toString(Binder.getCallingUid());
18040        }
18041        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18042    }
18043
18044    @Override
18045    public void setComponentEnabledSetting(ComponentName componentName,
18046            int newState, int flags, int userId) {
18047        if (!sUserManager.exists(userId)) return;
18048        setEnabledSetting(componentName.getPackageName(),
18049                componentName.getClassName(), newState, flags, userId, null);
18050    }
18051
18052    private void setEnabledSetting(final String packageName, String className, int newState,
18053            final int flags, int userId, String callingPackage) {
18054        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18055              || newState == COMPONENT_ENABLED_STATE_ENABLED
18056              || newState == COMPONENT_ENABLED_STATE_DISABLED
18057              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18058              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18059            throw new IllegalArgumentException("Invalid new component state: "
18060                    + newState);
18061        }
18062        PackageSetting pkgSetting;
18063        final int uid = Binder.getCallingUid();
18064        final int permission;
18065        if (uid == Process.SYSTEM_UID) {
18066            permission = PackageManager.PERMISSION_GRANTED;
18067        } else {
18068            permission = mContext.checkCallingOrSelfPermission(
18069                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18070        }
18071        enforceCrossUserPermission(uid, userId,
18072                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18073        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18074        boolean sendNow = false;
18075        boolean isApp = (className == null);
18076        String componentName = isApp ? packageName : className;
18077        int packageUid = -1;
18078        ArrayList<String> components;
18079
18080        // writer
18081        synchronized (mPackages) {
18082            pkgSetting = mSettings.mPackages.get(packageName);
18083            if (pkgSetting == null) {
18084                if (className == null) {
18085                    throw new IllegalArgumentException("Unknown package: " + packageName);
18086                }
18087                throw new IllegalArgumentException(
18088                        "Unknown component: " + packageName + "/" + className);
18089            }
18090        }
18091
18092        // Limit who can change which apps
18093        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18094            // Don't allow apps that don't have permission to modify other apps
18095            if (!allowedByPermission) {
18096                throw new SecurityException(
18097                        "Permission Denial: attempt to change component state from pid="
18098                        + Binder.getCallingPid()
18099                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18100            }
18101            // Don't allow changing protected packages.
18102            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18103                throw new SecurityException("Cannot disable a protected package: " + packageName);
18104            }
18105        }
18106
18107        synchronized (mPackages) {
18108            if (uid == Process.SHELL_UID
18109                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18110                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18111                // unless it is a test package.
18112                int oldState = pkgSetting.getEnabled(userId);
18113                if (className == null
18114                    &&
18115                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18116                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18117                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18118                    &&
18119                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18120                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18121                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18122                    // ok
18123                } else {
18124                    throw new SecurityException(
18125                            "Shell cannot change component state for " + packageName + "/"
18126                            + className + " to " + newState);
18127                }
18128            }
18129            if (className == null) {
18130                // We're dealing with an application/package level state change
18131                if (pkgSetting.getEnabled(userId) == newState) {
18132                    // Nothing to do
18133                    return;
18134                }
18135                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18136                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18137                    // Don't care about who enables an app.
18138                    callingPackage = null;
18139                }
18140                pkgSetting.setEnabled(newState, userId, callingPackage);
18141                // pkgSetting.pkg.mSetEnabled = newState;
18142            } else {
18143                // We're dealing with a component level state change
18144                // First, verify that this is a valid class name.
18145                PackageParser.Package pkg = pkgSetting.pkg;
18146                if (pkg == null || !pkg.hasComponentClassName(className)) {
18147                    if (pkg != null &&
18148                            pkg.applicationInfo.targetSdkVersion >=
18149                                    Build.VERSION_CODES.JELLY_BEAN) {
18150                        throw new IllegalArgumentException("Component class " + className
18151                                + " does not exist in " + packageName);
18152                    } else {
18153                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18154                                + className + " does not exist in " + packageName);
18155                    }
18156                }
18157                switch (newState) {
18158                case COMPONENT_ENABLED_STATE_ENABLED:
18159                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18160                        return;
18161                    }
18162                    break;
18163                case COMPONENT_ENABLED_STATE_DISABLED:
18164                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18165                        return;
18166                    }
18167                    break;
18168                case COMPONENT_ENABLED_STATE_DEFAULT:
18169                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18170                        return;
18171                    }
18172                    break;
18173                default:
18174                    Slog.e(TAG, "Invalid new component state: " + newState);
18175                    return;
18176                }
18177            }
18178            scheduleWritePackageRestrictionsLocked(userId);
18179            components = mPendingBroadcasts.get(userId, packageName);
18180            final boolean newPackage = components == null;
18181            if (newPackage) {
18182                components = new ArrayList<String>();
18183            }
18184            if (!components.contains(componentName)) {
18185                components.add(componentName);
18186            }
18187            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18188                sendNow = true;
18189                // Purge entry from pending broadcast list if another one exists already
18190                // since we are sending one right away.
18191                mPendingBroadcasts.remove(userId, packageName);
18192            } else {
18193                if (newPackage) {
18194                    mPendingBroadcasts.put(userId, packageName, components);
18195                }
18196                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18197                    // Schedule a message
18198                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18199                }
18200            }
18201        }
18202
18203        long callingId = Binder.clearCallingIdentity();
18204        try {
18205            if (sendNow) {
18206                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18207                sendPackageChangedBroadcast(packageName,
18208                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18209            }
18210        } finally {
18211            Binder.restoreCallingIdentity(callingId);
18212        }
18213    }
18214
18215    @Override
18216    public void flushPackageRestrictionsAsUser(int userId) {
18217        if (!sUserManager.exists(userId)) {
18218            return;
18219        }
18220        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18221                false /* checkShell */, "flushPackageRestrictions");
18222        synchronized (mPackages) {
18223            mSettings.writePackageRestrictionsLPr(userId);
18224            mDirtyUsers.remove(userId);
18225            if (mDirtyUsers.isEmpty()) {
18226                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18227            }
18228        }
18229    }
18230
18231    private void sendPackageChangedBroadcast(String packageName,
18232            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18233        if (DEBUG_INSTALL)
18234            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18235                    + componentNames);
18236        Bundle extras = new Bundle(4);
18237        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18238        String nameList[] = new String[componentNames.size()];
18239        componentNames.toArray(nameList);
18240        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18241        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18242        extras.putInt(Intent.EXTRA_UID, packageUid);
18243        // If this is not reporting a change of the overall package, then only send it
18244        // to registered receivers.  We don't want to launch a swath of apps for every
18245        // little component state change.
18246        final int flags = !componentNames.contains(packageName)
18247                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18248        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18249                new int[] {UserHandle.getUserId(packageUid)});
18250    }
18251
18252    @Override
18253    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18254        if (!sUserManager.exists(userId)) return;
18255        final int uid = Binder.getCallingUid();
18256        final int permission = mContext.checkCallingOrSelfPermission(
18257                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18258        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18259        enforceCrossUserPermission(uid, userId,
18260                true /* requireFullPermission */, true /* checkShell */, "stop package");
18261        // writer
18262        synchronized (mPackages) {
18263            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18264                    allowedByPermission, uid, userId)) {
18265                scheduleWritePackageRestrictionsLocked(userId);
18266            }
18267        }
18268    }
18269
18270    @Override
18271    public String getInstallerPackageName(String packageName) {
18272        // reader
18273        synchronized (mPackages) {
18274            return mSettings.getInstallerPackageNameLPr(packageName);
18275        }
18276    }
18277
18278    public boolean isOrphaned(String packageName) {
18279        // reader
18280        synchronized (mPackages) {
18281            return mSettings.isOrphaned(packageName);
18282        }
18283    }
18284
18285    @Override
18286    public int getApplicationEnabledSetting(String packageName, int userId) {
18287        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18288        int uid = Binder.getCallingUid();
18289        enforceCrossUserPermission(uid, userId,
18290                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18291        // reader
18292        synchronized (mPackages) {
18293            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18294        }
18295    }
18296
18297    @Override
18298    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18299        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18300        int uid = Binder.getCallingUid();
18301        enforceCrossUserPermission(uid, userId,
18302                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18303        // reader
18304        synchronized (mPackages) {
18305            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18306        }
18307    }
18308
18309    @Override
18310    public void enterSafeMode() {
18311        enforceSystemOrRoot("Only the system can request entering safe mode");
18312
18313        if (!mSystemReady) {
18314            mSafeMode = true;
18315        }
18316    }
18317
18318    @Override
18319    public void systemReady() {
18320        mSystemReady = true;
18321
18322        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18323        // disabled after already being started.
18324        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18325                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18326
18327        // Read the compatibilty setting when the system is ready.
18328        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18329                mContext.getContentResolver(),
18330                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18331        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18332        if (DEBUG_SETTINGS) {
18333            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18334        }
18335
18336        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18337
18338        synchronized (mPackages) {
18339            // Verify that all of the preferred activity components actually
18340            // exist.  It is possible for applications to be updated and at
18341            // that point remove a previously declared activity component that
18342            // had been set as a preferred activity.  We try to clean this up
18343            // the next time we encounter that preferred activity, but it is
18344            // possible for the user flow to never be able to return to that
18345            // situation so here we do a sanity check to make sure we haven't
18346            // left any junk around.
18347            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18348            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18349                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18350                removed.clear();
18351                for (PreferredActivity pa : pir.filterSet()) {
18352                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18353                        removed.add(pa);
18354                    }
18355                }
18356                if (removed.size() > 0) {
18357                    for (int r=0; r<removed.size(); r++) {
18358                        PreferredActivity pa = removed.get(r);
18359                        Slog.w(TAG, "Removing dangling preferred activity: "
18360                                + pa.mPref.mComponent);
18361                        pir.removeFilter(pa);
18362                    }
18363                    mSettings.writePackageRestrictionsLPr(
18364                            mSettings.mPreferredActivities.keyAt(i));
18365                }
18366            }
18367
18368            for (int userId : UserManagerService.getInstance().getUserIds()) {
18369                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18370                    grantPermissionsUserIds = ArrayUtils.appendInt(
18371                            grantPermissionsUserIds, userId);
18372                }
18373            }
18374        }
18375        sUserManager.systemReady();
18376
18377        // If we upgraded grant all default permissions before kicking off.
18378        for (int userId : grantPermissionsUserIds) {
18379            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18380        }
18381
18382        // If we did not grant default permissions, we preload from this the
18383        // default permission exceptions lazily to ensure we don't hit the
18384        // disk on a new user creation.
18385        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18386            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18387        }
18388
18389        // Kick off any messages waiting for system ready
18390        if (mPostSystemReadyMessages != null) {
18391            for (Message msg : mPostSystemReadyMessages) {
18392                msg.sendToTarget();
18393            }
18394            mPostSystemReadyMessages = null;
18395        }
18396
18397        // Watch for external volumes that come and go over time
18398        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18399        storage.registerListener(mStorageListener);
18400
18401        mInstallerService.systemReady();
18402        mPackageDexOptimizer.systemReady();
18403
18404        MountServiceInternal mountServiceInternal = LocalServices.getService(
18405                MountServiceInternal.class);
18406        mountServiceInternal.addExternalStoragePolicy(
18407                new MountServiceInternal.ExternalStorageMountPolicy() {
18408            @Override
18409            public int getMountMode(int uid, String packageName) {
18410                if (Process.isIsolated(uid)) {
18411                    return Zygote.MOUNT_EXTERNAL_NONE;
18412                }
18413                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18414                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18415                }
18416                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18417                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18418                }
18419                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18420                    return Zygote.MOUNT_EXTERNAL_READ;
18421                }
18422                return Zygote.MOUNT_EXTERNAL_WRITE;
18423            }
18424
18425            @Override
18426            public boolean hasExternalStorage(int uid, String packageName) {
18427                return true;
18428            }
18429        });
18430
18431        // Now that we're mostly running, clean up stale users and apps
18432        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18433        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18434    }
18435
18436    @Override
18437    public boolean isSafeMode() {
18438        return mSafeMode;
18439    }
18440
18441    @Override
18442    public boolean hasSystemUidErrors() {
18443        return mHasSystemUidErrors;
18444    }
18445
18446    static String arrayToString(int[] array) {
18447        StringBuffer buf = new StringBuffer(128);
18448        buf.append('[');
18449        if (array != null) {
18450            for (int i=0; i<array.length; i++) {
18451                if (i > 0) buf.append(", ");
18452                buf.append(array[i]);
18453            }
18454        }
18455        buf.append(']');
18456        return buf.toString();
18457    }
18458
18459    static class DumpState {
18460        public static final int DUMP_LIBS = 1 << 0;
18461        public static final int DUMP_FEATURES = 1 << 1;
18462        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18463        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18464        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18465        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18466        public static final int DUMP_PERMISSIONS = 1 << 6;
18467        public static final int DUMP_PACKAGES = 1 << 7;
18468        public static final int DUMP_SHARED_USERS = 1 << 8;
18469        public static final int DUMP_MESSAGES = 1 << 9;
18470        public static final int DUMP_PROVIDERS = 1 << 10;
18471        public static final int DUMP_VERIFIERS = 1 << 11;
18472        public static final int DUMP_PREFERRED = 1 << 12;
18473        public static final int DUMP_PREFERRED_XML = 1 << 13;
18474        public static final int DUMP_KEYSETS = 1 << 14;
18475        public static final int DUMP_VERSION = 1 << 15;
18476        public static final int DUMP_INSTALLS = 1 << 16;
18477        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18478        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18479        public static final int DUMP_FROZEN = 1 << 19;
18480        public static final int DUMP_DEXOPT = 1 << 20;
18481        public static final int DUMP_COMPILER_STATS = 1 << 21;
18482
18483        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18484
18485        private int mTypes;
18486
18487        private int mOptions;
18488
18489        private boolean mTitlePrinted;
18490
18491        private SharedUserSetting mSharedUser;
18492
18493        public boolean isDumping(int type) {
18494            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18495                return true;
18496            }
18497
18498            return (mTypes & type) != 0;
18499        }
18500
18501        public void setDump(int type) {
18502            mTypes |= type;
18503        }
18504
18505        public boolean isOptionEnabled(int option) {
18506            return (mOptions & option) != 0;
18507        }
18508
18509        public void setOptionEnabled(int option) {
18510            mOptions |= option;
18511        }
18512
18513        public boolean onTitlePrinted() {
18514            final boolean printed = mTitlePrinted;
18515            mTitlePrinted = true;
18516            return printed;
18517        }
18518
18519        public boolean getTitlePrinted() {
18520            return mTitlePrinted;
18521        }
18522
18523        public void setTitlePrinted(boolean enabled) {
18524            mTitlePrinted = enabled;
18525        }
18526
18527        public SharedUserSetting getSharedUser() {
18528            return mSharedUser;
18529        }
18530
18531        public void setSharedUser(SharedUserSetting user) {
18532            mSharedUser = user;
18533        }
18534    }
18535
18536    @Override
18537    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18538            FileDescriptor err, String[] args, ShellCallback callback,
18539            ResultReceiver resultReceiver) {
18540        (new PackageManagerShellCommand(this)).exec(
18541                this, in, out, err, args, callback, resultReceiver);
18542    }
18543
18544    @Override
18545    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18546        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18547                != PackageManager.PERMISSION_GRANTED) {
18548            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18549                    + Binder.getCallingPid()
18550                    + ", uid=" + Binder.getCallingUid()
18551                    + " without permission "
18552                    + android.Manifest.permission.DUMP);
18553            return;
18554        }
18555
18556        DumpState dumpState = new DumpState();
18557        boolean fullPreferred = false;
18558        boolean checkin = false;
18559
18560        String packageName = null;
18561        ArraySet<String> permissionNames = null;
18562
18563        int opti = 0;
18564        while (opti < args.length) {
18565            String opt = args[opti];
18566            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18567                break;
18568            }
18569            opti++;
18570
18571            if ("-a".equals(opt)) {
18572                // Right now we only know how to print all.
18573            } else if ("-h".equals(opt)) {
18574                pw.println("Package manager dump options:");
18575                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18576                pw.println("    --checkin: dump for a checkin");
18577                pw.println("    -f: print details of intent filters");
18578                pw.println("    -h: print this help");
18579                pw.println("  cmd may be one of:");
18580                pw.println("    l[ibraries]: list known shared libraries");
18581                pw.println("    f[eatures]: list device features");
18582                pw.println("    k[eysets]: print known keysets");
18583                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18584                pw.println("    perm[issions]: dump permissions");
18585                pw.println("    permission [name ...]: dump declaration and use of given permission");
18586                pw.println("    pref[erred]: print preferred package settings");
18587                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18588                pw.println("    prov[iders]: dump content providers");
18589                pw.println("    p[ackages]: dump installed packages");
18590                pw.println("    s[hared-users]: dump shared user IDs");
18591                pw.println("    m[essages]: print collected runtime messages");
18592                pw.println("    v[erifiers]: print package verifier info");
18593                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18594                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18595                pw.println("    version: print database version info");
18596                pw.println("    write: write current settings now");
18597                pw.println("    installs: details about install sessions");
18598                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18599                pw.println("    dexopt: dump dexopt state");
18600                pw.println("    compiler-stats: dump compiler statistics");
18601                pw.println("    <package.name>: info about given package");
18602                return;
18603            } else if ("--checkin".equals(opt)) {
18604                checkin = true;
18605            } else if ("-f".equals(opt)) {
18606                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18607            } else {
18608                pw.println("Unknown argument: " + opt + "; use -h for help");
18609            }
18610        }
18611
18612        // Is the caller requesting to dump a particular piece of data?
18613        if (opti < args.length) {
18614            String cmd = args[opti];
18615            opti++;
18616            // Is this a package name?
18617            if ("android".equals(cmd) || cmd.contains(".")) {
18618                packageName = cmd;
18619                // When dumping a single package, we always dump all of its
18620                // filter information since the amount of data will be reasonable.
18621                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18622            } else if ("check-permission".equals(cmd)) {
18623                if (opti >= args.length) {
18624                    pw.println("Error: check-permission missing permission argument");
18625                    return;
18626                }
18627                String perm = args[opti];
18628                opti++;
18629                if (opti >= args.length) {
18630                    pw.println("Error: check-permission missing package argument");
18631                    return;
18632                }
18633                String pkg = args[opti];
18634                opti++;
18635                int user = UserHandle.getUserId(Binder.getCallingUid());
18636                if (opti < args.length) {
18637                    try {
18638                        user = Integer.parseInt(args[opti]);
18639                    } catch (NumberFormatException e) {
18640                        pw.println("Error: check-permission user argument is not a number: "
18641                                + args[opti]);
18642                        return;
18643                    }
18644                }
18645                pw.println(checkPermission(perm, pkg, user));
18646                return;
18647            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18648                dumpState.setDump(DumpState.DUMP_LIBS);
18649            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18650                dumpState.setDump(DumpState.DUMP_FEATURES);
18651            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18652                if (opti >= args.length) {
18653                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18654                            | DumpState.DUMP_SERVICE_RESOLVERS
18655                            | DumpState.DUMP_RECEIVER_RESOLVERS
18656                            | DumpState.DUMP_CONTENT_RESOLVERS);
18657                } else {
18658                    while (opti < args.length) {
18659                        String name = args[opti];
18660                        if ("a".equals(name) || "activity".equals(name)) {
18661                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18662                        } else if ("s".equals(name) || "service".equals(name)) {
18663                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18664                        } else if ("r".equals(name) || "receiver".equals(name)) {
18665                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18666                        } else if ("c".equals(name) || "content".equals(name)) {
18667                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18668                        } else {
18669                            pw.println("Error: unknown resolver table type: " + name);
18670                            return;
18671                        }
18672                        opti++;
18673                    }
18674                }
18675            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18676                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18677            } else if ("permission".equals(cmd)) {
18678                if (opti >= args.length) {
18679                    pw.println("Error: permission requires permission name");
18680                    return;
18681                }
18682                permissionNames = new ArraySet<>();
18683                while (opti < args.length) {
18684                    permissionNames.add(args[opti]);
18685                    opti++;
18686                }
18687                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18688                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18689            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18690                dumpState.setDump(DumpState.DUMP_PREFERRED);
18691            } else if ("preferred-xml".equals(cmd)) {
18692                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18693                if (opti < args.length && "--full".equals(args[opti])) {
18694                    fullPreferred = true;
18695                    opti++;
18696                }
18697            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18698                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18699            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18700                dumpState.setDump(DumpState.DUMP_PACKAGES);
18701            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18702                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18703            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18704                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18705            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18706                dumpState.setDump(DumpState.DUMP_MESSAGES);
18707            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18708                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18709            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18710                    || "intent-filter-verifiers".equals(cmd)) {
18711                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18712            } else if ("version".equals(cmd)) {
18713                dumpState.setDump(DumpState.DUMP_VERSION);
18714            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18715                dumpState.setDump(DumpState.DUMP_KEYSETS);
18716            } else if ("installs".equals(cmd)) {
18717                dumpState.setDump(DumpState.DUMP_INSTALLS);
18718            } else if ("frozen".equals(cmd)) {
18719                dumpState.setDump(DumpState.DUMP_FROZEN);
18720            } else if ("dexopt".equals(cmd)) {
18721                dumpState.setDump(DumpState.DUMP_DEXOPT);
18722            } else if ("compiler-stats".equals(cmd)) {
18723                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18724            } else if ("write".equals(cmd)) {
18725                synchronized (mPackages) {
18726                    mSettings.writeLPr();
18727                    pw.println("Settings written.");
18728                    return;
18729                }
18730            }
18731        }
18732
18733        if (checkin) {
18734            pw.println("vers,1");
18735        }
18736
18737        // reader
18738        synchronized (mPackages) {
18739            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18740                if (!checkin) {
18741                    if (dumpState.onTitlePrinted())
18742                        pw.println();
18743                    pw.println("Database versions:");
18744                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18745                }
18746            }
18747
18748            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18749                if (!checkin) {
18750                    if (dumpState.onTitlePrinted())
18751                        pw.println();
18752                    pw.println("Verifiers:");
18753                    pw.print("  Required: ");
18754                    pw.print(mRequiredVerifierPackage);
18755                    pw.print(" (uid=");
18756                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18757                            UserHandle.USER_SYSTEM));
18758                    pw.println(")");
18759                } else if (mRequiredVerifierPackage != null) {
18760                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18761                    pw.print(",");
18762                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18763                            UserHandle.USER_SYSTEM));
18764                }
18765            }
18766
18767            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18768                    packageName == null) {
18769                if (mIntentFilterVerifierComponent != null) {
18770                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18771                    if (!checkin) {
18772                        if (dumpState.onTitlePrinted())
18773                            pw.println();
18774                        pw.println("Intent Filter Verifier:");
18775                        pw.print("  Using: ");
18776                        pw.print(verifierPackageName);
18777                        pw.print(" (uid=");
18778                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18779                                UserHandle.USER_SYSTEM));
18780                        pw.println(")");
18781                    } else if (verifierPackageName != null) {
18782                        pw.print("ifv,"); pw.print(verifierPackageName);
18783                        pw.print(",");
18784                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18785                                UserHandle.USER_SYSTEM));
18786                    }
18787                } else {
18788                    pw.println();
18789                    pw.println("No Intent Filter Verifier available!");
18790                }
18791            }
18792
18793            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18794                boolean printedHeader = false;
18795                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18796                while (it.hasNext()) {
18797                    String name = it.next();
18798                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18799                    if (!checkin) {
18800                        if (!printedHeader) {
18801                            if (dumpState.onTitlePrinted())
18802                                pw.println();
18803                            pw.println("Libraries:");
18804                            printedHeader = true;
18805                        }
18806                        pw.print("  ");
18807                    } else {
18808                        pw.print("lib,");
18809                    }
18810                    pw.print(name);
18811                    if (!checkin) {
18812                        pw.print(" -> ");
18813                    }
18814                    if (ent.path != null) {
18815                        if (!checkin) {
18816                            pw.print("(jar) ");
18817                            pw.print(ent.path);
18818                        } else {
18819                            pw.print(",jar,");
18820                            pw.print(ent.path);
18821                        }
18822                    } else {
18823                        if (!checkin) {
18824                            pw.print("(apk) ");
18825                            pw.print(ent.apk);
18826                        } else {
18827                            pw.print(",apk,");
18828                            pw.print(ent.apk);
18829                        }
18830                    }
18831                    pw.println();
18832                }
18833            }
18834
18835            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18836                if (dumpState.onTitlePrinted())
18837                    pw.println();
18838                if (!checkin) {
18839                    pw.println("Features:");
18840                }
18841
18842                for (FeatureInfo feat : mAvailableFeatures.values()) {
18843                    if (checkin) {
18844                        pw.print("feat,");
18845                        pw.print(feat.name);
18846                        pw.print(",");
18847                        pw.println(feat.version);
18848                    } else {
18849                        pw.print("  ");
18850                        pw.print(feat.name);
18851                        if (feat.version > 0) {
18852                            pw.print(" version=");
18853                            pw.print(feat.version);
18854                        }
18855                        pw.println();
18856                    }
18857                }
18858            }
18859
18860            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18861                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18862                        : "Activity Resolver Table:", "  ", packageName,
18863                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18864                    dumpState.setTitlePrinted(true);
18865                }
18866            }
18867            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18868                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18869                        : "Receiver Resolver Table:", "  ", packageName,
18870                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18871                    dumpState.setTitlePrinted(true);
18872                }
18873            }
18874            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18875                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18876                        : "Service Resolver Table:", "  ", packageName,
18877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18878                    dumpState.setTitlePrinted(true);
18879                }
18880            }
18881            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18882                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18883                        : "Provider Resolver Table:", "  ", packageName,
18884                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18885                    dumpState.setTitlePrinted(true);
18886                }
18887            }
18888
18889            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18890                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18891                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18892                    int user = mSettings.mPreferredActivities.keyAt(i);
18893                    if (pir.dump(pw,
18894                            dumpState.getTitlePrinted()
18895                                ? "\nPreferred Activities User " + user + ":"
18896                                : "Preferred Activities User " + user + ":", "  ",
18897                            packageName, true, false)) {
18898                        dumpState.setTitlePrinted(true);
18899                    }
18900                }
18901            }
18902
18903            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18904                pw.flush();
18905                FileOutputStream fout = new FileOutputStream(fd);
18906                BufferedOutputStream str = new BufferedOutputStream(fout);
18907                XmlSerializer serializer = new FastXmlSerializer();
18908                try {
18909                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18910                    serializer.startDocument(null, true);
18911                    serializer.setFeature(
18912                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18913                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18914                    serializer.endDocument();
18915                    serializer.flush();
18916                } catch (IllegalArgumentException e) {
18917                    pw.println("Failed writing: " + e);
18918                } catch (IllegalStateException e) {
18919                    pw.println("Failed writing: " + e);
18920                } catch (IOException e) {
18921                    pw.println("Failed writing: " + e);
18922                }
18923            }
18924
18925            if (!checkin
18926                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18927                    && packageName == null) {
18928                pw.println();
18929                int count = mSettings.mPackages.size();
18930                if (count == 0) {
18931                    pw.println("No applications!");
18932                    pw.println();
18933                } else {
18934                    final String prefix = "  ";
18935                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18936                    if (allPackageSettings.size() == 0) {
18937                        pw.println("No domain preferred apps!");
18938                        pw.println();
18939                    } else {
18940                        pw.println("App verification status:");
18941                        pw.println();
18942                        count = 0;
18943                        for (PackageSetting ps : allPackageSettings) {
18944                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18945                            if (ivi == null || ivi.getPackageName() == null) continue;
18946                            pw.println(prefix + "Package: " + ivi.getPackageName());
18947                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18948                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18949                            pw.println();
18950                            count++;
18951                        }
18952                        if (count == 0) {
18953                            pw.println(prefix + "No app verification established.");
18954                            pw.println();
18955                        }
18956                        for (int userId : sUserManager.getUserIds()) {
18957                            pw.println("App linkages for user " + userId + ":");
18958                            pw.println();
18959                            count = 0;
18960                            for (PackageSetting ps : allPackageSettings) {
18961                                final long status = ps.getDomainVerificationStatusForUser(userId);
18962                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18963                                    continue;
18964                                }
18965                                pw.println(prefix + "Package: " + ps.name);
18966                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18967                                String statusStr = IntentFilterVerificationInfo.
18968                                        getStatusStringFromValue(status);
18969                                pw.println(prefix + "Status:  " + statusStr);
18970                                pw.println();
18971                                count++;
18972                            }
18973                            if (count == 0) {
18974                                pw.println(prefix + "No configured app linkages.");
18975                                pw.println();
18976                            }
18977                        }
18978                    }
18979                }
18980            }
18981
18982            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18983                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18984                if (packageName == null && permissionNames == null) {
18985                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18986                        if (iperm == 0) {
18987                            if (dumpState.onTitlePrinted())
18988                                pw.println();
18989                            pw.println("AppOp Permissions:");
18990                        }
18991                        pw.print("  AppOp Permission ");
18992                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18993                        pw.println(":");
18994                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18995                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18996                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18997                        }
18998                    }
18999                }
19000            }
19001
19002            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19003                boolean printedSomething = false;
19004                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19005                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19006                        continue;
19007                    }
19008                    if (!printedSomething) {
19009                        if (dumpState.onTitlePrinted())
19010                            pw.println();
19011                        pw.println("Registered ContentProviders:");
19012                        printedSomething = true;
19013                    }
19014                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19015                    pw.print("    "); pw.println(p.toString());
19016                }
19017                printedSomething = false;
19018                for (Map.Entry<String, PackageParser.Provider> entry :
19019                        mProvidersByAuthority.entrySet()) {
19020                    PackageParser.Provider p = entry.getValue();
19021                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19022                        continue;
19023                    }
19024                    if (!printedSomething) {
19025                        if (dumpState.onTitlePrinted())
19026                            pw.println();
19027                        pw.println("ContentProvider Authorities:");
19028                        printedSomething = true;
19029                    }
19030                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19031                    pw.print("    "); pw.println(p.toString());
19032                    if (p.info != null && p.info.applicationInfo != null) {
19033                        final String appInfo = p.info.applicationInfo.toString();
19034                        pw.print("      applicationInfo="); pw.println(appInfo);
19035                    }
19036                }
19037            }
19038
19039            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19040                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19041            }
19042
19043            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19044                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19045            }
19046
19047            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19048                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19049            }
19050
19051            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19052                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19053            }
19054
19055            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19056                // XXX should handle packageName != null by dumping only install data that
19057                // the given package is involved with.
19058                if (dumpState.onTitlePrinted()) pw.println();
19059                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19060            }
19061
19062            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19063                // XXX should handle packageName != null by dumping only install data that
19064                // the given package is involved with.
19065                if (dumpState.onTitlePrinted()) pw.println();
19066
19067                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19068                ipw.println();
19069                ipw.println("Frozen packages:");
19070                ipw.increaseIndent();
19071                if (mFrozenPackages.size() == 0) {
19072                    ipw.println("(none)");
19073                } else {
19074                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19075                        ipw.println(mFrozenPackages.valueAt(i));
19076                    }
19077                }
19078                ipw.decreaseIndent();
19079            }
19080
19081            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19082                if (dumpState.onTitlePrinted()) pw.println();
19083                dumpDexoptStateLPr(pw, packageName);
19084            }
19085
19086            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19087                if (dumpState.onTitlePrinted()) pw.println();
19088                dumpCompilerStatsLPr(pw, packageName);
19089            }
19090
19091            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19092                if (dumpState.onTitlePrinted()) pw.println();
19093                mSettings.dumpReadMessagesLPr(pw, dumpState);
19094
19095                pw.println();
19096                pw.println("Package warning messages:");
19097                BufferedReader in = null;
19098                String line = null;
19099                try {
19100                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19101                    while ((line = in.readLine()) != null) {
19102                        if (line.contains("ignored: updated version")) continue;
19103                        pw.println(line);
19104                    }
19105                } catch (IOException ignored) {
19106                } finally {
19107                    IoUtils.closeQuietly(in);
19108                }
19109            }
19110
19111            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19112                BufferedReader in = null;
19113                String line = null;
19114                try {
19115                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19116                    while ((line = in.readLine()) != null) {
19117                        if (line.contains("ignored: updated version")) continue;
19118                        pw.print("msg,");
19119                        pw.println(line);
19120                    }
19121                } catch (IOException ignored) {
19122                } finally {
19123                    IoUtils.closeQuietly(in);
19124                }
19125            }
19126        }
19127    }
19128
19129    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19130        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19131        ipw.println();
19132        ipw.println("Dexopt state:");
19133        ipw.increaseIndent();
19134        Collection<PackageParser.Package> packages = null;
19135        if (packageName != null) {
19136            PackageParser.Package targetPackage = mPackages.get(packageName);
19137            if (targetPackage != null) {
19138                packages = Collections.singletonList(targetPackage);
19139            } else {
19140                ipw.println("Unable to find package: " + packageName);
19141                return;
19142            }
19143        } else {
19144            packages = mPackages.values();
19145        }
19146
19147        for (PackageParser.Package pkg : packages) {
19148            ipw.println("[" + pkg.packageName + "]");
19149            ipw.increaseIndent();
19150            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19151            ipw.decreaseIndent();
19152        }
19153    }
19154
19155    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19156        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19157        ipw.println();
19158        ipw.println("Compiler stats:");
19159        ipw.increaseIndent();
19160        Collection<PackageParser.Package> packages = null;
19161        if (packageName != null) {
19162            PackageParser.Package targetPackage = mPackages.get(packageName);
19163            if (targetPackage != null) {
19164                packages = Collections.singletonList(targetPackage);
19165            } else {
19166                ipw.println("Unable to find package: " + packageName);
19167                return;
19168            }
19169        } else {
19170            packages = mPackages.values();
19171        }
19172
19173        for (PackageParser.Package pkg : packages) {
19174            ipw.println("[" + pkg.packageName + "]");
19175            ipw.increaseIndent();
19176
19177            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19178            if (stats == null) {
19179                ipw.println("(No recorded stats)");
19180            } else {
19181                stats.dump(ipw);
19182            }
19183            ipw.decreaseIndent();
19184        }
19185    }
19186
19187    private String dumpDomainString(String packageName) {
19188        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19189                .getList();
19190        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19191
19192        ArraySet<String> result = new ArraySet<>();
19193        if (iviList.size() > 0) {
19194            for (IntentFilterVerificationInfo ivi : iviList) {
19195                for (String host : ivi.getDomains()) {
19196                    result.add(host);
19197                }
19198            }
19199        }
19200        if (filters != null && filters.size() > 0) {
19201            for (IntentFilter filter : filters) {
19202                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19203                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19204                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19205                    result.addAll(filter.getHostsList());
19206                }
19207            }
19208        }
19209
19210        StringBuilder sb = new StringBuilder(result.size() * 16);
19211        for (String domain : result) {
19212            if (sb.length() > 0) sb.append(" ");
19213            sb.append(domain);
19214        }
19215        return sb.toString();
19216    }
19217
19218    // ------- apps on sdcard specific code -------
19219    static final boolean DEBUG_SD_INSTALL = false;
19220
19221    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19222
19223    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19224
19225    private boolean mMediaMounted = false;
19226
19227    static String getEncryptKey() {
19228        try {
19229            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19230                    SD_ENCRYPTION_KEYSTORE_NAME);
19231            if (sdEncKey == null) {
19232                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19233                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19234                if (sdEncKey == null) {
19235                    Slog.e(TAG, "Failed to create encryption keys");
19236                    return null;
19237                }
19238            }
19239            return sdEncKey;
19240        } catch (NoSuchAlgorithmException nsae) {
19241            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19242            return null;
19243        } catch (IOException ioe) {
19244            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19245            return null;
19246        }
19247    }
19248
19249    /*
19250     * Update media status on PackageManager.
19251     */
19252    @Override
19253    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19254        int callingUid = Binder.getCallingUid();
19255        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19256            throw new SecurityException("Media status can only be updated by the system");
19257        }
19258        // reader; this apparently protects mMediaMounted, but should probably
19259        // be a different lock in that case.
19260        synchronized (mPackages) {
19261            Log.i(TAG, "Updating external media status from "
19262                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19263                    + (mediaStatus ? "mounted" : "unmounted"));
19264            if (DEBUG_SD_INSTALL)
19265                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19266                        + ", mMediaMounted=" + mMediaMounted);
19267            if (mediaStatus == mMediaMounted) {
19268                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19269                        : 0, -1);
19270                mHandler.sendMessage(msg);
19271                return;
19272            }
19273            mMediaMounted = mediaStatus;
19274        }
19275        // Queue up an async operation since the package installation may take a
19276        // little while.
19277        mHandler.post(new Runnable() {
19278            public void run() {
19279                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19280            }
19281        });
19282    }
19283
19284    /**
19285     * Called by MountService when the initial ASECs to scan are available.
19286     * Should block until all the ASEC containers are finished being scanned.
19287     */
19288    public void scanAvailableAsecs() {
19289        updateExternalMediaStatusInner(true, false, false);
19290    }
19291
19292    /*
19293     * Collect information of applications on external media, map them against
19294     * existing containers and update information based on current mount status.
19295     * Please note that we always have to report status if reportStatus has been
19296     * set to true especially when unloading packages.
19297     */
19298    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19299            boolean externalStorage) {
19300        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19301        int[] uidArr = EmptyArray.INT;
19302
19303        final String[] list = PackageHelper.getSecureContainerList();
19304        if (ArrayUtils.isEmpty(list)) {
19305            Log.i(TAG, "No secure containers found");
19306        } else {
19307            // Process list of secure containers and categorize them
19308            // as active or stale based on their package internal state.
19309
19310            // reader
19311            synchronized (mPackages) {
19312                for (String cid : list) {
19313                    // Leave stages untouched for now; installer service owns them
19314                    if (PackageInstallerService.isStageName(cid)) continue;
19315
19316                    if (DEBUG_SD_INSTALL)
19317                        Log.i(TAG, "Processing container " + cid);
19318                    String pkgName = getAsecPackageName(cid);
19319                    if (pkgName == null) {
19320                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19321                        continue;
19322                    }
19323                    if (DEBUG_SD_INSTALL)
19324                        Log.i(TAG, "Looking for pkg : " + pkgName);
19325
19326                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19327                    if (ps == null) {
19328                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19329                        continue;
19330                    }
19331
19332                    /*
19333                     * Skip packages that are not external if we're unmounting
19334                     * external storage.
19335                     */
19336                    if (externalStorage && !isMounted && !isExternal(ps)) {
19337                        continue;
19338                    }
19339
19340                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19341                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19342                    // The package status is changed only if the code path
19343                    // matches between settings and the container id.
19344                    if (ps.codePathString != null
19345                            && ps.codePathString.startsWith(args.getCodePath())) {
19346                        if (DEBUG_SD_INSTALL) {
19347                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19348                                    + " at code path: " + ps.codePathString);
19349                        }
19350
19351                        // We do have a valid package installed on sdcard
19352                        processCids.put(args, ps.codePathString);
19353                        final int uid = ps.appId;
19354                        if (uid != -1) {
19355                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19356                        }
19357                    } else {
19358                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19359                                + ps.codePathString);
19360                    }
19361                }
19362            }
19363
19364            Arrays.sort(uidArr);
19365        }
19366
19367        // Process packages with valid entries.
19368        if (isMounted) {
19369            if (DEBUG_SD_INSTALL)
19370                Log.i(TAG, "Loading packages");
19371            loadMediaPackages(processCids, uidArr, externalStorage);
19372            startCleaningPackages();
19373            mInstallerService.onSecureContainersAvailable();
19374        } else {
19375            if (DEBUG_SD_INSTALL)
19376                Log.i(TAG, "Unloading packages");
19377            unloadMediaPackages(processCids, uidArr, reportStatus);
19378        }
19379    }
19380
19381    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19382            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19383        final int size = infos.size();
19384        final String[] packageNames = new String[size];
19385        final int[] packageUids = new int[size];
19386        for (int i = 0; i < size; i++) {
19387            final ApplicationInfo info = infos.get(i);
19388            packageNames[i] = info.packageName;
19389            packageUids[i] = info.uid;
19390        }
19391        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19392                finishedReceiver);
19393    }
19394
19395    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19396            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19397        sendResourcesChangedBroadcast(mediaStatus, replacing,
19398                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19399    }
19400
19401    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19402            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19403        int size = pkgList.length;
19404        if (size > 0) {
19405            // Send broadcasts here
19406            Bundle extras = new Bundle();
19407            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19408            if (uidArr != null) {
19409                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19410            }
19411            if (replacing) {
19412                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19413            }
19414            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19415                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19416            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19417        }
19418    }
19419
19420   /*
19421     * Look at potentially valid container ids from processCids If package
19422     * information doesn't match the one on record or package scanning fails,
19423     * the cid is added to list of removeCids. We currently don't delete stale
19424     * containers.
19425     */
19426    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19427            boolean externalStorage) {
19428        ArrayList<String> pkgList = new ArrayList<String>();
19429        Set<AsecInstallArgs> keys = processCids.keySet();
19430
19431        for (AsecInstallArgs args : keys) {
19432            String codePath = processCids.get(args);
19433            if (DEBUG_SD_INSTALL)
19434                Log.i(TAG, "Loading container : " + args.cid);
19435            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19436            try {
19437                // Make sure there are no container errors first.
19438                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19439                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19440                            + " when installing from sdcard");
19441                    continue;
19442                }
19443                // Check code path here.
19444                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19445                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19446                            + " does not match one in settings " + codePath);
19447                    continue;
19448                }
19449                // Parse package
19450                int parseFlags = mDefParseFlags;
19451                if (args.isExternalAsec()) {
19452                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19453                }
19454                if (args.isFwdLocked()) {
19455                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19456                }
19457
19458                synchronized (mInstallLock) {
19459                    PackageParser.Package pkg = null;
19460                    try {
19461                        // Sadly we don't know the package name yet to freeze it
19462                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19463                                SCAN_IGNORE_FROZEN, 0, null);
19464                    } catch (PackageManagerException e) {
19465                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19466                    }
19467                    // Scan the package
19468                    if (pkg != null) {
19469                        /*
19470                         * TODO why is the lock being held? doPostInstall is
19471                         * called in other places without the lock. This needs
19472                         * to be straightened out.
19473                         */
19474                        // writer
19475                        synchronized (mPackages) {
19476                            retCode = PackageManager.INSTALL_SUCCEEDED;
19477                            pkgList.add(pkg.packageName);
19478                            // Post process args
19479                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19480                                    pkg.applicationInfo.uid);
19481                        }
19482                    } else {
19483                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19484                    }
19485                }
19486
19487            } finally {
19488                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19489                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19490                }
19491            }
19492        }
19493        // writer
19494        synchronized (mPackages) {
19495            // If the platform SDK has changed since the last time we booted,
19496            // we need to re-grant app permission to catch any new ones that
19497            // appear. This is really a hack, and means that apps can in some
19498            // cases get permissions that the user didn't initially explicitly
19499            // allow... it would be nice to have some better way to handle
19500            // this situation.
19501            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19502                    : mSettings.getInternalVersion();
19503            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19504                    : StorageManager.UUID_PRIVATE_INTERNAL;
19505
19506            int updateFlags = UPDATE_PERMISSIONS_ALL;
19507            if (ver.sdkVersion != mSdkVersion) {
19508                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19509                        + mSdkVersion + "; regranting permissions for external");
19510                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19511            }
19512            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19513
19514            // Yay, everything is now upgraded
19515            ver.forceCurrent();
19516
19517            // can downgrade to reader
19518            // Persist settings
19519            mSettings.writeLPr();
19520        }
19521        // Send a broadcast to let everyone know we are done processing
19522        if (pkgList.size() > 0) {
19523            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19524        }
19525    }
19526
19527   /*
19528     * Utility method to unload a list of specified containers
19529     */
19530    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19531        // Just unmount all valid containers.
19532        for (AsecInstallArgs arg : cidArgs) {
19533            synchronized (mInstallLock) {
19534                arg.doPostDeleteLI(false);
19535           }
19536       }
19537   }
19538
19539    /*
19540     * Unload packages mounted on external media. This involves deleting package
19541     * data from internal structures, sending broadcasts about disabled packages,
19542     * gc'ing to free up references, unmounting all secure containers
19543     * corresponding to packages on external media, and posting a
19544     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19545     * that we always have to post this message if status has been requested no
19546     * matter what.
19547     */
19548    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19549            final boolean reportStatus) {
19550        if (DEBUG_SD_INSTALL)
19551            Log.i(TAG, "unloading media packages");
19552        ArrayList<String> pkgList = new ArrayList<String>();
19553        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19554        final Set<AsecInstallArgs> keys = processCids.keySet();
19555        for (AsecInstallArgs args : keys) {
19556            String pkgName = args.getPackageName();
19557            if (DEBUG_SD_INSTALL)
19558                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19559            // Delete package internally
19560            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19561            synchronized (mInstallLock) {
19562                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19563                final boolean res;
19564                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19565                        "unloadMediaPackages")) {
19566                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19567                            null);
19568                }
19569                if (res) {
19570                    pkgList.add(pkgName);
19571                } else {
19572                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19573                    failedList.add(args);
19574                }
19575            }
19576        }
19577
19578        // reader
19579        synchronized (mPackages) {
19580            // We didn't update the settings after removing each package;
19581            // write them now for all packages.
19582            mSettings.writeLPr();
19583        }
19584
19585        // We have to absolutely send UPDATED_MEDIA_STATUS only
19586        // after confirming that all the receivers processed the ordered
19587        // broadcast when packages get disabled, force a gc to clean things up.
19588        // and unload all the containers.
19589        if (pkgList.size() > 0) {
19590            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19591                    new IIntentReceiver.Stub() {
19592                public void performReceive(Intent intent, int resultCode, String data,
19593                        Bundle extras, boolean ordered, boolean sticky,
19594                        int sendingUser) throws RemoteException {
19595                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19596                            reportStatus ? 1 : 0, 1, keys);
19597                    mHandler.sendMessage(msg);
19598                }
19599            });
19600        } else {
19601            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19602                    keys);
19603            mHandler.sendMessage(msg);
19604        }
19605    }
19606
19607    private void loadPrivatePackages(final VolumeInfo vol) {
19608        mHandler.post(new Runnable() {
19609            @Override
19610            public void run() {
19611                loadPrivatePackagesInner(vol);
19612            }
19613        });
19614    }
19615
19616    private void loadPrivatePackagesInner(VolumeInfo vol) {
19617        final String volumeUuid = vol.fsUuid;
19618        if (TextUtils.isEmpty(volumeUuid)) {
19619            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19620            return;
19621        }
19622
19623        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19624        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19625        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19626
19627        final VersionInfo ver;
19628        final List<PackageSetting> packages;
19629        synchronized (mPackages) {
19630            ver = mSettings.findOrCreateVersion(volumeUuid);
19631            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19632        }
19633
19634        for (PackageSetting ps : packages) {
19635            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19636            synchronized (mInstallLock) {
19637                final PackageParser.Package pkg;
19638                try {
19639                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19640                    loaded.add(pkg.applicationInfo);
19641
19642                } catch (PackageManagerException e) {
19643                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19644                }
19645
19646                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19647                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19648                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19649                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19650                }
19651            }
19652        }
19653
19654        // Reconcile app data for all started/unlocked users
19655        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19656        final UserManager um = mContext.getSystemService(UserManager.class);
19657        UserManagerInternal umInternal = getUserManagerInternal();
19658        for (UserInfo user : um.getUsers()) {
19659            final int flags;
19660            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19661                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19662            } else if (umInternal.isUserRunning(user.id)) {
19663                flags = StorageManager.FLAG_STORAGE_DE;
19664            } else {
19665                continue;
19666            }
19667
19668            try {
19669                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19670                synchronized (mInstallLock) {
19671                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19672                }
19673            } catch (IllegalStateException e) {
19674                // Device was probably ejected, and we'll process that event momentarily
19675                Slog.w(TAG, "Failed to prepare storage: " + e);
19676            }
19677        }
19678
19679        synchronized (mPackages) {
19680            int updateFlags = UPDATE_PERMISSIONS_ALL;
19681            if (ver.sdkVersion != mSdkVersion) {
19682                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19683                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19684                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19685            }
19686            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19687
19688            // Yay, everything is now upgraded
19689            ver.forceCurrent();
19690
19691            mSettings.writeLPr();
19692        }
19693
19694        for (PackageFreezer freezer : freezers) {
19695            freezer.close();
19696        }
19697
19698        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19699        sendResourcesChangedBroadcast(true, false, loaded, null);
19700    }
19701
19702    private void unloadPrivatePackages(final VolumeInfo vol) {
19703        mHandler.post(new Runnable() {
19704            @Override
19705            public void run() {
19706                unloadPrivatePackagesInner(vol);
19707            }
19708        });
19709    }
19710
19711    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19712        final String volumeUuid = vol.fsUuid;
19713        if (TextUtils.isEmpty(volumeUuid)) {
19714            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19715            return;
19716        }
19717
19718        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19719        synchronized (mInstallLock) {
19720        synchronized (mPackages) {
19721            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19722            for (PackageSetting ps : packages) {
19723                if (ps.pkg == null) continue;
19724
19725                final ApplicationInfo info = ps.pkg.applicationInfo;
19726                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19727                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19728
19729                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19730                        "unloadPrivatePackagesInner")) {
19731                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19732                            false, null)) {
19733                        unloaded.add(info);
19734                    } else {
19735                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19736                    }
19737                }
19738
19739                // Try very hard to release any references to this package
19740                // so we don't risk the system server being killed due to
19741                // open FDs
19742                AttributeCache.instance().removePackage(ps.name);
19743            }
19744
19745            mSettings.writeLPr();
19746        }
19747        }
19748
19749        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19750        sendResourcesChangedBroadcast(false, false, unloaded, null);
19751
19752        // Try very hard to release any references to this path so we don't risk
19753        // the system server being killed due to open FDs
19754        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19755
19756        for (int i = 0; i < 3; i++) {
19757            System.gc();
19758            System.runFinalization();
19759        }
19760    }
19761
19762    /**
19763     * Prepare storage areas for given user on all mounted devices.
19764     */
19765    void prepareUserData(int userId, int userSerial, int flags) {
19766        synchronized (mInstallLock) {
19767            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19768            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19769                final String volumeUuid = vol.getFsUuid();
19770                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19771            }
19772        }
19773    }
19774
19775    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19776            boolean allowRecover) {
19777        // Prepare storage and verify that serial numbers are consistent; if
19778        // there's a mismatch we need to destroy to avoid leaking data
19779        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19780        try {
19781            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19782
19783            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19784                UserManagerService.enforceSerialNumber(
19785                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19786                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19787                    UserManagerService.enforceSerialNumber(
19788                            Environment.getDataSystemDeDirectory(userId), userSerial);
19789                }
19790            }
19791            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19792                UserManagerService.enforceSerialNumber(
19793                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19794                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19795                    UserManagerService.enforceSerialNumber(
19796                            Environment.getDataSystemCeDirectory(userId), userSerial);
19797                }
19798            }
19799
19800            synchronized (mInstallLock) {
19801                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19802            }
19803        } catch (Exception e) {
19804            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19805                    + " because we failed to prepare: " + e);
19806            destroyUserDataLI(volumeUuid, userId,
19807                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19808
19809            if (allowRecover) {
19810                // Try one last time; if we fail again we're really in trouble
19811                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19812            }
19813        }
19814    }
19815
19816    /**
19817     * Destroy storage areas for given user on all mounted devices.
19818     */
19819    void destroyUserData(int userId, int flags) {
19820        synchronized (mInstallLock) {
19821            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19822            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19823                final String volumeUuid = vol.getFsUuid();
19824                destroyUserDataLI(volumeUuid, userId, flags);
19825            }
19826        }
19827    }
19828
19829    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19830        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19831        try {
19832            // Clean up app data, profile data, and media data
19833            mInstaller.destroyUserData(volumeUuid, userId, flags);
19834
19835            // Clean up system data
19836            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19837                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19838                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19839                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19840                }
19841                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19842                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19843                }
19844            }
19845
19846            // Data with special labels is now gone, so finish the job
19847            storage.destroyUserStorage(volumeUuid, userId, flags);
19848
19849        } catch (Exception e) {
19850            logCriticalInfo(Log.WARN,
19851                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19852        }
19853    }
19854
19855    /**
19856     * Examine all users present on given mounted volume, and destroy data
19857     * belonging to users that are no longer valid, or whose user ID has been
19858     * recycled.
19859     */
19860    private void reconcileUsers(String volumeUuid) {
19861        final List<File> files = new ArrayList<>();
19862        Collections.addAll(files, FileUtils
19863                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19864        Collections.addAll(files, FileUtils
19865                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19866        Collections.addAll(files, FileUtils
19867                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19868        Collections.addAll(files, FileUtils
19869                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19870        for (File file : files) {
19871            if (!file.isDirectory()) continue;
19872
19873            final int userId;
19874            final UserInfo info;
19875            try {
19876                userId = Integer.parseInt(file.getName());
19877                info = sUserManager.getUserInfo(userId);
19878            } catch (NumberFormatException e) {
19879                Slog.w(TAG, "Invalid user directory " + file);
19880                continue;
19881            }
19882
19883            boolean destroyUser = false;
19884            if (info == null) {
19885                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19886                        + " because no matching user was found");
19887                destroyUser = true;
19888            } else if (!mOnlyCore) {
19889                try {
19890                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19891                } catch (IOException e) {
19892                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19893                            + " because we failed to enforce serial number: " + e);
19894                    destroyUser = true;
19895                }
19896            }
19897
19898            if (destroyUser) {
19899                synchronized (mInstallLock) {
19900                    destroyUserDataLI(volumeUuid, userId,
19901                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19902                }
19903            }
19904        }
19905    }
19906
19907    private void assertPackageKnown(String volumeUuid, String packageName)
19908            throws PackageManagerException {
19909        synchronized (mPackages) {
19910            final PackageSetting ps = mSettings.mPackages.get(packageName);
19911            if (ps == null) {
19912                throw new PackageManagerException("Package " + packageName + " is unknown");
19913            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19914                throw new PackageManagerException(
19915                        "Package " + packageName + " found on unknown volume " + volumeUuid
19916                                + "; expected volume " + ps.volumeUuid);
19917            }
19918        }
19919    }
19920
19921    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19922            throws PackageManagerException {
19923        synchronized (mPackages) {
19924            final PackageSetting ps = mSettings.mPackages.get(packageName);
19925            if (ps == null) {
19926                throw new PackageManagerException("Package " + packageName + " is unknown");
19927            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19928                throw new PackageManagerException(
19929                        "Package " + packageName + " found on unknown volume " + volumeUuid
19930                                + "; expected volume " + ps.volumeUuid);
19931            } else if (!ps.getInstalled(userId)) {
19932                throw new PackageManagerException(
19933                        "Package " + packageName + " not installed for user " + userId);
19934            }
19935        }
19936    }
19937
19938    /**
19939     * Examine all apps present on given mounted volume, and destroy apps that
19940     * aren't expected, either due to uninstallation or reinstallation on
19941     * another volume.
19942     */
19943    private void reconcileApps(String volumeUuid) {
19944        final File[] files = FileUtils
19945                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19946        for (File file : files) {
19947            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19948                    && !PackageInstallerService.isStageName(file.getName());
19949            if (!isPackage) {
19950                // Ignore entries which are not packages
19951                continue;
19952            }
19953
19954            try {
19955                final PackageLite pkg = PackageParser.parsePackageLite(file,
19956                        PackageParser.PARSE_MUST_BE_APK);
19957                assertPackageKnown(volumeUuid, pkg.packageName);
19958
19959            } catch (PackageParserException | PackageManagerException e) {
19960                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19961                synchronized (mInstallLock) {
19962                    removeCodePathLI(file);
19963                }
19964            }
19965        }
19966    }
19967
19968    /**
19969     * Reconcile all app data for the given user.
19970     * <p>
19971     * Verifies that directories exist and that ownership and labeling is
19972     * correct for all installed apps on all mounted volumes.
19973     */
19974    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19975        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19976        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19977            final String volumeUuid = vol.getFsUuid();
19978            synchronized (mInstallLock) {
19979                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19980            }
19981        }
19982    }
19983
19984    /**
19985     * Reconcile all app data on given mounted volume.
19986     * <p>
19987     * Destroys app data that isn't expected, either due to uninstallation or
19988     * reinstallation on another volume.
19989     * <p>
19990     * Verifies that directories exist and that ownership and labeling is
19991     * correct for all installed apps.
19992     */
19993    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19994            boolean migrateAppData) {
19995        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19996                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19997
19998        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19999        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20000
20001        // First look for stale data that doesn't belong, and check if things
20002        // have changed since we did our last restorecon
20003        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20004            if (StorageManager.isFileEncryptedNativeOrEmulated()
20005                    && !StorageManager.isUserKeyUnlocked(userId)) {
20006                throw new RuntimeException(
20007                        "Yikes, someone asked us to reconcile CE storage while " + userId
20008                                + " was still locked; this would have caused massive data loss!");
20009            }
20010
20011            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20012            for (File file : files) {
20013                final String packageName = file.getName();
20014                try {
20015                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20016                } catch (PackageManagerException e) {
20017                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20018                    try {
20019                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20020                                StorageManager.FLAG_STORAGE_CE, 0);
20021                    } catch (InstallerException e2) {
20022                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20023                    }
20024                }
20025            }
20026        }
20027        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20028            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20029            for (File file : files) {
20030                final String packageName = file.getName();
20031                try {
20032                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20033                } catch (PackageManagerException e) {
20034                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20035                    try {
20036                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20037                                StorageManager.FLAG_STORAGE_DE, 0);
20038                    } catch (InstallerException e2) {
20039                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20040                    }
20041                }
20042            }
20043        }
20044
20045        // Ensure that data directories are ready to roll for all packages
20046        // installed for this volume and user
20047        final List<PackageSetting> packages;
20048        synchronized (mPackages) {
20049            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20050        }
20051        int preparedCount = 0;
20052        for (PackageSetting ps : packages) {
20053            final String packageName = ps.name;
20054            if (ps.pkg == null) {
20055                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20056                // TODO: might be due to legacy ASEC apps; we should circle back
20057                // and reconcile again once they're scanned
20058                continue;
20059            }
20060
20061            if (ps.getInstalled(userId)) {
20062                prepareAppDataLIF(ps.pkg, userId, flags);
20063
20064                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20065                    // We may have just shuffled around app data directories, so
20066                    // prepare them one more time
20067                    prepareAppDataLIF(ps.pkg, userId, flags);
20068                }
20069
20070                preparedCount++;
20071            }
20072        }
20073
20074        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20075    }
20076
20077    /**
20078     * Prepare app data for the given app just after it was installed or
20079     * upgraded. This method carefully only touches users that it's installed
20080     * for, and it forces a restorecon to handle any seinfo changes.
20081     * <p>
20082     * Verifies that directories exist and that ownership and labeling is
20083     * correct for all installed apps. If there is an ownership mismatch, it
20084     * will try recovering system apps by wiping data; third-party app data is
20085     * left intact.
20086     * <p>
20087     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20088     */
20089    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20090        final PackageSetting ps;
20091        synchronized (mPackages) {
20092            ps = mSettings.mPackages.get(pkg.packageName);
20093            mSettings.writeKernelMappingLPr(ps);
20094        }
20095
20096        final UserManager um = mContext.getSystemService(UserManager.class);
20097        UserManagerInternal umInternal = getUserManagerInternal();
20098        for (UserInfo user : um.getUsers()) {
20099            final int flags;
20100            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20101                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20102            } else if (umInternal.isUserRunning(user.id)) {
20103                flags = StorageManager.FLAG_STORAGE_DE;
20104            } else {
20105                continue;
20106            }
20107
20108            if (ps.getInstalled(user.id)) {
20109                // TODO: when user data is locked, mark that we're still dirty
20110                prepareAppDataLIF(pkg, user.id, flags);
20111            }
20112        }
20113    }
20114
20115    /**
20116     * Prepare app data for the given app.
20117     * <p>
20118     * Verifies that directories exist and that ownership and labeling is
20119     * correct for all installed apps. If there is an ownership mismatch, this
20120     * will try recovering system apps by wiping data; third-party app data is
20121     * left intact.
20122     */
20123    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20124        if (pkg == null) {
20125            Slog.wtf(TAG, "Package was null!", new Throwable());
20126            return;
20127        }
20128        prepareAppDataLeafLIF(pkg, userId, flags);
20129        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20130        for (int i = 0; i < childCount; i++) {
20131            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20132        }
20133    }
20134
20135    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20136        if (DEBUG_APP_DATA) {
20137            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20138                    + Integer.toHexString(flags));
20139        }
20140
20141        final String volumeUuid = pkg.volumeUuid;
20142        final String packageName = pkg.packageName;
20143        final ApplicationInfo app = pkg.applicationInfo;
20144        final int appId = UserHandle.getAppId(app.uid);
20145
20146        Preconditions.checkNotNull(app.seinfo);
20147
20148        try {
20149            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20150                    appId, app.seinfo, app.targetSdkVersion);
20151        } catch (InstallerException e) {
20152            if (app.isSystemApp()) {
20153                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20154                        + ", but trying to recover: " + e);
20155                destroyAppDataLeafLIF(pkg, userId, flags);
20156                try {
20157                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20158                            appId, app.seinfo, app.targetSdkVersion);
20159                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20160                } catch (InstallerException e2) {
20161                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20162                }
20163            } else {
20164                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20165            }
20166        }
20167
20168        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20169            try {
20170                // CE storage is unlocked right now, so read out the inode and
20171                // remember for use later when it's locked
20172                // TODO: mark this structure as dirty so we persist it!
20173                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20174                        StorageManager.FLAG_STORAGE_CE);
20175                synchronized (mPackages) {
20176                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20177                    if (ps != null) {
20178                        ps.setCeDataInode(ceDataInode, userId);
20179                    }
20180                }
20181            } catch (InstallerException e) {
20182                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20183            }
20184        }
20185
20186        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20187    }
20188
20189    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20190        if (pkg == null) {
20191            Slog.wtf(TAG, "Package was null!", new Throwable());
20192            return;
20193        }
20194        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20195        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20196        for (int i = 0; i < childCount; i++) {
20197            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20198        }
20199    }
20200
20201    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20202        final String volumeUuid = pkg.volumeUuid;
20203        final String packageName = pkg.packageName;
20204        final ApplicationInfo app = pkg.applicationInfo;
20205
20206        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20207            // Create a native library symlink only if we have native libraries
20208            // and if the native libraries are 32 bit libraries. We do not provide
20209            // this symlink for 64 bit libraries.
20210            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20211                final String nativeLibPath = app.nativeLibraryDir;
20212                try {
20213                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20214                            nativeLibPath, userId);
20215                } catch (InstallerException e) {
20216                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20217                }
20218            }
20219        }
20220    }
20221
20222    /**
20223     * For system apps on non-FBE devices, this method migrates any existing
20224     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20225     * requested by the app.
20226     */
20227    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20228        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20229                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20230            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20231                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20232            try {
20233                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20234                        storageTarget);
20235            } catch (InstallerException e) {
20236                logCriticalInfo(Log.WARN,
20237                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20238            }
20239            return true;
20240        } else {
20241            return false;
20242        }
20243    }
20244
20245    public PackageFreezer freezePackage(String packageName, String killReason) {
20246        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20247    }
20248
20249    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20250        return new PackageFreezer(packageName, userId, killReason);
20251    }
20252
20253    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20254            String killReason) {
20255        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20256    }
20257
20258    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20259            String killReason) {
20260        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20261            return new PackageFreezer();
20262        } else {
20263            return freezePackage(packageName, userId, killReason);
20264        }
20265    }
20266
20267    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20268            String killReason) {
20269        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20270    }
20271
20272    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20273            String killReason) {
20274        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20275            return new PackageFreezer();
20276        } else {
20277            return freezePackage(packageName, userId, killReason);
20278        }
20279    }
20280
20281    /**
20282     * Class that freezes and kills the given package upon creation, and
20283     * unfreezes it upon closing. This is typically used when doing surgery on
20284     * app code/data to prevent the app from running while you're working.
20285     */
20286    private class PackageFreezer implements AutoCloseable {
20287        private final String mPackageName;
20288        private final PackageFreezer[] mChildren;
20289
20290        private final boolean mWeFroze;
20291
20292        private final AtomicBoolean mClosed = new AtomicBoolean();
20293        private final CloseGuard mCloseGuard = CloseGuard.get();
20294
20295        /**
20296         * Create and return a stub freezer that doesn't actually do anything,
20297         * typically used when someone requested
20298         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20299         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20300         */
20301        public PackageFreezer() {
20302            mPackageName = null;
20303            mChildren = null;
20304            mWeFroze = false;
20305            mCloseGuard.open("close");
20306        }
20307
20308        public PackageFreezer(String packageName, int userId, String killReason) {
20309            synchronized (mPackages) {
20310                mPackageName = packageName;
20311                mWeFroze = mFrozenPackages.add(mPackageName);
20312
20313                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20314                if (ps != null) {
20315                    killApplication(ps.name, ps.appId, userId, killReason);
20316                }
20317
20318                final PackageParser.Package p = mPackages.get(packageName);
20319                if (p != null && p.childPackages != null) {
20320                    final int N = p.childPackages.size();
20321                    mChildren = new PackageFreezer[N];
20322                    for (int i = 0; i < N; i++) {
20323                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20324                                userId, killReason);
20325                    }
20326                } else {
20327                    mChildren = null;
20328                }
20329            }
20330            mCloseGuard.open("close");
20331        }
20332
20333        @Override
20334        protected void finalize() throws Throwable {
20335            try {
20336                mCloseGuard.warnIfOpen();
20337                close();
20338            } finally {
20339                super.finalize();
20340            }
20341        }
20342
20343        @Override
20344        public void close() {
20345            mCloseGuard.close();
20346            if (mClosed.compareAndSet(false, true)) {
20347                synchronized (mPackages) {
20348                    if (mWeFroze) {
20349                        mFrozenPackages.remove(mPackageName);
20350                    }
20351
20352                    if (mChildren != null) {
20353                        for (PackageFreezer freezer : mChildren) {
20354                            freezer.close();
20355                        }
20356                    }
20357                }
20358            }
20359        }
20360    }
20361
20362    /**
20363     * Verify that given package is currently frozen.
20364     */
20365    private void checkPackageFrozen(String packageName) {
20366        synchronized (mPackages) {
20367            if (!mFrozenPackages.contains(packageName)) {
20368                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20369            }
20370        }
20371    }
20372
20373    @Override
20374    public int movePackage(final String packageName, final String volumeUuid) {
20375        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20376
20377        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20378        final int moveId = mNextMoveId.getAndIncrement();
20379        mHandler.post(new Runnable() {
20380            @Override
20381            public void run() {
20382                try {
20383                    movePackageInternal(packageName, volumeUuid, moveId, user);
20384                } catch (PackageManagerException e) {
20385                    Slog.w(TAG, "Failed to move " + packageName, e);
20386                    mMoveCallbacks.notifyStatusChanged(moveId,
20387                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20388                }
20389            }
20390        });
20391        return moveId;
20392    }
20393
20394    private void movePackageInternal(final String packageName, final String volumeUuid,
20395            final int moveId, UserHandle user) throws PackageManagerException {
20396        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20397        final PackageManager pm = mContext.getPackageManager();
20398
20399        final boolean currentAsec;
20400        final String currentVolumeUuid;
20401        final File codeFile;
20402        final String installerPackageName;
20403        final String packageAbiOverride;
20404        final int appId;
20405        final String seinfo;
20406        final String label;
20407        final int targetSdkVersion;
20408        final PackageFreezer freezer;
20409        final int[] installedUserIds;
20410
20411        // reader
20412        synchronized (mPackages) {
20413            final PackageParser.Package pkg = mPackages.get(packageName);
20414            final PackageSetting ps = mSettings.mPackages.get(packageName);
20415            if (pkg == null || ps == null) {
20416                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20417            }
20418
20419            if (pkg.applicationInfo.isSystemApp()) {
20420                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20421                        "Cannot move system application");
20422            }
20423
20424            if (pkg.applicationInfo.isExternalAsec()) {
20425                currentAsec = true;
20426                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20427            } else if (pkg.applicationInfo.isForwardLocked()) {
20428                currentAsec = true;
20429                currentVolumeUuid = "forward_locked";
20430            } else {
20431                currentAsec = false;
20432                currentVolumeUuid = ps.volumeUuid;
20433
20434                final File probe = new File(pkg.codePath);
20435                final File probeOat = new File(probe, "oat");
20436                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20437                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20438                            "Move only supported for modern cluster style installs");
20439                }
20440            }
20441
20442            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20443                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20444                        "Package already moved to " + volumeUuid);
20445            }
20446            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20447                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20448                        "Device admin cannot be moved");
20449            }
20450
20451            if (mFrozenPackages.contains(packageName)) {
20452                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20453                        "Failed to move already frozen package");
20454            }
20455
20456            codeFile = new File(pkg.codePath);
20457            installerPackageName = ps.installerPackageName;
20458            packageAbiOverride = ps.cpuAbiOverrideString;
20459            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20460            seinfo = pkg.applicationInfo.seinfo;
20461            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20462            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20463            freezer = freezePackage(packageName, "movePackageInternal");
20464            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20465        }
20466
20467        final Bundle extras = new Bundle();
20468        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20469        extras.putString(Intent.EXTRA_TITLE, label);
20470        mMoveCallbacks.notifyCreated(moveId, extras);
20471
20472        int installFlags;
20473        final boolean moveCompleteApp;
20474        final File measurePath;
20475
20476        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20477            installFlags = INSTALL_INTERNAL;
20478            moveCompleteApp = !currentAsec;
20479            measurePath = Environment.getDataAppDirectory(volumeUuid);
20480        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20481            installFlags = INSTALL_EXTERNAL;
20482            moveCompleteApp = false;
20483            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20484        } else {
20485            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20486            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20487                    || !volume.isMountedWritable()) {
20488                freezer.close();
20489                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20490                        "Move location not mounted private volume");
20491            }
20492
20493            Preconditions.checkState(!currentAsec);
20494
20495            installFlags = INSTALL_INTERNAL;
20496            moveCompleteApp = true;
20497            measurePath = Environment.getDataAppDirectory(volumeUuid);
20498        }
20499
20500        final PackageStats stats = new PackageStats(null, -1);
20501        synchronized (mInstaller) {
20502            for (int userId : installedUserIds) {
20503                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20504                    freezer.close();
20505                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20506                            "Failed to measure package size");
20507                }
20508            }
20509        }
20510
20511        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20512                + stats.dataSize);
20513
20514        final long startFreeBytes = measurePath.getFreeSpace();
20515        final long sizeBytes;
20516        if (moveCompleteApp) {
20517            sizeBytes = stats.codeSize + stats.dataSize;
20518        } else {
20519            sizeBytes = stats.codeSize;
20520        }
20521
20522        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20523            freezer.close();
20524            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20525                    "Not enough free space to move");
20526        }
20527
20528        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20529
20530        final CountDownLatch installedLatch = new CountDownLatch(1);
20531        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20532            @Override
20533            public void onUserActionRequired(Intent intent) throws RemoteException {
20534                throw new IllegalStateException();
20535            }
20536
20537            @Override
20538            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20539                    Bundle extras) throws RemoteException {
20540                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20541                        + PackageManager.installStatusToString(returnCode, msg));
20542
20543                installedLatch.countDown();
20544                freezer.close();
20545
20546                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20547                switch (status) {
20548                    case PackageInstaller.STATUS_SUCCESS:
20549                        mMoveCallbacks.notifyStatusChanged(moveId,
20550                                PackageManager.MOVE_SUCCEEDED);
20551                        break;
20552                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20553                        mMoveCallbacks.notifyStatusChanged(moveId,
20554                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20555                        break;
20556                    default:
20557                        mMoveCallbacks.notifyStatusChanged(moveId,
20558                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20559                        break;
20560                }
20561            }
20562        };
20563
20564        final MoveInfo move;
20565        if (moveCompleteApp) {
20566            // Kick off a thread to report progress estimates
20567            new Thread() {
20568                @Override
20569                public void run() {
20570                    while (true) {
20571                        try {
20572                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20573                                break;
20574                            }
20575                        } catch (InterruptedException ignored) {
20576                        }
20577
20578                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20579                        final int progress = 10 + (int) MathUtils.constrain(
20580                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20581                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20582                    }
20583                }
20584            }.start();
20585
20586            final String dataAppName = codeFile.getName();
20587            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20588                    dataAppName, appId, seinfo, targetSdkVersion);
20589        } else {
20590            move = null;
20591        }
20592
20593        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20594
20595        final Message msg = mHandler.obtainMessage(INIT_COPY);
20596        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20597        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20598                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20599                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20600        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20601        msg.obj = params;
20602
20603        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20604                System.identityHashCode(msg.obj));
20605        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20606                System.identityHashCode(msg.obj));
20607
20608        mHandler.sendMessage(msg);
20609    }
20610
20611    @Override
20612    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20613        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20614
20615        final int realMoveId = mNextMoveId.getAndIncrement();
20616        final Bundle extras = new Bundle();
20617        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20618        mMoveCallbacks.notifyCreated(realMoveId, extras);
20619
20620        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20621            @Override
20622            public void onCreated(int moveId, Bundle extras) {
20623                // Ignored
20624            }
20625
20626            @Override
20627            public void onStatusChanged(int moveId, int status, long estMillis) {
20628                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20629            }
20630        };
20631
20632        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20633        storage.setPrimaryStorageUuid(volumeUuid, callback);
20634        return realMoveId;
20635    }
20636
20637    @Override
20638    public int getMoveStatus(int moveId) {
20639        mContext.enforceCallingOrSelfPermission(
20640                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20641        return mMoveCallbacks.mLastStatus.get(moveId);
20642    }
20643
20644    @Override
20645    public void registerMoveCallback(IPackageMoveObserver callback) {
20646        mContext.enforceCallingOrSelfPermission(
20647                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20648        mMoveCallbacks.register(callback);
20649    }
20650
20651    @Override
20652    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20653        mContext.enforceCallingOrSelfPermission(
20654                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20655        mMoveCallbacks.unregister(callback);
20656    }
20657
20658    @Override
20659    public boolean setInstallLocation(int loc) {
20660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20661                null);
20662        if (getInstallLocation() == loc) {
20663            return true;
20664        }
20665        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20666                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20667            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20668                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20669            return true;
20670        }
20671        return false;
20672   }
20673
20674    @Override
20675    public int getInstallLocation() {
20676        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20677                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20678                PackageHelper.APP_INSTALL_AUTO);
20679    }
20680
20681    /** Called by UserManagerService */
20682    void cleanUpUser(UserManagerService userManager, int userHandle) {
20683        synchronized (mPackages) {
20684            mDirtyUsers.remove(userHandle);
20685            mUserNeedsBadging.delete(userHandle);
20686            mSettings.removeUserLPw(userHandle);
20687            mPendingBroadcasts.remove(userHandle);
20688            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20689            removeUnusedPackagesLPw(userManager, userHandle);
20690        }
20691    }
20692
20693    /**
20694     * We're removing userHandle and would like to remove any downloaded packages
20695     * that are no longer in use by any other user.
20696     * @param userHandle the user being removed
20697     */
20698    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20699        final boolean DEBUG_CLEAN_APKS = false;
20700        int [] users = userManager.getUserIds();
20701        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20702        while (psit.hasNext()) {
20703            PackageSetting ps = psit.next();
20704            if (ps.pkg == null) {
20705                continue;
20706            }
20707            final String packageName = ps.pkg.packageName;
20708            // Skip over if system app
20709            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20710                continue;
20711            }
20712            if (DEBUG_CLEAN_APKS) {
20713                Slog.i(TAG, "Checking package " + packageName);
20714            }
20715            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20716            if (keep) {
20717                if (DEBUG_CLEAN_APKS) {
20718                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20719                }
20720            } else {
20721                for (int i = 0; i < users.length; i++) {
20722                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20723                        keep = true;
20724                        if (DEBUG_CLEAN_APKS) {
20725                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20726                                    + users[i]);
20727                        }
20728                        break;
20729                    }
20730                }
20731            }
20732            if (!keep) {
20733                if (DEBUG_CLEAN_APKS) {
20734                    Slog.i(TAG, "  Removing package " + packageName);
20735                }
20736                mHandler.post(new Runnable() {
20737                    public void run() {
20738                        deletePackageX(packageName, userHandle, 0);
20739                    } //end run
20740                });
20741            }
20742        }
20743    }
20744
20745    /** Called by UserManagerService */
20746    void createNewUser(int userId, String[] disallowedPackages) {
20747        synchronized (mInstallLock) {
20748            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20749        }
20750        synchronized (mPackages) {
20751            scheduleWritePackageRestrictionsLocked(userId);
20752            scheduleWritePackageListLocked(userId);
20753            applyFactoryDefaultBrowserLPw(userId);
20754            primeDomainVerificationsLPw(userId);
20755        }
20756    }
20757
20758    void onNewUserCreated(final int userId) {
20759        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20760        // If permission review for legacy apps is required, we represent
20761        // dagerous permissions for such apps as always granted runtime
20762        // permissions to keep per user flag state whether review is needed.
20763        // Hence, if a new user is added we have to propagate dangerous
20764        // permission grants for these legacy apps.
20765        if (mPermissionReviewRequired) {
20766            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20767                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20768        }
20769    }
20770
20771    @Override
20772    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20773        mContext.enforceCallingOrSelfPermission(
20774                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20775                "Only package verification agents can read the verifier device identity");
20776
20777        synchronized (mPackages) {
20778            return mSettings.getVerifierDeviceIdentityLPw();
20779        }
20780    }
20781
20782    @Override
20783    public void setPermissionEnforced(String permission, boolean enforced) {
20784        // TODO: Now that we no longer change GID for storage, this should to away.
20785        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20786                "setPermissionEnforced");
20787        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20788            synchronized (mPackages) {
20789                if (mSettings.mReadExternalStorageEnforced == null
20790                        || mSettings.mReadExternalStorageEnforced != enforced) {
20791                    mSettings.mReadExternalStorageEnforced = enforced;
20792                    mSettings.writeLPr();
20793                }
20794            }
20795            // kill any non-foreground processes so we restart them and
20796            // grant/revoke the GID.
20797            final IActivityManager am = ActivityManagerNative.getDefault();
20798            if (am != null) {
20799                final long token = Binder.clearCallingIdentity();
20800                try {
20801                    am.killProcessesBelowForeground("setPermissionEnforcement");
20802                } catch (RemoteException e) {
20803                } finally {
20804                    Binder.restoreCallingIdentity(token);
20805                }
20806            }
20807        } else {
20808            throw new IllegalArgumentException("No selective enforcement for " + permission);
20809        }
20810    }
20811
20812    @Override
20813    @Deprecated
20814    public boolean isPermissionEnforced(String permission) {
20815        return true;
20816    }
20817
20818    @Override
20819    public boolean isStorageLow() {
20820        final long token = Binder.clearCallingIdentity();
20821        try {
20822            final DeviceStorageMonitorInternal
20823                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20824            if (dsm != null) {
20825                return dsm.isMemoryLow();
20826            } else {
20827                return false;
20828            }
20829        } finally {
20830            Binder.restoreCallingIdentity(token);
20831        }
20832    }
20833
20834    @Override
20835    public IPackageInstaller getPackageInstaller() {
20836        return mInstallerService;
20837    }
20838
20839    private boolean userNeedsBadging(int userId) {
20840        int index = mUserNeedsBadging.indexOfKey(userId);
20841        if (index < 0) {
20842            final UserInfo userInfo;
20843            final long token = Binder.clearCallingIdentity();
20844            try {
20845                userInfo = sUserManager.getUserInfo(userId);
20846            } finally {
20847                Binder.restoreCallingIdentity(token);
20848            }
20849            final boolean b;
20850            if (userInfo != null && userInfo.isManagedProfile()) {
20851                b = true;
20852            } else {
20853                b = false;
20854            }
20855            mUserNeedsBadging.put(userId, b);
20856            return b;
20857        }
20858        return mUserNeedsBadging.valueAt(index);
20859    }
20860
20861    @Override
20862    public KeySet getKeySetByAlias(String packageName, String alias) {
20863        if (packageName == null || alias == null) {
20864            return null;
20865        }
20866        synchronized(mPackages) {
20867            final PackageParser.Package pkg = mPackages.get(packageName);
20868            if (pkg == null) {
20869                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20870                throw new IllegalArgumentException("Unknown package: " + packageName);
20871            }
20872            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20873            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20874        }
20875    }
20876
20877    @Override
20878    public KeySet getSigningKeySet(String packageName) {
20879        if (packageName == null) {
20880            return null;
20881        }
20882        synchronized(mPackages) {
20883            final PackageParser.Package pkg = mPackages.get(packageName);
20884            if (pkg == null) {
20885                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20886                throw new IllegalArgumentException("Unknown package: " + packageName);
20887            }
20888            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20889                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20890                throw new SecurityException("May not access signing KeySet of other apps.");
20891            }
20892            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20893            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20894        }
20895    }
20896
20897    @Override
20898    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20899        if (packageName == null || ks == null) {
20900            return false;
20901        }
20902        synchronized(mPackages) {
20903            final PackageParser.Package pkg = mPackages.get(packageName);
20904            if (pkg == null) {
20905                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20906                throw new IllegalArgumentException("Unknown package: " + packageName);
20907            }
20908            IBinder ksh = ks.getToken();
20909            if (ksh instanceof KeySetHandle) {
20910                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20911                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20912            }
20913            return false;
20914        }
20915    }
20916
20917    @Override
20918    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20919        if (packageName == null || ks == null) {
20920            return false;
20921        }
20922        synchronized(mPackages) {
20923            final PackageParser.Package pkg = mPackages.get(packageName);
20924            if (pkg == null) {
20925                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20926                throw new IllegalArgumentException("Unknown package: " + packageName);
20927            }
20928            IBinder ksh = ks.getToken();
20929            if (ksh instanceof KeySetHandle) {
20930                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20931                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20932            }
20933            return false;
20934        }
20935    }
20936
20937    private void deletePackageIfUnusedLPr(final String packageName) {
20938        PackageSetting ps = mSettings.mPackages.get(packageName);
20939        if (ps == null) {
20940            return;
20941        }
20942        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20943            // TODO Implement atomic delete if package is unused
20944            // It is currently possible that the package will be deleted even if it is installed
20945            // after this method returns.
20946            mHandler.post(new Runnable() {
20947                public void run() {
20948                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20949                }
20950            });
20951        }
20952    }
20953
20954    /**
20955     * Check and throw if the given before/after packages would be considered a
20956     * downgrade.
20957     */
20958    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20959            throws PackageManagerException {
20960        if (after.versionCode < before.mVersionCode) {
20961            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20962                    "Update version code " + after.versionCode + " is older than current "
20963                    + before.mVersionCode);
20964        } else if (after.versionCode == before.mVersionCode) {
20965            if (after.baseRevisionCode < before.baseRevisionCode) {
20966                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20967                        "Update base revision code " + after.baseRevisionCode
20968                        + " is older than current " + before.baseRevisionCode);
20969            }
20970
20971            if (!ArrayUtils.isEmpty(after.splitNames)) {
20972                for (int i = 0; i < after.splitNames.length; i++) {
20973                    final String splitName = after.splitNames[i];
20974                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20975                    if (j != -1) {
20976                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20977                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20978                                    "Update split " + splitName + " revision code "
20979                                    + after.splitRevisionCodes[i] + " is older than current "
20980                                    + before.splitRevisionCodes[j]);
20981                        }
20982                    }
20983                }
20984            }
20985        }
20986    }
20987
20988    private static class MoveCallbacks extends Handler {
20989        private static final int MSG_CREATED = 1;
20990        private static final int MSG_STATUS_CHANGED = 2;
20991
20992        private final RemoteCallbackList<IPackageMoveObserver>
20993                mCallbacks = new RemoteCallbackList<>();
20994
20995        private final SparseIntArray mLastStatus = new SparseIntArray();
20996
20997        public MoveCallbacks(Looper looper) {
20998            super(looper);
20999        }
21000
21001        public void register(IPackageMoveObserver callback) {
21002            mCallbacks.register(callback);
21003        }
21004
21005        public void unregister(IPackageMoveObserver callback) {
21006            mCallbacks.unregister(callback);
21007        }
21008
21009        @Override
21010        public void handleMessage(Message msg) {
21011            final SomeArgs args = (SomeArgs) msg.obj;
21012            final int n = mCallbacks.beginBroadcast();
21013            for (int i = 0; i < n; i++) {
21014                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21015                try {
21016                    invokeCallback(callback, msg.what, args);
21017                } catch (RemoteException ignored) {
21018                }
21019            }
21020            mCallbacks.finishBroadcast();
21021            args.recycle();
21022        }
21023
21024        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21025                throws RemoteException {
21026            switch (what) {
21027                case MSG_CREATED: {
21028                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21029                    break;
21030                }
21031                case MSG_STATUS_CHANGED: {
21032                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21033                    break;
21034                }
21035            }
21036        }
21037
21038        private void notifyCreated(int moveId, Bundle extras) {
21039            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21040
21041            final SomeArgs args = SomeArgs.obtain();
21042            args.argi1 = moveId;
21043            args.arg2 = extras;
21044            obtainMessage(MSG_CREATED, args).sendToTarget();
21045        }
21046
21047        private void notifyStatusChanged(int moveId, int status) {
21048            notifyStatusChanged(moveId, status, -1);
21049        }
21050
21051        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21052            Slog.v(TAG, "Move " + moveId + " status " + status);
21053
21054            final SomeArgs args = SomeArgs.obtain();
21055            args.argi1 = moveId;
21056            args.argi2 = status;
21057            args.arg3 = estMillis;
21058            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21059
21060            synchronized (mLastStatus) {
21061                mLastStatus.put(moveId, status);
21062            }
21063        }
21064    }
21065
21066    private final static class OnPermissionChangeListeners extends Handler {
21067        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21068
21069        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21070                new RemoteCallbackList<>();
21071
21072        public OnPermissionChangeListeners(Looper looper) {
21073            super(looper);
21074        }
21075
21076        @Override
21077        public void handleMessage(Message msg) {
21078            switch (msg.what) {
21079                case MSG_ON_PERMISSIONS_CHANGED: {
21080                    final int uid = msg.arg1;
21081                    handleOnPermissionsChanged(uid);
21082                } break;
21083            }
21084        }
21085
21086        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21087            mPermissionListeners.register(listener);
21088
21089        }
21090
21091        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21092            mPermissionListeners.unregister(listener);
21093        }
21094
21095        public void onPermissionsChanged(int uid) {
21096            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21097                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21098            }
21099        }
21100
21101        private void handleOnPermissionsChanged(int uid) {
21102            final int count = mPermissionListeners.beginBroadcast();
21103            try {
21104                for (int i = 0; i < count; i++) {
21105                    IOnPermissionsChangeListener callback = mPermissionListeners
21106                            .getBroadcastItem(i);
21107                    try {
21108                        callback.onPermissionsChanged(uid);
21109                    } catch (RemoteException e) {
21110                        Log.e(TAG, "Permission listener is dead", e);
21111                    }
21112                }
21113            } finally {
21114                mPermissionListeners.finishBroadcast();
21115            }
21116        }
21117    }
21118
21119    private class PackageManagerInternalImpl extends PackageManagerInternal {
21120        @Override
21121        public void setLocationPackagesProvider(PackagesProvider provider) {
21122            synchronized (mPackages) {
21123                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21124            }
21125        }
21126
21127        @Override
21128        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21129            synchronized (mPackages) {
21130                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21131            }
21132        }
21133
21134        @Override
21135        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21136            synchronized (mPackages) {
21137                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21138            }
21139        }
21140
21141        @Override
21142        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21143            synchronized (mPackages) {
21144                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21145            }
21146        }
21147
21148        @Override
21149        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21150            synchronized (mPackages) {
21151                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21152            }
21153        }
21154
21155        @Override
21156        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21157            synchronized (mPackages) {
21158                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21159            }
21160        }
21161
21162        @Override
21163        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21164            synchronized (mPackages) {
21165                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21166                        packageName, userId);
21167            }
21168        }
21169
21170        @Override
21171        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21172            synchronized (mPackages) {
21173                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21174                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21175                        packageName, userId);
21176            }
21177        }
21178
21179        @Override
21180        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21181            synchronized (mPackages) {
21182                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21183                        packageName, userId);
21184            }
21185        }
21186
21187        @Override
21188        public void setKeepUninstalledPackages(final List<String> packageList) {
21189            Preconditions.checkNotNull(packageList);
21190            List<String> removedFromList = null;
21191            synchronized (mPackages) {
21192                if (mKeepUninstalledPackages != null) {
21193                    final int packagesCount = mKeepUninstalledPackages.size();
21194                    for (int i = 0; i < packagesCount; i++) {
21195                        String oldPackage = mKeepUninstalledPackages.get(i);
21196                        if (packageList != null && packageList.contains(oldPackage)) {
21197                            continue;
21198                        }
21199                        if (removedFromList == null) {
21200                            removedFromList = new ArrayList<>();
21201                        }
21202                        removedFromList.add(oldPackage);
21203                    }
21204                }
21205                mKeepUninstalledPackages = new ArrayList<>(packageList);
21206                if (removedFromList != null) {
21207                    final int removedCount = removedFromList.size();
21208                    for (int i = 0; i < removedCount; i++) {
21209                        deletePackageIfUnusedLPr(removedFromList.get(i));
21210                    }
21211                }
21212            }
21213        }
21214
21215        @Override
21216        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21217            synchronized (mPackages) {
21218                // If we do not support permission review, done.
21219                if (!mPermissionReviewRequired) {
21220                    return false;
21221                }
21222
21223                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21224                if (packageSetting == null) {
21225                    return false;
21226                }
21227
21228                // Permission review applies only to apps not supporting the new permission model.
21229                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21230                    return false;
21231                }
21232
21233                // Legacy apps have the permission and get user consent on launch.
21234                PermissionsState permissionsState = packageSetting.getPermissionsState();
21235                return permissionsState.isPermissionReviewRequired(userId);
21236            }
21237        }
21238
21239        @Override
21240        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21241            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21242        }
21243
21244        @Override
21245        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21246                int userId) {
21247            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21248        }
21249
21250        @Override
21251        public void setDeviceAndProfileOwnerPackages(
21252                int deviceOwnerUserId, String deviceOwnerPackage,
21253                SparseArray<String> profileOwnerPackages) {
21254            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21255                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21256        }
21257
21258        @Override
21259        public boolean isPackageDataProtected(int userId, String packageName) {
21260            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21261        }
21262
21263        @Override
21264        public boolean wasPackageEverLaunched(String packageName, int userId) {
21265            synchronized (mPackages) {
21266                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21267            }
21268        }
21269
21270        @Override
21271        public void grantRuntimePermission(String packageName, String name, int userId,
21272                boolean overridePolicy) {
21273            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21274                    overridePolicy);
21275        }
21276
21277        @Override
21278        public void revokeRuntimePermission(String packageName, String name, int userId,
21279                boolean overridePolicy) {
21280            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21281                    overridePolicy);
21282        }
21283
21284        @Override
21285        public String getNameForUid(int uid) {
21286            return PackageManagerService.this.getNameForUid(uid);
21287        }
21288    }
21289
21290    @Override
21291    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21292        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21293        synchronized (mPackages) {
21294            final long identity = Binder.clearCallingIdentity();
21295            try {
21296                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21297                        packageNames, userId);
21298            } finally {
21299                Binder.restoreCallingIdentity(identity);
21300            }
21301        }
21302    }
21303
21304    private static void enforceSystemOrPhoneCaller(String tag) {
21305        int callingUid = Binder.getCallingUid();
21306        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21307            throw new SecurityException(
21308                    "Cannot call " + tag + " from UID " + callingUid);
21309        }
21310    }
21311
21312    boolean isHistoricalPackageUsageAvailable() {
21313        return mPackageUsage.isHistoricalPackageUsageAvailable();
21314    }
21315
21316    /**
21317     * Return a <b>copy</b> of the collection of packages known to the package manager.
21318     * @return A copy of the values of mPackages.
21319     */
21320    Collection<PackageParser.Package> getPackages() {
21321        synchronized (mPackages) {
21322            return new ArrayList<>(mPackages.values());
21323        }
21324    }
21325
21326    /**
21327     * Logs process start information (including base APK hash) to the security log.
21328     * @hide
21329     */
21330    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21331            String apkFile, int pid) {
21332        if (!SecurityLog.isLoggingEnabled()) {
21333            return;
21334        }
21335        Bundle data = new Bundle();
21336        data.putLong("startTimestamp", System.currentTimeMillis());
21337        data.putString("processName", processName);
21338        data.putInt("uid", uid);
21339        data.putString("seinfo", seinfo);
21340        data.putString("apkFile", apkFile);
21341        data.putInt("pid", pid);
21342        Message msg = mProcessLoggingHandler.obtainMessage(
21343                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21344        msg.setData(data);
21345        mProcessLoggingHandler.sendMessage(msg);
21346    }
21347
21348    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21349        return mCompilerStats.getPackageStats(pkgName);
21350    }
21351
21352    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21353        return getOrCreateCompilerPackageStats(pkg.packageName);
21354    }
21355
21356    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21357        return mCompilerStats.getOrCreatePackageStats(pkgName);
21358    }
21359
21360    public void deleteCompilerPackageStats(String pkgName) {
21361        mCompilerStats.deletePackageStats(pkgName);
21362    }
21363}
21364