PackageManagerService.java revision b8976d8f22fecaa9ed39276d9d8ded17d35b51a6
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_ANY_USER;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
76import static android.content.pm.PackageManager.PERMISSION_DENIED;
77import static android.content.pm.PackageManager.PERMISSION_GRANTED;
78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
79import static android.content.pm.PackageParser.isApkFile;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.AppOpsManager;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.ContentResolver;
116import android.content.Context;
117import android.content.IIntentReceiver;
118import android.content.Intent;
119import android.content.IntentFilter;
120import android.content.IntentSender;
121import android.content.IntentSender.SendIntentException;
122import android.content.ServiceConnection;
123import android.content.pm.ActivityInfo;
124import android.content.pm.ApplicationInfo;
125import android.content.pm.AppsQueryHelper;
126import android.content.pm.ComponentInfo;
127import android.content.pm.EphemeralApplicationInfo;
128import android.content.pm.EphemeralRequest;
129import android.content.pm.EphemeralResolveInfo;
130import android.content.pm.EphemeralResponse;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstrumentationInfo;
142import android.content.pm.IntentFilterVerificationInfo;
143import android.content.pm.KeySet;
144import android.content.pm.PackageCleanItem;
145import android.content.pm.PackageInfo;
146import android.content.pm.PackageInfoLite;
147import android.content.pm.PackageInstaller;
148import android.content.pm.PackageManager;
149import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
150import android.content.pm.PackageManagerInternal;
151import android.content.pm.PackageParser;
152import android.content.pm.PackageParser.ActivityIntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.PatternMatcher;
185import android.os.Process;
186import android.os.RemoteCallbackList;
187import android.os.RemoteException;
188import android.os.ResultReceiver;
189import android.os.SELinux;
190import android.os.ServiceManager;
191import android.os.ShellCallback;
192import android.os.SystemClock;
193import android.os.SystemProperties;
194import android.os.Trace;
195import android.os.UserHandle;
196import android.os.UserManager;
197import android.os.UserManagerInternal;
198import android.os.storage.IStorageManager;
199import android.os.storage.StorageManagerInternal;
200import android.os.storage.StorageEventListener;
201import android.os.storage.StorageManager;
202import android.os.storage.VolumeInfo;
203import android.os.storage.VolumeRecord;
204import android.provider.Settings.Global;
205import android.provider.Settings.Secure;
206import android.security.KeyStore;
207import android.security.SystemKeyStore;
208import android.system.ErrnoException;
209import android.system.Os;
210import android.text.TextUtils;
211import android.text.format.DateUtils;
212import android.util.ArrayMap;
213import android.util.ArraySet;
214import android.util.Base64;
215import android.util.DisplayMetrics;
216import android.util.EventLog;
217import android.util.ExceptionUtils;
218import android.util.Log;
219import android.util.LogPrinter;
220import android.util.MathUtils;
221import android.util.Pair;
222import android.util.PrintStreamPrinter;
223import android.util.Slog;
224import android.util.SparseArray;
225import android.util.SparseBooleanArray;
226import android.util.SparseIntArray;
227import android.util.Xml;
228import android.util.jar.StrictJarFile;
229import android.view.Display;
230
231import com.android.internal.R;
232import com.android.internal.annotations.GuardedBy;
233import com.android.internal.app.IMediaContainerService;
234import com.android.internal.app.ResolverActivity;
235import com.android.internal.content.NativeLibraryHelper;
236import com.android.internal.content.PackageHelper;
237import com.android.internal.logging.MetricsLogger;
238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
239import com.android.internal.os.IParcelFileDescriptorFactory;
240import com.android.internal.os.RoSystemProperties;
241import com.android.internal.os.SomeArgs;
242import com.android.internal.os.Zygote;
243import com.android.internal.telephony.CarrierAppUtils;
244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
246import com.android.internal.util.FastXmlSerializer;
247import com.android.internal.util.IndentingPrintWriter;
248import com.android.internal.util.Preconditions;
249import com.android.internal.util.XmlUtils;
250import com.android.server.AttributeCache;
251import com.android.server.EventLogTags;
252import com.android.server.FgThread;
253import com.android.server.IntentResolver;
254import com.android.server.LocalServices;
255import com.android.server.ServiceThread;
256import com.android.server.SystemConfig;
257import com.android.server.Watchdog;
258import com.android.server.net.NetworkPolicyManagerInternal;
259import com.android.server.pm.Installer.InstallerException;
260import com.android.server.pm.PermissionsState.PermissionState;
261import com.android.server.pm.Settings.DatabaseVersion;
262import com.android.server.pm.Settings.VersionInfo;
263import com.android.server.pm.dex.DexManager;
264import com.android.server.storage.DeviceStorageMonitorInternal;
265
266import dalvik.system.CloseGuard;
267import dalvik.system.DexFile;
268import dalvik.system.VMRuntime;
269
270import libcore.io.IoUtils;
271import libcore.util.EmptyArray;
272
273import org.xmlpull.v1.XmlPullParser;
274import org.xmlpull.v1.XmlPullParserException;
275import org.xmlpull.v1.XmlSerializer;
276
277import java.io.BufferedOutputStream;
278import java.io.BufferedReader;
279import java.io.ByteArrayInputStream;
280import java.io.ByteArrayOutputStream;
281import java.io.File;
282import java.io.FileDescriptor;
283import java.io.FileInputStream;
284import java.io.FileNotFoundException;
285import java.io.FileOutputStream;
286import java.io.FileReader;
287import java.io.FilenameFilter;
288import java.io.IOException;
289import java.io.PrintWriter;
290import java.nio.charset.StandardCharsets;
291import java.security.DigestInputStream;
292import java.security.MessageDigest;
293import java.security.NoSuchAlgorithmException;
294import java.security.PublicKey;
295import java.security.SecureRandom;
296import java.security.cert.Certificate;
297import java.security.cert.CertificateEncodingException;
298import java.security.cert.CertificateException;
299import java.text.SimpleDateFormat;
300import java.util.ArrayList;
301import java.util.Arrays;
302import java.util.Collection;
303import java.util.Collections;
304import java.util.Comparator;
305import java.util.Date;
306import java.util.HashSet;
307import java.util.HashMap;
308import java.util.Iterator;
309import java.util.List;
310import java.util.Map;
311import java.util.Objects;
312import java.util.Set;
313import java.util.concurrent.CountDownLatch;
314import java.util.concurrent.TimeUnit;
315import java.util.concurrent.atomic.AtomicBoolean;
316import java.util.concurrent.atomic.AtomicInteger;
317
318/**
319 * Keep track of all those APKs everywhere.
320 * <p>
321 * Internally there are two important locks:
322 * <ul>
323 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
324 * and other related state. It is a fine-grained lock that should only be held
325 * momentarily, as it's one of the most contended locks in the system.
326 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
327 * operations typically involve heavy lifting of application data on disk. Since
328 * {@code installd} is single-threaded, and it's operations can often be slow,
329 * this lock should never be acquired while already holding {@link #mPackages}.
330 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
331 * holding {@link #mInstallLock}.
332 * </ul>
333 * Many internal methods rely on the caller to hold the appropriate locks, and
334 * this contract is expressed through method name suffixes:
335 * <ul>
336 * <li>fooLI(): the caller must hold {@link #mInstallLock}
337 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
338 * being modified must be frozen
339 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
340 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
341 * </ul>
342 * <p>
343 * Because this class is very central to the platform's security; please run all
344 * CTS and unit tests whenever making modifications:
345 *
346 * <pre>
347 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
348 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
349 * </pre>
350 */
351public class PackageManagerService extends IPackageManager.Stub {
352    static final String TAG = "PackageManager";
353    static final boolean DEBUG_SETTINGS = false;
354    static final boolean DEBUG_PREFERRED = false;
355    static final boolean DEBUG_UPGRADE = false;
356    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
357    private static final boolean DEBUG_BACKUP = false;
358    private static final boolean DEBUG_INSTALL = false;
359    private static final boolean DEBUG_REMOVE = false;
360    private static final boolean DEBUG_BROADCASTS = false;
361    private static final boolean DEBUG_SHOW_INFO = false;
362    private static final boolean DEBUG_PACKAGE_INFO = false;
363    private static final boolean DEBUG_INTENT_MATCHING = false;
364    private static final boolean DEBUG_PACKAGE_SCANNING = false;
365    private static final boolean DEBUG_VERIFY = false;
366    private static final boolean DEBUG_FILTERS = false;
367
368    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
369    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
370    // user, but by default initialize to this.
371    static final boolean DEBUG_DEXOPT = false;
372
373    private static final boolean DEBUG_ABI_SELECTION = false;
374    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
375    private static final boolean DEBUG_TRIAGED_MISSING = false;
376    private static final boolean DEBUG_APP_DATA = false;
377
378    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
379    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
380
381    private static final boolean DISABLE_EPHEMERAL_APPS = false;
382    private static final boolean HIDE_EPHEMERAL_APIS = true;
383
384    private static final int RADIO_UID = Process.PHONE_UID;
385    private static final int LOG_UID = Process.LOG_UID;
386    private static final int NFC_UID = Process.NFC_UID;
387    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
388    private static final int SHELL_UID = Process.SHELL_UID;
389
390    // Cap the size of permission trees that 3rd party apps can define
391    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
392
393    // Suffix used during package installation when copying/moving
394    // package apks to install directory.
395    private static final String INSTALL_PACKAGE_SUFFIX = "-";
396
397    static final int SCAN_NO_DEX = 1<<1;
398    static final int SCAN_FORCE_DEX = 1<<2;
399    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
400    static final int SCAN_NEW_INSTALL = 1<<4;
401    static final int SCAN_UPDATE_TIME = 1<<5;
402    static final int SCAN_BOOTING = 1<<6;
403    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
404    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
405    static final int SCAN_REPLACING = 1<<9;
406    static final int SCAN_REQUIRE_KNOWN = 1<<10;
407    static final int SCAN_MOVE = 1<<11;
408    static final int SCAN_INITIAL = 1<<12;
409    static final int SCAN_CHECK_ONLY = 1<<13;
410    static final int SCAN_DONT_KILL_APP = 1<<14;
411    static final int SCAN_IGNORE_FROZEN = 1<<15;
412    static final int REMOVE_CHATTY = 1<<16;
413    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
414
415    private static final int[] EMPTY_INT_ARRAY = new int[0];
416
417    /**
418     * Timeout (in milliseconds) after which the watchdog should declare that
419     * our handler thread is wedged.  The usual default for such things is one
420     * minute but we sometimes do very lengthy I/O operations on this thread,
421     * such as installing multi-gigabyte applications, so ours needs to be longer.
422     */
423    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
424
425    /**
426     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
427     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
428     * settings entry if available, otherwise we use the hardcoded default.  If it's been
429     * more than this long since the last fstrim, we force one during the boot sequence.
430     *
431     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
432     * one gets run at the next available charging+idle time.  This final mandatory
433     * no-fstrim check kicks in only of the other scheduling criteria is never met.
434     */
435    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
436
437    /**
438     * Whether verification is enabled by default.
439     */
440    private static final boolean DEFAULT_VERIFY_ENABLE = true;
441
442    /**
443     * The default maximum time to wait for the verification agent to return in
444     * milliseconds.
445     */
446    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
447
448    /**
449     * The default response for package verification timeout.
450     *
451     * This can be either PackageManager.VERIFICATION_ALLOW or
452     * PackageManager.VERIFICATION_REJECT.
453     */
454    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
455
456    static final String PLATFORM_PACKAGE_NAME = "android";
457
458    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
459
460    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
461            DEFAULT_CONTAINER_PACKAGE,
462            "com.android.defcontainer.DefaultContainerService");
463
464    private static final String KILL_APP_REASON_GIDS_CHANGED =
465            "permission grant or revoke changed gids";
466
467    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
468            "permissions revoked";
469
470    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
471
472    private static final String PACKAGE_SCHEME = "package";
473
474    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
475    /**
476     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
477     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
478     * VENDOR_OVERLAY_DIR.
479     */
480    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
481    /**
482     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
483     * is in VENDOR_OVERLAY_THEME_PROPERTY.
484     */
485    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
486            = "persist.vendor.overlay.theme";
487
488    /** Permission grant: not grant the permission. */
489    private static final int GRANT_DENIED = 1;
490
491    /** Permission grant: grant the permission as an install permission. */
492    private static final int GRANT_INSTALL = 2;
493
494    /** Permission grant: grant the permission as a runtime one. */
495    private static final int GRANT_RUNTIME = 3;
496
497    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
498    private static final int GRANT_UPGRADE = 4;
499
500    /** Canonical intent used to identify what counts as a "web browser" app */
501    private static final Intent sBrowserIntent;
502    static {
503        sBrowserIntent = new Intent();
504        sBrowserIntent.setAction(Intent.ACTION_VIEW);
505        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
506        sBrowserIntent.setData(Uri.parse("http:"));
507    }
508
509    /**
510     * The set of all protected actions [i.e. those actions for which a high priority
511     * intent filter is disallowed].
512     */
513    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
514    static {
515        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
516        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
517        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
518        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
519    }
520
521    // Compilation reasons.
522    public static final int REASON_FIRST_BOOT = 0;
523    public static final int REASON_BOOT = 1;
524    public static final int REASON_INSTALL = 2;
525    public static final int REASON_BACKGROUND_DEXOPT = 3;
526    public static final int REASON_AB_OTA = 4;
527    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
528    public static final int REASON_SHARED_APK = 6;
529    public static final int REASON_FORCED_DEXOPT = 7;
530    public static final int REASON_CORE_APP = 8;
531
532    public static final int REASON_LAST = REASON_CORE_APP;
533
534    /** Special library name that skips shared libraries check during compilation. */
535    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
536
537    /** All dangerous permission names in the same order as the events in MetricsEvent */
538    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
539            Manifest.permission.READ_CALENDAR,
540            Manifest.permission.WRITE_CALENDAR,
541            Manifest.permission.CAMERA,
542            Manifest.permission.READ_CONTACTS,
543            Manifest.permission.WRITE_CONTACTS,
544            Manifest.permission.GET_ACCOUNTS,
545            Manifest.permission.ACCESS_FINE_LOCATION,
546            Manifest.permission.ACCESS_COARSE_LOCATION,
547            Manifest.permission.RECORD_AUDIO,
548            Manifest.permission.READ_PHONE_STATE,
549            Manifest.permission.CALL_PHONE,
550            Manifest.permission.READ_CALL_LOG,
551            Manifest.permission.WRITE_CALL_LOG,
552            Manifest.permission.ADD_VOICEMAIL,
553            Manifest.permission.USE_SIP,
554            Manifest.permission.PROCESS_OUTGOING_CALLS,
555            Manifest.permission.READ_CELL_BROADCASTS,
556            Manifest.permission.BODY_SENSORS,
557            Manifest.permission.SEND_SMS,
558            Manifest.permission.RECEIVE_SMS,
559            Manifest.permission.READ_SMS,
560            Manifest.permission.RECEIVE_WAP_PUSH,
561            Manifest.permission.RECEIVE_MMS,
562            Manifest.permission.READ_EXTERNAL_STORAGE,
563            Manifest.permission.WRITE_EXTERNAL_STORAGE,
564            Manifest.permission.READ_PHONE_NUMBER);
565
566    final ServiceThread mHandlerThread;
567
568    final PackageHandler mHandler;
569
570    private final ProcessLoggingHandler mProcessLoggingHandler;
571
572    /**
573     * Messages for {@link #mHandler} that need to wait for system ready before
574     * being dispatched.
575     */
576    private ArrayList<Message> mPostSystemReadyMessages;
577
578    final int mSdkVersion = Build.VERSION.SDK_INT;
579
580    final Context mContext;
581    final boolean mFactoryTest;
582    final boolean mOnlyCore;
583    final DisplayMetrics mMetrics;
584    final int mDefParseFlags;
585    final String[] mSeparateProcesses;
586    final boolean mIsUpgrade;
587    final boolean mIsPreNUpgrade;
588    final boolean mIsPreNMR1Upgrade;
589
590    @GuardedBy("mPackages")
591    private boolean mDexOptDialogShown;
592
593    /** The location for ASEC container files on internal storage. */
594    final String mAsecInternalPath;
595
596    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
597    // LOCK HELD.  Can be called with mInstallLock held.
598    @GuardedBy("mInstallLock")
599    final Installer mInstaller;
600
601    /** Directory where installed third-party apps stored */
602    final File mAppInstallDir;
603    final File mEphemeralInstallDir;
604
605    /**
606     * Directory to which applications installed internally have their
607     * 32 bit native libraries copied.
608     */
609    private File mAppLib32InstallDir;
610
611    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
612    // apps.
613    final File mDrmAppPrivateInstallDir;
614
615    // ----------------------------------------------------------------
616
617    // Lock for state used when installing and doing other long running
618    // operations.  Methods that must be called with this lock held have
619    // the suffix "LI".
620    final Object mInstallLock = new Object();
621
622    // ----------------------------------------------------------------
623
624    // Keys are String (package name), values are Package.  This also serves
625    // as the lock for the global state.  Methods that must be called with
626    // this lock held have the prefix "LP".
627    @GuardedBy("mPackages")
628    final ArrayMap<String, PackageParser.Package> mPackages =
629            new ArrayMap<String, PackageParser.Package>();
630
631    final ArrayMap<String, Set<String>> mKnownCodebase =
632            new ArrayMap<String, Set<String>>();
633
634    // Tracks available target package names -> overlay package paths.
635    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
636        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
637
638    /**
639     * Tracks new system packages [received in an OTA] that we expect to
640     * find updated user-installed versions. Keys are package name, values
641     * are package location.
642     */
643    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
644    /**
645     * Tracks high priority intent filters for protected actions. During boot, certain
646     * filter actions are protected and should never be allowed to have a high priority
647     * intent filter for them. However, there is one, and only one exception -- the
648     * setup wizard. It must be able to define a high priority intent filter for these
649     * actions to ensure there are no escapes from the wizard. We need to delay processing
650     * of these during boot as we need to look at all of the system packages in order
651     * to know which component is the setup wizard.
652     */
653    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
654    /**
655     * Whether or not processing protected filters should be deferred.
656     */
657    private boolean mDeferProtectedFilters = true;
658
659    /**
660     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
661     */
662    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
663    /**
664     * Whether or not system app permissions should be promoted from install to runtime.
665     */
666    boolean mPromoteSystemApps;
667
668    @GuardedBy("mPackages")
669    final Settings mSettings;
670
671    /**
672     * Set of package names that are currently "frozen", which means active
673     * surgery is being done on the code/data for that package. The platform
674     * will refuse to launch frozen packages to avoid race conditions.
675     *
676     * @see PackageFreezer
677     */
678    @GuardedBy("mPackages")
679    final ArraySet<String> mFrozenPackages = new ArraySet<>();
680
681    final ProtectedPackages mProtectedPackages;
682
683    boolean mFirstBoot;
684
685    // System configuration read by SystemConfig.
686    final int[] mGlobalGids;
687    final SparseArray<ArraySet<String>> mSystemPermissions;
688    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
689
690    // If mac_permissions.xml was found for seinfo labeling.
691    boolean mFoundPolicyFile;
692
693    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
694
695    public static final class SharedLibraryEntry {
696        public final String path;
697        public final String apk;
698
699        SharedLibraryEntry(String _path, String _apk) {
700            path = _path;
701            apk = _apk;
702        }
703    }
704
705    // Currently known shared libraries.
706    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
707            new ArrayMap<String, SharedLibraryEntry>();
708
709    // All available activities, for your resolving pleasure.
710    final ActivityIntentResolver mActivities =
711            new ActivityIntentResolver();
712
713    // All available receivers, for your resolving pleasure.
714    final ActivityIntentResolver mReceivers =
715            new ActivityIntentResolver();
716
717    // All available services, for your resolving pleasure.
718    final ServiceIntentResolver mServices = new ServiceIntentResolver();
719
720    // All available providers, for your resolving pleasure.
721    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
722
723    // Mapping from provider base names (first directory in content URI codePath)
724    // to the provider information.
725    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
726            new ArrayMap<String, PackageParser.Provider>();
727
728    // Mapping from instrumentation class names to info about them.
729    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
730            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
731
732    // Mapping from permission names to info about them.
733    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
734            new ArrayMap<String, PackageParser.PermissionGroup>();
735
736    // Packages whose data we have transfered into another package, thus
737    // should no longer exist.
738    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
739
740    // Broadcast actions that are only available to the system.
741    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
742
743    /** List of packages waiting for verification. */
744    final SparseArray<PackageVerificationState> mPendingVerification
745            = new SparseArray<PackageVerificationState>();
746
747    /** Set of packages associated with each app op permission. */
748    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
749
750    final PackageInstallerService mInstallerService;
751
752    private final PackageDexOptimizer mPackageDexOptimizer;
753    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
754    // is used by other apps).
755    private final DexManager mDexManager;
756
757    private AtomicInteger mNextMoveId = new AtomicInteger();
758    private final MoveCallbacks mMoveCallbacks;
759
760    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
761
762    // Cache of users who need badging.
763    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
764
765    /** Token for keys in mPendingVerification. */
766    private int mPendingVerificationToken = 0;
767
768    volatile boolean mSystemReady;
769    volatile boolean mSafeMode;
770    volatile boolean mHasSystemUidErrors;
771
772    ApplicationInfo mAndroidApplication;
773    final ActivityInfo mResolveActivity = new ActivityInfo();
774    final ResolveInfo mResolveInfo = new ResolveInfo();
775    ComponentName mResolveComponentName;
776    PackageParser.Package mPlatformPackage;
777    ComponentName mCustomResolverComponentName;
778
779    boolean mResolverReplaced = false;
780
781    private final @Nullable ComponentName mIntentFilterVerifierComponent;
782    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
783
784    private int mIntentFilterVerificationToken = 0;
785
786    /** The service connection to the ephemeral resolver */
787    final EphemeralResolverConnection mEphemeralResolverConnection;
788
789    /** Component used to install ephemeral applications */
790    ComponentName mEphemeralInstallerComponent;
791    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
792    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
793
794    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
795            = new SparseArray<IntentFilterVerificationState>();
796
797    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
798
799    // List of packages names to keep cached, even if they are uninstalled for all users
800    private List<String> mKeepUninstalledPackages;
801
802    private UserManagerInternal mUserManagerInternal;
803
804    private static class IFVerificationParams {
805        PackageParser.Package pkg;
806        boolean replacing;
807        int userId;
808        int verifierUid;
809
810        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
811                int _userId, int _verifierUid) {
812            pkg = _pkg;
813            replacing = _replacing;
814            userId = _userId;
815            replacing = _replacing;
816            verifierUid = _verifierUid;
817        }
818    }
819
820    private interface IntentFilterVerifier<T extends IntentFilter> {
821        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
822                                               T filter, String packageName);
823        void startVerifications(int userId);
824        void receiveVerificationResponse(int verificationId);
825    }
826
827    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
828        private Context mContext;
829        private ComponentName mIntentFilterVerifierComponent;
830        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
831
832        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
833            mContext = context;
834            mIntentFilterVerifierComponent = verifierComponent;
835        }
836
837        private String getDefaultScheme() {
838            return IntentFilter.SCHEME_HTTPS;
839        }
840
841        @Override
842        public void startVerifications(int userId) {
843            // Launch verifications requests
844            int count = mCurrentIntentFilterVerifications.size();
845            for (int n=0; n<count; n++) {
846                int verificationId = mCurrentIntentFilterVerifications.get(n);
847                final IntentFilterVerificationState ivs =
848                        mIntentFilterVerificationStates.get(verificationId);
849
850                String packageName = ivs.getPackageName();
851
852                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
853                final int filterCount = filters.size();
854                ArraySet<String> domainsSet = new ArraySet<>();
855                for (int m=0; m<filterCount; m++) {
856                    PackageParser.ActivityIntentInfo filter = filters.get(m);
857                    domainsSet.addAll(filter.getHostsList());
858                }
859                synchronized (mPackages) {
860                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
861                            packageName, domainsSet) != null) {
862                        scheduleWriteSettingsLocked();
863                    }
864                }
865                sendVerificationRequest(userId, verificationId, ivs);
866            }
867            mCurrentIntentFilterVerifications.clear();
868        }
869
870        private void sendVerificationRequest(int userId, int verificationId,
871                IntentFilterVerificationState ivs) {
872
873            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
874            verificationIntent.putExtra(
875                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
876                    verificationId);
877            verificationIntent.putExtra(
878                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
879                    getDefaultScheme());
880            verificationIntent.putExtra(
881                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
882                    ivs.getHostsString());
883            verificationIntent.putExtra(
884                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
885                    ivs.getPackageName());
886            verificationIntent.setComponent(mIntentFilterVerifierComponent);
887            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
888
889            UserHandle user = new UserHandle(userId);
890            mContext.sendBroadcastAsUser(verificationIntent, user);
891            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
892                    "Sending IntentFilter verification broadcast");
893        }
894
895        public void receiveVerificationResponse(int verificationId) {
896            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
897
898            final boolean verified = ivs.isVerified();
899
900            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
901            final int count = filters.size();
902            if (DEBUG_DOMAIN_VERIFICATION) {
903                Slog.i(TAG, "Received verification response " + verificationId
904                        + " for " + count + " filters, verified=" + verified);
905            }
906            for (int n=0; n<count; n++) {
907                PackageParser.ActivityIntentInfo filter = filters.get(n);
908                filter.setVerified(verified);
909
910                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
911                        + " verified with result:" + verified + " and hosts:"
912                        + ivs.getHostsString());
913            }
914
915            mIntentFilterVerificationStates.remove(verificationId);
916
917            final String packageName = ivs.getPackageName();
918            IntentFilterVerificationInfo ivi = null;
919
920            synchronized (mPackages) {
921                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
922            }
923            if (ivi == null) {
924                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
925                        + verificationId + " packageName:" + packageName);
926                return;
927            }
928            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
929                    "Updating IntentFilterVerificationInfo for package " + packageName
930                            +" verificationId:" + verificationId);
931
932            synchronized (mPackages) {
933                if (verified) {
934                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
935                } else {
936                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
937                }
938                scheduleWriteSettingsLocked();
939
940                final int userId = ivs.getUserId();
941                if (userId != UserHandle.USER_ALL) {
942                    final int userStatus =
943                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
944
945                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
946                    boolean needUpdate = false;
947
948                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
949                    // already been set by the User thru the Disambiguation dialog
950                    switch (userStatus) {
951                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
952                            if (verified) {
953                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
954                            } else {
955                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
956                            }
957                            needUpdate = true;
958                            break;
959
960                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
961                            if (verified) {
962                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
963                                needUpdate = true;
964                            }
965                            break;
966
967                        default:
968                            // Nothing to do
969                    }
970
971                    if (needUpdate) {
972                        mSettings.updateIntentFilterVerificationStatusLPw(
973                                packageName, updatedStatus, userId);
974                        scheduleWritePackageRestrictionsLocked(userId);
975                    }
976                }
977            }
978        }
979
980        @Override
981        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
982                    ActivityIntentInfo filter, String packageName) {
983            if (!hasValidDomains(filter)) {
984                return false;
985            }
986            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
987            if (ivs == null) {
988                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
989                        packageName);
990            }
991            if (DEBUG_DOMAIN_VERIFICATION) {
992                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
993            }
994            ivs.addFilter(filter);
995            return true;
996        }
997
998        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
999                int userId, int verificationId, String packageName) {
1000            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1001                    verifierUid, userId, packageName);
1002            ivs.setPendingState();
1003            synchronized (mPackages) {
1004                mIntentFilterVerificationStates.append(verificationId, ivs);
1005                mCurrentIntentFilterVerifications.add(verificationId);
1006            }
1007            return ivs;
1008        }
1009    }
1010
1011    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1012        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1013                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1014                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1015    }
1016
1017    // Set of pending broadcasts for aggregating enable/disable of components.
1018    static class PendingPackageBroadcasts {
1019        // for each user id, a map of <package name -> components within that package>
1020        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1021
1022        public PendingPackageBroadcasts() {
1023            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1024        }
1025
1026        public ArrayList<String> get(int userId, String packageName) {
1027            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1028            return packages.get(packageName);
1029        }
1030
1031        public void put(int userId, String packageName, ArrayList<String> components) {
1032            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1033            packages.put(packageName, components);
1034        }
1035
1036        public void remove(int userId, String packageName) {
1037            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1038            if (packages != null) {
1039                packages.remove(packageName);
1040            }
1041        }
1042
1043        public void remove(int userId) {
1044            mUidMap.remove(userId);
1045        }
1046
1047        public int userIdCount() {
1048            return mUidMap.size();
1049        }
1050
1051        public int userIdAt(int n) {
1052            return mUidMap.keyAt(n);
1053        }
1054
1055        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1056            return mUidMap.get(userId);
1057        }
1058
1059        public int size() {
1060            // total number of pending broadcast entries across all userIds
1061            int num = 0;
1062            for (int i = 0; i< mUidMap.size(); i++) {
1063                num += mUidMap.valueAt(i).size();
1064            }
1065            return num;
1066        }
1067
1068        public void clear() {
1069            mUidMap.clear();
1070        }
1071
1072        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1073            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1074            if (map == null) {
1075                map = new ArrayMap<String, ArrayList<String>>();
1076                mUidMap.put(userId, map);
1077            }
1078            return map;
1079        }
1080    }
1081    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1082
1083    // Service Connection to remote media container service to copy
1084    // package uri's from external media onto secure containers
1085    // or internal storage.
1086    private IMediaContainerService mContainerService = null;
1087
1088    static final int SEND_PENDING_BROADCAST = 1;
1089    static final int MCS_BOUND = 3;
1090    static final int END_COPY = 4;
1091    static final int INIT_COPY = 5;
1092    static final int MCS_UNBIND = 6;
1093    static final int START_CLEANING_PACKAGE = 7;
1094    static final int FIND_INSTALL_LOC = 8;
1095    static final int POST_INSTALL = 9;
1096    static final int MCS_RECONNECT = 10;
1097    static final int MCS_GIVE_UP = 11;
1098    static final int UPDATED_MEDIA_STATUS = 12;
1099    static final int WRITE_SETTINGS = 13;
1100    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1101    static final int PACKAGE_VERIFIED = 15;
1102    static final int CHECK_PENDING_VERIFICATION = 16;
1103    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1104    static final int INTENT_FILTER_VERIFIED = 18;
1105    static final int WRITE_PACKAGE_LIST = 19;
1106    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1107
1108    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1109
1110    // Delay time in millisecs
1111    static final int BROADCAST_DELAY = 10 * 1000;
1112
1113    static UserManagerService sUserManager;
1114
1115    // Stores a list of users whose package restrictions file needs to be updated
1116    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1117
1118    final private DefaultContainerConnection mDefContainerConn =
1119            new DefaultContainerConnection();
1120    class DefaultContainerConnection implements ServiceConnection {
1121        public void onServiceConnected(ComponentName name, IBinder service) {
1122            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1123            final IMediaContainerService imcs = IMediaContainerService.Stub
1124                    .asInterface(Binder.allowBlocking(service));
1125            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1126        }
1127
1128        public void onServiceDisconnected(ComponentName name) {
1129            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1130        }
1131    }
1132
1133    // Recordkeeping of restore-after-install operations that are currently in flight
1134    // between the Package Manager and the Backup Manager
1135    static class PostInstallData {
1136        public InstallArgs args;
1137        public PackageInstalledInfo res;
1138
1139        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1140            args = _a;
1141            res = _r;
1142        }
1143    }
1144
1145    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1146    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1147
1148    // XML tags for backup/restore of various bits of state
1149    private static final String TAG_PREFERRED_BACKUP = "pa";
1150    private static final String TAG_DEFAULT_APPS = "da";
1151    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1152
1153    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1154    private static final String TAG_ALL_GRANTS = "rt-grants";
1155    private static final String TAG_GRANT = "grant";
1156    private static final String ATTR_PACKAGE_NAME = "pkg";
1157
1158    private static final String TAG_PERMISSION = "perm";
1159    private static final String ATTR_PERMISSION_NAME = "name";
1160    private static final String ATTR_IS_GRANTED = "g";
1161    private static final String ATTR_USER_SET = "set";
1162    private static final String ATTR_USER_FIXED = "fixed";
1163    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1164
1165    // System/policy permission grants are not backed up
1166    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1167            FLAG_PERMISSION_POLICY_FIXED
1168            | FLAG_PERMISSION_SYSTEM_FIXED
1169            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1170
1171    // And we back up these user-adjusted states
1172    private static final int USER_RUNTIME_GRANT_MASK =
1173            FLAG_PERMISSION_USER_SET
1174            | FLAG_PERMISSION_USER_FIXED
1175            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1176
1177    final @Nullable String mRequiredVerifierPackage;
1178    final @NonNull String mRequiredInstallerPackage;
1179    final @NonNull String mRequiredUninstallerPackage;
1180    final @Nullable String mSetupWizardPackage;
1181    final @Nullable String mStorageManagerPackage;
1182    final @NonNull String mServicesSystemSharedLibraryPackageName;
1183    final @NonNull String mSharedSystemSharedLibraryPackageName;
1184
1185    final boolean mPermissionReviewRequired;
1186
1187    private final PackageUsage mPackageUsage = new PackageUsage();
1188    private final CompilerStats mCompilerStats = new CompilerStats();
1189
1190    class PackageHandler extends Handler {
1191        private boolean mBound = false;
1192        final ArrayList<HandlerParams> mPendingInstalls =
1193            new ArrayList<HandlerParams>();
1194
1195        private boolean connectToService() {
1196            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1197                    " DefaultContainerService");
1198            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1199            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1200            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1201                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1202                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1203                mBound = true;
1204                return true;
1205            }
1206            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1207            return false;
1208        }
1209
1210        private void disconnectService() {
1211            mContainerService = null;
1212            mBound = false;
1213            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1214            mContext.unbindService(mDefContainerConn);
1215            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1216        }
1217
1218        PackageHandler(Looper looper) {
1219            super(looper);
1220        }
1221
1222        public void handleMessage(Message msg) {
1223            try {
1224                doHandleMessage(msg);
1225            } finally {
1226                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1227            }
1228        }
1229
1230        void doHandleMessage(Message msg) {
1231            switch (msg.what) {
1232                case INIT_COPY: {
1233                    HandlerParams params = (HandlerParams) msg.obj;
1234                    int idx = mPendingInstalls.size();
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1236                    // If a bind was already initiated we dont really
1237                    // need to do anything. The pending install
1238                    // will be processed later on.
1239                    if (!mBound) {
1240                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1241                                System.identityHashCode(mHandler));
1242                        // If this is the only one pending we might
1243                        // have to bind to the service again.
1244                        if (!connectToService()) {
1245                            Slog.e(TAG, "Failed to bind to media container service");
1246                            params.serviceError();
1247                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1248                                    System.identityHashCode(mHandler));
1249                            if (params.traceMethod != null) {
1250                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1251                                        params.traceCookie);
1252                            }
1253                            return;
1254                        } else {
1255                            // Once we bind to the service, the first
1256                            // pending request will be processed.
1257                            mPendingInstalls.add(idx, params);
1258                        }
1259                    } else {
1260                        mPendingInstalls.add(idx, params);
1261                        // Already bound to the service. Just make
1262                        // sure we trigger off processing the first request.
1263                        if (idx == 0) {
1264                            mHandler.sendEmptyMessage(MCS_BOUND);
1265                        }
1266                    }
1267                    break;
1268                }
1269                case MCS_BOUND: {
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1271                    if (msg.obj != null) {
1272                        mContainerService = (IMediaContainerService) msg.obj;
1273                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1274                                System.identityHashCode(mHandler));
1275                    }
1276                    if (mContainerService == null) {
1277                        if (!mBound) {
1278                            // Something seriously wrong since we are not bound and we are not
1279                            // waiting for connection. Bail out.
1280                            Slog.e(TAG, "Cannot bind to media container service");
1281                            for (HandlerParams params : mPendingInstalls) {
1282                                // Indicate service bind error
1283                                params.serviceError();
1284                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1285                                        System.identityHashCode(params));
1286                                if (params.traceMethod != null) {
1287                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1288                                            params.traceMethod, params.traceCookie);
1289                                }
1290                                return;
1291                            }
1292                            mPendingInstalls.clear();
1293                        } else {
1294                            Slog.w(TAG, "Waiting to connect to media container service");
1295                        }
1296                    } else if (mPendingInstalls.size() > 0) {
1297                        HandlerParams params = mPendingInstalls.get(0);
1298                        if (params != null) {
1299                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1300                                    System.identityHashCode(params));
1301                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1302                            if (params.startCopy()) {
1303                                // We are done...  look for more work or to
1304                                // go idle.
1305                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1306                                        "Checking for more work or unbind...");
1307                                // Delete pending install
1308                                if (mPendingInstalls.size() > 0) {
1309                                    mPendingInstalls.remove(0);
1310                                }
1311                                if (mPendingInstalls.size() == 0) {
1312                                    if (mBound) {
1313                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1314                                                "Posting delayed MCS_UNBIND");
1315                                        removeMessages(MCS_UNBIND);
1316                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1317                                        // Unbind after a little delay, to avoid
1318                                        // continual thrashing.
1319                                        sendMessageDelayed(ubmsg, 10000);
1320                                    }
1321                                } else {
1322                                    // There are more pending requests in queue.
1323                                    // Just post MCS_BOUND message to trigger processing
1324                                    // of next pending install.
1325                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1326                                            "Posting MCS_BOUND for next work");
1327                                    mHandler.sendEmptyMessage(MCS_BOUND);
1328                                }
1329                            }
1330                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1331                        }
1332                    } else {
1333                        // Should never happen ideally.
1334                        Slog.w(TAG, "Empty queue");
1335                    }
1336                    break;
1337                }
1338                case MCS_RECONNECT: {
1339                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1340                    if (mPendingInstalls.size() > 0) {
1341                        if (mBound) {
1342                            disconnectService();
1343                        }
1344                        if (!connectToService()) {
1345                            Slog.e(TAG, "Failed to bind to media container service");
1346                            for (HandlerParams params : mPendingInstalls) {
1347                                // Indicate service bind error
1348                                params.serviceError();
1349                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1350                                        System.identityHashCode(params));
1351                            }
1352                            mPendingInstalls.clear();
1353                        }
1354                    }
1355                    break;
1356                }
1357                case MCS_UNBIND: {
1358                    // If there is no actual work left, then time to unbind.
1359                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1360
1361                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1362                        if (mBound) {
1363                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1364
1365                            disconnectService();
1366                        }
1367                    } else if (mPendingInstalls.size() > 0) {
1368                        // There are more pending requests in queue.
1369                        // Just post MCS_BOUND message to trigger processing
1370                        // of next pending install.
1371                        mHandler.sendEmptyMessage(MCS_BOUND);
1372                    }
1373
1374                    break;
1375                }
1376                case MCS_GIVE_UP: {
1377                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1378                    HandlerParams params = mPendingInstalls.remove(0);
1379                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1380                            System.identityHashCode(params));
1381                    break;
1382                }
1383                case SEND_PENDING_BROADCAST: {
1384                    String packages[];
1385                    ArrayList<String> components[];
1386                    int size = 0;
1387                    int uids[];
1388                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1389                    synchronized (mPackages) {
1390                        if (mPendingBroadcasts == null) {
1391                            return;
1392                        }
1393                        size = mPendingBroadcasts.size();
1394                        if (size <= 0) {
1395                            // Nothing to be done. Just return
1396                            return;
1397                        }
1398                        packages = new String[size];
1399                        components = new ArrayList[size];
1400                        uids = new int[size];
1401                        int i = 0;  // filling out the above arrays
1402
1403                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1404                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1405                            Iterator<Map.Entry<String, ArrayList<String>>> it
1406                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1407                                            .entrySet().iterator();
1408                            while (it.hasNext() && i < size) {
1409                                Map.Entry<String, ArrayList<String>> ent = it.next();
1410                                packages[i] = ent.getKey();
1411                                components[i] = ent.getValue();
1412                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1413                                uids[i] = (ps != null)
1414                                        ? UserHandle.getUid(packageUserId, ps.appId)
1415                                        : -1;
1416                                i++;
1417                            }
1418                        }
1419                        size = i;
1420                        mPendingBroadcasts.clear();
1421                    }
1422                    // Send broadcasts
1423                    for (int i = 0; i < size; i++) {
1424                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1425                    }
1426                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                    break;
1428                }
1429                case START_CLEANING_PACKAGE: {
1430                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1431                    final String packageName = (String)msg.obj;
1432                    final int userId = msg.arg1;
1433                    final boolean andCode = msg.arg2 != 0;
1434                    synchronized (mPackages) {
1435                        if (userId == UserHandle.USER_ALL) {
1436                            int[] users = sUserManager.getUserIds();
1437                            for (int user : users) {
1438                                mSettings.addPackageToCleanLPw(
1439                                        new PackageCleanItem(user, packageName, andCode));
1440                            }
1441                        } else {
1442                            mSettings.addPackageToCleanLPw(
1443                                    new PackageCleanItem(userId, packageName, andCode));
1444                        }
1445                    }
1446                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1447                    startCleaningPackages();
1448                } break;
1449                case POST_INSTALL: {
1450                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1451
1452                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1453                    final boolean didRestore = (msg.arg2 != 0);
1454                    mRunningInstalls.delete(msg.arg1);
1455
1456                    if (data != null) {
1457                        InstallArgs args = data.args;
1458                        PackageInstalledInfo parentRes = data.res;
1459
1460                        final boolean grantPermissions = (args.installFlags
1461                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1462                        final boolean killApp = (args.installFlags
1463                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1464                        final String[] grantedPermissions = args.installGrantPermissions;
1465
1466                        // Handle the parent package
1467                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1468                                grantedPermissions, didRestore, args.installerPackageName,
1469                                args.observer);
1470
1471                        // Handle the child packages
1472                        final int childCount = (parentRes.addedChildPackages != null)
1473                                ? parentRes.addedChildPackages.size() : 0;
1474                        for (int i = 0; i < childCount; i++) {
1475                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1476                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1477                                    grantedPermissions, false, args.installerPackageName,
1478                                    args.observer);
1479                        }
1480
1481                        // Log tracing if needed
1482                        if (args.traceMethod != null) {
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1484                                    args.traceCookie);
1485                        }
1486                    } else {
1487                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1488                    }
1489
1490                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1491                } break;
1492                case UPDATED_MEDIA_STATUS: {
1493                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1494                    boolean reportStatus = msg.arg1 == 1;
1495                    boolean doGc = msg.arg2 == 1;
1496                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1497                    if (doGc) {
1498                        // Force a gc to clear up stale containers.
1499                        Runtime.getRuntime().gc();
1500                    }
1501                    if (msg.obj != null) {
1502                        @SuppressWarnings("unchecked")
1503                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1504                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1505                        // Unload containers
1506                        unloadAllContainers(args);
1507                    }
1508                    if (reportStatus) {
1509                        try {
1510                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1511                                    "Invoking StorageManagerService call back");
1512                            PackageHelper.getStorageManager().finishMediaUpdate();
1513                        } catch (RemoteException e) {
1514                            Log.e(TAG, "StorageManagerService not running?");
1515                        }
1516                    }
1517                } break;
1518                case WRITE_SETTINGS: {
1519                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1520                    synchronized (mPackages) {
1521                        removeMessages(WRITE_SETTINGS);
1522                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1523                        mSettings.writeLPr();
1524                        mDirtyUsers.clear();
1525                    }
1526                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1527                } break;
1528                case WRITE_PACKAGE_RESTRICTIONS: {
1529                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1530                    synchronized (mPackages) {
1531                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1532                        for (int userId : mDirtyUsers) {
1533                            mSettings.writePackageRestrictionsLPr(userId);
1534                        }
1535                        mDirtyUsers.clear();
1536                    }
1537                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1538                } break;
1539                case WRITE_PACKAGE_LIST: {
1540                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1541                    synchronized (mPackages) {
1542                        removeMessages(WRITE_PACKAGE_LIST);
1543                        mSettings.writePackageListLPr(msg.arg1);
1544                    }
1545                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1546                } break;
1547                case CHECK_PENDING_VERIFICATION: {
1548                    final int verificationId = msg.arg1;
1549                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1550
1551                    if ((state != null) && !state.timeoutExtended()) {
1552                        final InstallArgs args = state.getInstallArgs();
1553                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1554
1555                        Slog.i(TAG, "Verification timed out for " + originUri);
1556                        mPendingVerification.remove(verificationId);
1557
1558                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1559
1560                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1561                            Slog.i(TAG, "Continuing with installation of " + originUri);
1562                            state.setVerifierResponse(Binder.getCallingUid(),
1563                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    PackageManager.VERIFICATION_ALLOW,
1566                                    state.getInstallArgs().getUser());
1567                            try {
1568                                ret = args.copyApk(mContainerService, true);
1569                            } catch (RemoteException e) {
1570                                Slog.e(TAG, "Could not contact the ContainerService");
1571                            }
1572                        } else {
1573                            broadcastPackageVerified(verificationId, originUri,
1574                                    PackageManager.VERIFICATION_REJECT,
1575                                    state.getInstallArgs().getUser());
1576                        }
1577
1578                        Trace.asyncTraceEnd(
1579                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1580
1581                        processPendingInstall(args, ret);
1582                        mHandler.sendEmptyMessage(MCS_UNBIND);
1583                    }
1584                    break;
1585                }
1586                case PACKAGE_VERIFIED: {
1587                    final int verificationId = msg.arg1;
1588
1589                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1590                    if (state == null) {
1591                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1592                        break;
1593                    }
1594
1595                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1596
1597                    state.setVerifierResponse(response.callerUid, response.code);
1598
1599                    if (state.isVerificationComplete()) {
1600                        mPendingVerification.remove(verificationId);
1601
1602                        final InstallArgs args = state.getInstallArgs();
1603                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1604
1605                        int ret;
1606                        if (state.isInstallAllowed()) {
1607                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1608                            broadcastPackageVerified(verificationId, originUri,
1609                                    response.code, state.getInstallArgs().getUser());
1610                            try {
1611                                ret = args.copyApk(mContainerService, true);
1612                            } catch (RemoteException e) {
1613                                Slog.e(TAG, "Could not contact the ContainerService");
1614                            }
1615                        } else {
1616                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1617                        }
1618
1619                        Trace.asyncTraceEnd(
1620                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1621
1622                        processPendingInstall(args, ret);
1623                        mHandler.sendEmptyMessage(MCS_UNBIND);
1624                    }
1625
1626                    break;
1627                }
1628                case START_INTENT_FILTER_VERIFICATIONS: {
1629                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1630                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1631                            params.replacing, params.pkg);
1632                    break;
1633                }
1634                case INTENT_FILTER_VERIFIED: {
1635                    final int verificationId = msg.arg1;
1636
1637                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1638                            verificationId);
1639                    if (state == null) {
1640                        Slog.w(TAG, "Invalid IntentFilter verification token "
1641                                + verificationId + " received");
1642                        break;
1643                    }
1644
1645                    final int userId = state.getUserId();
1646
1647                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1648                            "Processing IntentFilter verification with token:"
1649                            + verificationId + " and userId:" + userId);
1650
1651                    final IntentFilterVerificationResponse response =
1652                            (IntentFilterVerificationResponse) msg.obj;
1653
1654                    state.setVerifierResponse(response.callerUid, response.code);
1655
1656                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1657                            "IntentFilter verification with token:" + verificationId
1658                            + " and userId:" + userId
1659                            + " is settings verifier response with response code:"
1660                            + response.code);
1661
1662                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1663                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1664                                + response.getFailedDomainsString());
1665                    }
1666
1667                    if (state.isVerificationComplete()) {
1668                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1669                    } else {
1670                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1671                                "IntentFilter verification with token:" + verificationId
1672                                + " was not said to be complete");
1673                    }
1674
1675                    break;
1676                }
1677                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1678                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1679                            mEphemeralResolverConnection,
1680                            (EphemeralRequest) msg.obj,
1681                            mEphemeralInstallerActivity,
1682                            mHandler);
1683                }
1684            }
1685        }
1686    }
1687
1688    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1689            boolean killApp, String[] grantedPermissions,
1690            boolean launchedForRestore, String installerPackage,
1691            IPackageInstallObserver2 installObserver) {
1692        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1693            // Send the removed broadcasts
1694            if (res.removedInfo != null) {
1695                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1696            }
1697
1698            // Now that we successfully installed the package, grant runtime
1699            // permissions if requested before broadcasting the install.
1700            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1701                    >= Build.VERSION_CODES.M) {
1702                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1703            }
1704
1705            final boolean update = res.removedInfo != null
1706                    && res.removedInfo.removedPackage != null;
1707
1708            // If this is the first time we have child packages for a disabled privileged
1709            // app that had no children, we grant requested runtime permissions to the new
1710            // children if the parent on the system image had them already granted.
1711            if (res.pkg.parentPackage != null) {
1712                synchronized (mPackages) {
1713                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1714                }
1715            }
1716
1717            synchronized (mPackages) {
1718                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1719            }
1720
1721            final String packageName = res.pkg.applicationInfo.packageName;
1722
1723            // Determine the set of users who are adding this package for
1724            // the first time vs. those who are seeing an update.
1725            int[] firstUsers = EMPTY_INT_ARRAY;
1726            int[] updateUsers = EMPTY_INT_ARRAY;
1727            if (res.origUsers == null || res.origUsers.length == 0) {
1728                firstUsers = res.newUsers;
1729            } else {
1730                for (int newUser : res.newUsers) {
1731                    boolean isNew = true;
1732                    for (int origUser : res.origUsers) {
1733                        if (origUser == newUser) {
1734                            isNew = false;
1735                            break;
1736                        }
1737                    }
1738                    if (isNew) {
1739                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1740                    } else {
1741                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1742                    }
1743                }
1744            }
1745
1746            // Send installed broadcasts if the install/update is not ephemeral
1747            if (!isEphemeral(res.pkg)) {
1748                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1749
1750                // Send added for users that see the package for the first time
1751                // sendPackageAddedForNewUsers also deals with system apps
1752                int appId = UserHandle.getAppId(res.uid);
1753                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1754                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1755
1756                // Send added for users that don't see the package for the first time
1757                Bundle extras = new Bundle(1);
1758                extras.putInt(Intent.EXTRA_UID, res.uid);
1759                if (update) {
1760                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1761                }
1762                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1763                        extras, 0 /*flags*/, null /*targetPackage*/,
1764                        null /*finishedReceiver*/, updateUsers);
1765
1766                // Send replaced for users that don't see the package for the first time
1767                if (update) {
1768                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1769                            packageName, extras, 0 /*flags*/,
1770                            null /*targetPackage*/, null /*finishedReceiver*/,
1771                            updateUsers);
1772                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1773                            null /*package*/, null /*extras*/, 0 /*flags*/,
1774                            packageName /*targetPackage*/,
1775                            null /*finishedReceiver*/, updateUsers);
1776                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1777                    // First-install and we did a restore, so we're responsible for the
1778                    // first-launch broadcast.
1779                    if (DEBUG_BACKUP) {
1780                        Slog.i(TAG, "Post-restore of " + packageName
1781                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1782                    }
1783                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1784                }
1785
1786                // Send broadcast package appeared if forward locked/external for all users
1787                // treat asec-hosted packages like removable media on upgrade
1788                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1789                    if (DEBUG_INSTALL) {
1790                        Slog.i(TAG, "upgrading pkg " + res.pkg
1791                                + " is ASEC-hosted -> AVAILABLE");
1792                    }
1793                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1794                    ArrayList<String> pkgList = new ArrayList<>(1);
1795                    pkgList.add(packageName);
1796                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1797                }
1798            }
1799
1800            // Work that needs to happen on first install within each user
1801            if (firstUsers != null && firstUsers.length > 0) {
1802                synchronized (mPackages) {
1803                    for (int userId : firstUsers) {
1804                        // If this app is a browser and it's newly-installed for some
1805                        // users, clear any default-browser state in those users. The
1806                        // app's nature doesn't depend on the user, so we can just check
1807                        // its browser nature in any user and generalize.
1808                        if (packageIsBrowser(packageName, userId)) {
1809                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1810                        }
1811
1812                        // We may also need to apply pending (restored) runtime
1813                        // permission grants within these users.
1814                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1815                    }
1816                }
1817            }
1818
1819            // Log current value of "unknown sources" setting
1820            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1821                    getUnknownSourcesSettings());
1822
1823            // Force a gc to clear up things
1824            Runtime.getRuntime().gc();
1825
1826            // Remove the replaced package's older resources safely now
1827            // We delete after a gc for applications  on sdcard.
1828            if (res.removedInfo != null && res.removedInfo.args != null) {
1829                synchronized (mInstallLock) {
1830                    res.removedInfo.args.doPostDeleteLI(true);
1831                }
1832            }
1833        }
1834
1835        // If someone is watching installs - notify them
1836        if (installObserver != null) {
1837            try {
1838                Bundle extras = extrasForInstallResult(res);
1839                installObserver.onPackageInstalled(res.name, res.returnCode,
1840                        res.returnMsg, extras);
1841            } catch (RemoteException e) {
1842                Slog.i(TAG, "Observer no longer exists.");
1843            }
1844        }
1845    }
1846
1847    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1848            PackageParser.Package pkg) {
1849        if (pkg.parentPackage == null) {
1850            return;
1851        }
1852        if (pkg.requestedPermissions == null) {
1853            return;
1854        }
1855        final PackageSetting disabledSysParentPs = mSettings
1856                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1857        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1858                || !disabledSysParentPs.isPrivileged()
1859                || (disabledSysParentPs.childPackageNames != null
1860                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1861            return;
1862        }
1863        final int[] allUserIds = sUserManager.getUserIds();
1864        final int permCount = pkg.requestedPermissions.size();
1865        for (int i = 0; i < permCount; i++) {
1866            String permission = pkg.requestedPermissions.get(i);
1867            BasePermission bp = mSettings.mPermissions.get(permission);
1868            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1869                continue;
1870            }
1871            for (int userId : allUserIds) {
1872                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1873                        permission, userId)) {
1874                    grantRuntimePermission(pkg.packageName, permission, userId);
1875                }
1876            }
1877        }
1878    }
1879
1880    private StorageEventListener mStorageListener = new StorageEventListener() {
1881        @Override
1882        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1883            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1884                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1885                    final String volumeUuid = vol.getFsUuid();
1886
1887                    // Clean up any users or apps that were removed or recreated
1888                    // while this volume was missing
1889                    reconcileUsers(volumeUuid);
1890                    reconcileApps(volumeUuid);
1891
1892                    // Clean up any install sessions that expired or were
1893                    // cancelled while this volume was missing
1894                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1895
1896                    loadPrivatePackages(vol);
1897
1898                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1899                    unloadPrivatePackages(vol);
1900                }
1901            }
1902
1903            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1904                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1905                    updateExternalMediaStatus(true, false);
1906                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1907                    updateExternalMediaStatus(false, false);
1908                }
1909            }
1910        }
1911
1912        @Override
1913        public void onVolumeForgotten(String fsUuid) {
1914            if (TextUtils.isEmpty(fsUuid)) {
1915                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1916                return;
1917            }
1918
1919            // Remove any apps installed on the forgotten volume
1920            synchronized (mPackages) {
1921                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1922                for (PackageSetting ps : packages) {
1923                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1924                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1925                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1926
1927                    // Try very hard to release any references to this package
1928                    // so we don't risk the system server being killed due to
1929                    // open FDs
1930                    AttributeCache.instance().removePackage(ps.name);
1931                }
1932
1933                mSettings.onVolumeForgotten(fsUuid);
1934                mSettings.writeLPr();
1935            }
1936        }
1937    };
1938
1939    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1940            String[] grantedPermissions) {
1941        for (int userId : userIds) {
1942            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1943        }
1944
1945        // We could have touched GID membership, so flush out packages.list
1946        synchronized (mPackages) {
1947            mSettings.writePackageListLPr();
1948        }
1949    }
1950
1951    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1952            String[] grantedPermissions) {
1953        SettingBase sb = (SettingBase) pkg.mExtras;
1954        if (sb == null) {
1955            return;
1956        }
1957
1958        PermissionsState permissionsState = sb.getPermissionsState();
1959
1960        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1961                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1962
1963        for (String permission : pkg.requestedPermissions) {
1964            final BasePermission bp;
1965            synchronized (mPackages) {
1966                bp = mSettings.mPermissions.get(permission);
1967            }
1968            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1969                    && (grantedPermissions == null
1970                           || ArrayUtils.contains(grantedPermissions, permission))) {
1971                final int flags = permissionsState.getPermissionFlags(permission, userId);
1972                // Installer cannot change immutable permissions.
1973                if ((flags & immutableFlags) == 0) {
1974                    grantRuntimePermission(pkg.packageName, permission, userId);
1975                }
1976            }
1977        }
1978    }
1979
1980    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1981        Bundle extras = null;
1982        switch (res.returnCode) {
1983            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1984                extras = new Bundle();
1985                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1986                        res.origPermission);
1987                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1988                        res.origPackage);
1989                break;
1990            }
1991            case PackageManager.INSTALL_SUCCEEDED: {
1992                extras = new Bundle();
1993                extras.putBoolean(Intent.EXTRA_REPLACING,
1994                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1995                break;
1996            }
1997        }
1998        return extras;
1999    }
2000
2001    void scheduleWriteSettingsLocked() {
2002        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2003            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2004        }
2005    }
2006
2007    void scheduleWritePackageListLocked(int userId) {
2008        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2009            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2010            msg.arg1 = userId;
2011            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2012        }
2013    }
2014
2015    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2016        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2017        scheduleWritePackageRestrictionsLocked(userId);
2018    }
2019
2020    void scheduleWritePackageRestrictionsLocked(int userId) {
2021        final int[] userIds = (userId == UserHandle.USER_ALL)
2022                ? sUserManager.getUserIds() : new int[]{userId};
2023        for (int nextUserId : userIds) {
2024            if (!sUserManager.exists(nextUserId)) return;
2025            mDirtyUsers.add(nextUserId);
2026            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2027                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2028            }
2029        }
2030    }
2031
2032    public static PackageManagerService main(Context context, Installer installer,
2033            boolean factoryTest, boolean onlyCore) {
2034        // Self-check for initial settings.
2035        PackageManagerServiceCompilerMapping.checkProperties();
2036
2037        PackageManagerService m = new PackageManagerService(context, installer,
2038                factoryTest, onlyCore);
2039        m.enableSystemUserPackages();
2040        ServiceManager.addService("package", m);
2041        return m;
2042    }
2043
2044    private void enableSystemUserPackages() {
2045        if (!UserManager.isSplitSystemUser()) {
2046            return;
2047        }
2048        // For system user, enable apps based on the following conditions:
2049        // - app is whitelisted or belong to one of these groups:
2050        //   -- system app which has no launcher icons
2051        //   -- system app which has INTERACT_ACROSS_USERS permission
2052        //   -- system IME app
2053        // - app is not in the blacklist
2054        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2055        Set<String> enableApps = new ArraySet<>();
2056        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2057                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2058                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2059        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2060        enableApps.addAll(wlApps);
2061        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2062                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2063        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2064        enableApps.removeAll(blApps);
2065        Log.i(TAG, "Applications installed for system user: " + enableApps);
2066        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2067                UserHandle.SYSTEM);
2068        final int allAppsSize = allAps.size();
2069        synchronized (mPackages) {
2070            for (int i = 0; i < allAppsSize; i++) {
2071                String pName = allAps.get(i);
2072                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2073                // Should not happen, but we shouldn't be failing if it does
2074                if (pkgSetting == null) {
2075                    continue;
2076                }
2077                boolean install = enableApps.contains(pName);
2078                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2079                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2080                            + " for system user");
2081                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2082                }
2083            }
2084        }
2085    }
2086
2087    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2088        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2089                Context.DISPLAY_SERVICE);
2090        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2091    }
2092
2093    /**
2094     * Requests that files preopted on a secondary system partition be copied to the data partition
2095     * if possible.  Note that the actual copying of the files is accomplished by init for security
2096     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2097     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2098     */
2099    private static void requestCopyPreoptedFiles() {
2100        final int WAIT_TIME_MS = 100;
2101        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2102        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2103            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2104            // We will wait for up to 100 seconds.
2105            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2106            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2107                try {
2108                    Thread.sleep(WAIT_TIME_MS);
2109                } catch (InterruptedException e) {
2110                    // Do nothing
2111                }
2112                if (SystemClock.uptimeMillis() > timeEnd) {
2113                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2114                    Slog.wtf(TAG, "cppreopt did not finish!");
2115                    break;
2116                }
2117            }
2118        }
2119    }
2120
2121    public PackageManagerService(Context context, Installer installer,
2122            boolean factoryTest, boolean onlyCore) {
2123        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2124        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2125                SystemClock.uptimeMillis());
2126
2127        if (mSdkVersion <= 0) {
2128            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2129        }
2130
2131        mContext = context;
2132
2133        mPermissionReviewRequired = context.getResources().getBoolean(
2134                R.bool.config_permissionReviewRequired);
2135
2136        mFactoryTest = factoryTest;
2137        mOnlyCore = onlyCore;
2138        mMetrics = new DisplayMetrics();
2139        mSettings = new Settings(mPackages);
2140        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2141                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2142        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2143                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2144        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2145                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2146        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2147                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2148        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2149                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2150        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2151                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2152
2153        String separateProcesses = SystemProperties.get("debug.separate_processes");
2154        if (separateProcesses != null && separateProcesses.length() > 0) {
2155            if ("*".equals(separateProcesses)) {
2156                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2157                mSeparateProcesses = null;
2158                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2159            } else {
2160                mDefParseFlags = 0;
2161                mSeparateProcesses = separateProcesses.split(",");
2162                Slog.w(TAG, "Running with debug.separate_processes: "
2163                        + separateProcesses);
2164            }
2165        } else {
2166            mDefParseFlags = 0;
2167            mSeparateProcesses = null;
2168        }
2169
2170        mInstaller = installer;
2171        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2172                "*dexopt*");
2173        mDexManager = new DexManager();
2174        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2175
2176        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2177                FgThread.get().getLooper());
2178
2179        getDefaultDisplayMetrics(context, mMetrics);
2180
2181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2182        SystemConfig systemConfig = SystemConfig.getInstance();
2183        mGlobalGids = systemConfig.getGlobalGids();
2184        mSystemPermissions = systemConfig.getSystemPermissions();
2185        mAvailableFeatures = systemConfig.getAvailableFeatures();
2186        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2187
2188        mProtectedPackages = new ProtectedPackages(mContext);
2189
2190        synchronized (mInstallLock) {
2191        // writer
2192        synchronized (mPackages) {
2193            mHandlerThread = new ServiceThread(TAG,
2194                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2195            mHandlerThread.start();
2196            mHandler = new PackageHandler(mHandlerThread.getLooper());
2197            mProcessLoggingHandler = new ProcessLoggingHandler();
2198            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2199
2200            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2201
2202            File dataDir = Environment.getDataDirectory();
2203            mAppInstallDir = new File(dataDir, "app");
2204            mAppLib32InstallDir = new File(dataDir, "app-lib");
2205            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2206            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2207            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2208
2209            sUserManager = new UserManagerService(context, this, mPackages);
2210
2211            // Propagate permission configuration in to package manager.
2212            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2213                    = systemConfig.getPermissions();
2214            for (int i=0; i<permConfig.size(); i++) {
2215                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2216                BasePermission bp = mSettings.mPermissions.get(perm.name);
2217                if (bp == null) {
2218                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2219                    mSettings.mPermissions.put(perm.name, bp);
2220                }
2221                if (perm.gids != null) {
2222                    bp.setGids(perm.gids, perm.perUser);
2223                }
2224            }
2225
2226            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2227            for (int i=0; i<libConfig.size(); i++) {
2228                mSharedLibraries.put(libConfig.keyAt(i),
2229                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2230            }
2231
2232            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2233
2234            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2235            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2236            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2237
2238            // Clean up orphaned packages for which the code path doesn't exist
2239            // and they are an update to a system app - caused by bug/32321269
2240            final int packageSettingCount = mSettings.mPackages.size();
2241            for (int i = packageSettingCount - 1; i >= 0; i--) {
2242                PackageSetting ps = mSettings.mPackages.valueAt(i);
2243                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2244                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2245                    mSettings.mPackages.removeAt(i);
2246                    mSettings.enableSystemPackageLPw(ps.name);
2247                }
2248            }
2249
2250            if (mFirstBoot) {
2251                requestCopyPreoptedFiles();
2252            }
2253
2254            String customResolverActivity = Resources.getSystem().getString(
2255                    R.string.config_customResolverActivity);
2256            if (TextUtils.isEmpty(customResolverActivity)) {
2257                customResolverActivity = null;
2258            } else {
2259                mCustomResolverComponentName = ComponentName.unflattenFromString(
2260                        customResolverActivity);
2261            }
2262
2263            long startTime = SystemClock.uptimeMillis();
2264
2265            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2266                    startTime);
2267
2268            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2269            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2270
2271            if (bootClassPath == null) {
2272                Slog.w(TAG, "No BOOTCLASSPATH found!");
2273            }
2274
2275            if (systemServerClassPath == null) {
2276                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2277            }
2278
2279            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2280            final String[] dexCodeInstructionSets =
2281                    getDexCodeInstructionSets(
2282                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2283
2284            /**
2285             * Ensure all external libraries have had dexopt run on them.
2286             */
2287            if (mSharedLibraries.size() > 0) {
2288                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2289                // NOTE: For now, we're compiling these system "shared libraries"
2290                // (and framework jars) into all available architectures. It's possible
2291                // to compile them only when we come across an app that uses them (there's
2292                // already logic for that in scanPackageLI) but that adds some complexity.
2293                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2294                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2295                        final String lib = libEntry.path;
2296                        if (lib == null) {
2297                            continue;
2298                        }
2299
2300                        try {
2301                            // Shared libraries do not have profiles so we perform a full
2302                            // AOT compilation (if needed).
2303                            int dexoptNeeded = DexFile.getDexOptNeeded(
2304                                    lib, dexCodeInstructionSet,
2305                                    getCompilerFilterForReason(REASON_SHARED_APK),
2306                                    false /* newProfile */);
2307                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2308                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2309                                        dexCodeInstructionSet, dexoptNeeded, null,
2310                                        DEXOPT_PUBLIC,
2311                                        getCompilerFilterForReason(REASON_SHARED_APK),
2312                                        StorageManager.UUID_PRIVATE_INTERNAL,
2313                                        SKIP_SHARED_LIBRARY_CHECK);
2314                            }
2315                        } catch (FileNotFoundException e) {
2316                            Slog.w(TAG, "Library not found: " + lib);
2317                        } catch (IOException | InstallerException e) {
2318                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2319                                    + e.getMessage());
2320                        }
2321                    }
2322                }
2323                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2324            }
2325
2326            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2327
2328            final VersionInfo ver = mSettings.getInternalVersion();
2329            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2330
2331            // when upgrading from pre-M, promote system app permissions from install to runtime
2332            mPromoteSystemApps =
2333                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2334
2335            // When upgrading from pre-N, we need to handle package extraction like first boot,
2336            // as there is no profiling data available.
2337            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2338
2339            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2340
2341            // save off the names of pre-existing system packages prior to scanning; we don't
2342            // want to automatically grant runtime permissions for new system apps
2343            if (mPromoteSystemApps) {
2344                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2345                while (pkgSettingIter.hasNext()) {
2346                    PackageSetting ps = pkgSettingIter.next();
2347                    if (isSystemApp(ps)) {
2348                        mExistingSystemPackages.add(ps.name);
2349                    }
2350                }
2351            }
2352
2353            // Set flag to monitor and not change apk file paths when
2354            // scanning install directories.
2355            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2356
2357            if (mIsUpgrade || mFirstBoot) {
2358                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2359            }
2360
2361            // Collect vendor overlay packages. (Do this before scanning any apps.)
2362            // For security and version matching reason, only consider
2363            // overlay packages if they reside in the right directory.
2364            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2365            if (overlayThemeDir.isEmpty()) {
2366                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2367            }
2368            if (!overlayThemeDir.isEmpty()) {
2369                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2370                        | PackageParser.PARSE_IS_SYSTEM
2371                        | PackageParser.PARSE_IS_SYSTEM_DIR
2372                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2373            }
2374            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2375                    | PackageParser.PARSE_IS_SYSTEM
2376                    | PackageParser.PARSE_IS_SYSTEM_DIR
2377                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2378
2379            // Find base frameworks (resource packages without code).
2380            scanDirTracedLI(frameworkDir, mDefParseFlags
2381                    | PackageParser.PARSE_IS_SYSTEM
2382                    | PackageParser.PARSE_IS_SYSTEM_DIR
2383                    | PackageParser.PARSE_IS_PRIVILEGED,
2384                    scanFlags | SCAN_NO_DEX, 0);
2385
2386            // Collected privileged system packages.
2387            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2388            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2389                    | PackageParser.PARSE_IS_SYSTEM
2390                    | PackageParser.PARSE_IS_SYSTEM_DIR
2391                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2392
2393            // Collect ordinary system packages.
2394            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2395            scanDirTracedLI(systemAppDir, mDefParseFlags
2396                    | PackageParser.PARSE_IS_SYSTEM
2397                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2398
2399            // Collect all vendor packages.
2400            File vendorAppDir = new File("/vendor/app");
2401            try {
2402                vendorAppDir = vendorAppDir.getCanonicalFile();
2403            } catch (IOException e) {
2404                // failed to look up canonical path, continue with original one
2405            }
2406            scanDirTracedLI(vendorAppDir, mDefParseFlags
2407                    | PackageParser.PARSE_IS_SYSTEM
2408                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2409
2410            // Collect all OEM packages.
2411            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2412            scanDirTracedLI(oemAppDir, mDefParseFlags
2413                    | PackageParser.PARSE_IS_SYSTEM
2414                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2415
2416            // Prune any system packages that no longer exist.
2417            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2418            if (!mOnlyCore) {
2419                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2420                while (psit.hasNext()) {
2421                    PackageSetting ps = psit.next();
2422
2423                    /*
2424                     * If this is not a system app, it can't be a
2425                     * disable system app.
2426                     */
2427                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2428                        continue;
2429                    }
2430
2431                    /*
2432                     * If the package is scanned, it's not erased.
2433                     */
2434                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2435                    if (scannedPkg != null) {
2436                        /*
2437                         * If the system app is both scanned and in the
2438                         * disabled packages list, then it must have been
2439                         * added via OTA. Remove it from the currently
2440                         * scanned package so the previously user-installed
2441                         * application can be scanned.
2442                         */
2443                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2444                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2445                                    + ps.name + "; removing system app.  Last known codePath="
2446                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2447                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2448                                    + scannedPkg.mVersionCode);
2449                            removePackageLI(scannedPkg, true);
2450                            mExpectingBetter.put(ps.name, ps.codePath);
2451                        }
2452
2453                        continue;
2454                    }
2455
2456                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2457                        psit.remove();
2458                        logCriticalInfo(Log.WARN, "System package " + ps.name
2459                                + " no longer exists; it's data will be wiped");
2460                        // Actual deletion of code and data will be handled by later
2461                        // reconciliation step
2462                    } else {
2463                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2464                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2465                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2466                        }
2467                    }
2468                }
2469            }
2470
2471            //look for any incomplete package installations
2472            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2473            for (int i = 0; i < deletePkgsList.size(); i++) {
2474                // Actual deletion of code and data will be handled by later
2475                // reconciliation step
2476                final String packageName = deletePkgsList.get(i).name;
2477                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2478                synchronized (mPackages) {
2479                    mSettings.removePackageLPw(packageName);
2480                }
2481            }
2482
2483            //delete tmp files
2484            deleteTempPackageFiles();
2485
2486            // Remove any shared userIDs that have no associated packages
2487            mSettings.pruneSharedUsersLPw();
2488
2489            if (!mOnlyCore) {
2490                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2491                        SystemClock.uptimeMillis());
2492                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2493
2494                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2495                        | PackageParser.PARSE_FORWARD_LOCK,
2496                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2497
2498                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2499                        | PackageParser.PARSE_IS_EPHEMERAL,
2500                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2501
2502                /**
2503                 * Remove disable package settings for any updated system
2504                 * apps that were removed via an OTA. If they're not a
2505                 * previously-updated app, remove them completely.
2506                 * Otherwise, just revoke their system-level permissions.
2507                 */
2508                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2509                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2510                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2511
2512                    String msg;
2513                    if (deletedPkg == null) {
2514                        msg = "Updated system package " + deletedAppName
2515                                + " no longer exists; it's data will be wiped";
2516                        // Actual deletion of code and data will be handled by later
2517                        // reconciliation step
2518                    } else {
2519                        msg = "Updated system app + " + deletedAppName
2520                                + " no longer present; removing system privileges for "
2521                                + deletedAppName;
2522
2523                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2524
2525                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2526                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2527                    }
2528                    logCriticalInfo(Log.WARN, msg);
2529                }
2530
2531                /**
2532                 * Make sure all system apps that we expected to appear on
2533                 * the userdata partition actually showed up. If they never
2534                 * appeared, crawl back and revive the system version.
2535                 */
2536                for (int i = 0; i < mExpectingBetter.size(); i++) {
2537                    final String packageName = mExpectingBetter.keyAt(i);
2538                    if (!mPackages.containsKey(packageName)) {
2539                        final File scanFile = mExpectingBetter.valueAt(i);
2540
2541                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2542                                + " but never showed up; reverting to system");
2543
2544                        int reparseFlags = mDefParseFlags;
2545                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2546                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2547                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2548                                    | PackageParser.PARSE_IS_PRIVILEGED;
2549                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2550                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2551                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2552                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2553                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2554                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2555                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2556                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2557                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2558                        } else {
2559                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2560                            continue;
2561                        }
2562
2563                        mSettings.enableSystemPackageLPw(packageName);
2564
2565                        try {
2566                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2567                        } catch (PackageManagerException e) {
2568                            Slog.e(TAG, "Failed to parse original system package: "
2569                                    + e.getMessage());
2570                        }
2571                    }
2572                }
2573            }
2574            mExpectingBetter.clear();
2575
2576            // Resolve the storage manager.
2577            mStorageManagerPackage = getStorageManagerPackageName();
2578
2579            // Resolve protected action filters. Only the setup wizard is allowed to
2580            // have a high priority filter for these actions.
2581            mSetupWizardPackage = getSetupWizardPackageName();
2582            if (mProtectedFilters.size() > 0) {
2583                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2584                    Slog.i(TAG, "No setup wizard;"
2585                        + " All protected intents capped to priority 0");
2586                }
2587                for (ActivityIntentInfo filter : mProtectedFilters) {
2588                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2589                        if (DEBUG_FILTERS) {
2590                            Slog.i(TAG, "Found setup wizard;"
2591                                + " allow priority " + filter.getPriority() + ";"
2592                                + " package: " + filter.activity.info.packageName
2593                                + " activity: " + filter.activity.className
2594                                + " priority: " + filter.getPriority());
2595                        }
2596                        // skip setup wizard; allow it to keep the high priority filter
2597                        continue;
2598                    }
2599                    Slog.w(TAG, "Protected action; cap priority to 0;"
2600                            + " package: " + filter.activity.info.packageName
2601                            + " activity: " + filter.activity.className
2602                            + " origPrio: " + filter.getPriority());
2603                    filter.setPriority(0);
2604                }
2605            }
2606            mDeferProtectedFilters = false;
2607            mProtectedFilters.clear();
2608
2609            // Now that we know all of the shared libraries, update all clients to have
2610            // the correct library paths.
2611            updateAllSharedLibrariesLPw();
2612
2613            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2614                // NOTE: We ignore potential failures here during a system scan (like
2615                // the rest of the commands above) because there's precious little we
2616                // can do about it. A settings error is reported, though.
2617                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2618            }
2619
2620            // Now that we know all the packages we are keeping,
2621            // read and update their last usage times.
2622            mPackageUsage.read(mPackages);
2623            mCompilerStats.read();
2624
2625            // Read and update the usage of dex files.
2626            // At this point we know the code paths  of the packages, so we can validate
2627            // the disk file and build the internal cache.
2628            // The usage file is expected to be small so loading and verifying it
2629            // should take a fairly small time compare to the other activities (e.g. package
2630            // scanning).
2631            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2632            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2633            for (int userId : currentUserIds) {
2634                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2635            }
2636            mDexManager.load(userPackages);
2637
2638            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2639                    SystemClock.uptimeMillis());
2640            Slog.i(TAG, "Time to scan packages: "
2641                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2642                    + " seconds");
2643
2644            // If the platform SDK has changed since the last time we booted,
2645            // we need to re-grant app permission to catch any new ones that
2646            // appear.  This is really a hack, and means that apps can in some
2647            // cases get permissions that the user didn't initially explicitly
2648            // allow...  it would be nice to have some better way to handle
2649            // this situation.
2650            int updateFlags = UPDATE_PERMISSIONS_ALL;
2651            if (ver.sdkVersion != mSdkVersion) {
2652                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2653                        + mSdkVersion + "; regranting permissions for internal storage");
2654                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2655            }
2656            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2657            ver.sdkVersion = mSdkVersion;
2658
2659            // If this is the first boot or an update from pre-M, and it is a normal
2660            // boot, then we need to initialize the default preferred apps across
2661            // all defined users.
2662            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2663                for (UserInfo user : sUserManager.getUsers(true)) {
2664                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2665                    applyFactoryDefaultBrowserLPw(user.id);
2666                    primeDomainVerificationsLPw(user.id);
2667                }
2668            }
2669
2670            // Prepare storage for system user really early during boot,
2671            // since core system apps like SettingsProvider and SystemUI
2672            // can't wait for user to start
2673            final int storageFlags;
2674            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2675                storageFlags = StorageManager.FLAG_STORAGE_DE;
2676            } else {
2677                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2678            }
2679            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2680                    storageFlags, true /* migrateAppData */);
2681
2682            // If this is first boot after an OTA, and a normal boot, then
2683            // we need to clear code cache directories.
2684            // Note that we do *not* clear the application profiles. These remain valid
2685            // across OTAs and are used to drive profile verification (post OTA) and
2686            // profile compilation (without waiting to collect a fresh set of profiles).
2687            if (mIsUpgrade && !onlyCore) {
2688                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2689                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2690                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2691                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2692                        // No apps are running this early, so no need to freeze
2693                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2694                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2695                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2696                    }
2697                }
2698                ver.fingerprint = Build.FINGERPRINT;
2699            }
2700
2701            checkDefaultBrowser();
2702
2703            // clear only after permissions and other defaults have been updated
2704            mExistingSystemPackages.clear();
2705            mPromoteSystemApps = false;
2706
2707            // All the changes are done during package scanning.
2708            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2709
2710            // can downgrade to reader
2711            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2712            mSettings.writeLPr();
2713            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2714
2715            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2716            // early on (before the package manager declares itself as early) because other
2717            // components in the system server might ask for package contexts for these apps.
2718            //
2719            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2720            // (i.e, that the data partition is unavailable).
2721            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2722                long start = System.nanoTime();
2723                List<PackageParser.Package> coreApps = new ArrayList<>();
2724                for (PackageParser.Package pkg : mPackages.values()) {
2725                    if (pkg.coreApp) {
2726                        coreApps.add(pkg);
2727                    }
2728                }
2729
2730                int[] stats = performDexOptUpgrade(coreApps, false,
2731                        getCompilerFilterForReason(REASON_CORE_APP));
2732
2733                final int elapsedTimeSeconds =
2734                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2735                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2736
2737                if (DEBUG_DEXOPT) {
2738                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2739                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2740                }
2741
2742
2743                // TODO: Should we log these stats to tron too ?
2744                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2745                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2746                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2747                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2748            }
2749
2750            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2751                    SystemClock.uptimeMillis());
2752
2753            if (!mOnlyCore) {
2754                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2755                mRequiredInstallerPackage = getRequiredInstallerLPr();
2756                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2757                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2758                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2759                        mIntentFilterVerifierComponent);
2760                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2761                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2762                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2763                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2764            } else {
2765                mRequiredVerifierPackage = null;
2766                mRequiredInstallerPackage = null;
2767                mRequiredUninstallerPackage = null;
2768                mIntentFilterVerifierComponent = null;
2769                mIntentFilterVerifier = null;
2770                mServicesSystemSharedLibraryPackageName = null;
2771                mSharedSystemSharedLibraryPackageName = null;
2772            }
2773
2774            mInstallerService = new PackageInstallerService(context, this);
2775
2776            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2777            if (ephemeralResolverComponent != null) {
2778                if (DEBUG_EPHEMERAL) {
2779                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2780                }
2781                mEphemeralResolverConnection =
2782                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2783            } else {
2784                mEphemeralResolverConnection = null;
2785            }
2786            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2787            if (mEphemeralInstallerComponent != null) {
2788                if (DEBUG_EPHEMERAL) {
2789                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2790                }
2791                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2792            }
2793
2794            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2795        } // synchronized (mPackages)
2796        } // synchronized (mInstallLock)
2797
2798        // Now after opening every single application zip, make sure they
2799        // are all flushed.  Not really needed, but keeps things nice and
2800        // tidy.
2801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2802        Runtime.getRuntime().gc();
2803        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2804
2805        // The initial scanning above does many calls into installd while
2806        // holding the mPackages lock, but we're mostly interested in yelling
2807        // once we have a booted system.
2808        mInstaller.setWarnIfHeld(mPackages);
2809
2810        // Expose private service for system components to use.
2811        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2812        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2813    }
2814
2815    @Override
2816    public boolean isFirstBoot() {
2817        return mFirstBoot;
2818    }
2819
2820    @Override
2821    public boolean isOnlyCoreApps() {
2822        return mOnlyCore;
2823    }
2824
2825    @Override
2826    public boolean isUpgrade() {
2827        return mIsUpgrade;
2828    }
2829
2830    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2831        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2832
2833        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2834                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2835                UserHandle.USER_SYSTEM);
2836        if (matches.size() == 1) {
2837            return matches.get(0).getComponentInfo().packageName;
2838        } else if (matches.size() == 0) {
2839            Log.e(TAG, "There should probably be a verifier, but, none were found");
2840            return null;
2841        }
2842        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2843    }
2844
2845    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2846        synchronized (mPackages) {
2847            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2848            if (libraryEntry == null) {
2849                throw new IllegalStateException("Missing required shared library:" + libraryName);
2850            }
2851            return libraryEntry.apk;
2852        }
2853    }
2854
2855    private @NonNull String getRequiredInstallerLPr() {
2856        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2857        intent.addCategory(Intent.CATEGORY_DEFAULT);
2858        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2859
2860        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2861                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2862                UserHandle.USER_SYSTEM);
2863        if (matches.size() == 1) {
2864            ResolveInfo resolveInfo = matches.get(0);
2865            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2866                throw new RuntimeException("The installer must be a privileged app");
2867            }
2868            return matches.get(0).getComponentInfo().packageName;
2869        } else {
2870            throw new RuntimeException("There must be exactly one installer; found " + matches);
2871        }
2872    }
2873
2874    private @NonNull String getRequiredUninstallerLPr() {
2875        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2876        intent.addCategory(Intent.CATEGORY_DEFAULT);
2877        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2878
2879        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2880                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2881                UserHandle.USER_SYSTEM);
2882        if (resolveInfo == null ||
2883                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2884            throw new RuntimeException("There must be exactly one uninstaller; found "
2885                    + resolveInfo);
2886        }
2887        return resolveInfo.getComponentInfo().packageName;
2888    }
2889
2890    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2891        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2892
2893        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2894                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2895                UserHandle.USER_SYSTEM);
2896        ResolveInfo best = null;
2897        final int N = matches.size();
2898        for (int i = 0; i < N; i++) {
2899            final ResolveInfo cur = matches.get(i);
2900            final String packageName = cur.getComponentInfo().packageName;
2901            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2902                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2903                continue;
2904            }
2905
2906            if (best == null || cur.priority > best.priority) {
2907                best = cur;
2908            }
2909        }
2910
2911        if (best != null) {
2912            return best.getComponentInfo().getComponentName();
2913        } else {
2914            throw new RuntimeException("There must be at least one intent filter verifier");
2915        }
2916    }
2917
2918    private @Nullable ComponentName getEphemeralResolverLPr() {
2919        final String[] packageArray =
2920                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2921        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2922            if (DEBUG_EPHEMERAL) {
2923                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2924            }
2925            return null;
2926        }
2927
2928        final int resolveFlags =
2929                MATCH_DIRECT_BOOT_AWARE
2930                | MATCH_DIRECT_BOOT_UNAWARE
2931                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2932        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2933        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2934                resolveFlags, UserHandle.USER_SYSTEM);
2935
2936        final int N = resolvers.size();
2937        if (N == 0) {
2938            if (DEBUG_EPHEMERAL) {
2939                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2940            }
2941            return null;
2942        }
2943
2944        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2945        for (int i = 0; i < N; i++) {
2946            final ResolveInfo info = resolvers.get(i);
2947
2948            if (info.serviceInfo == null) {
2949                continue;
2950            }
2951
2952            final String packageName = info.serviceInfo.packageName;
2953            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2954                if (DEBUG_EPHEMERAL) {
2955                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2956                            + " pkg: " + packageName + ", info:" + info);
2957                }
2958                continue;
2959            }
2960
2961            if (DEBUG_EPHEMERAL) {
2962                Slog.v(TAG, "Ephemeral resolver found;"
2963                        + " pkg: " + packageName + ", info:" + info);
2964            }
2965            return new ComponentName(packageName, info.serviceInfo.name);
2966        }
2967        if (DEBUG_EPHEMERAL) {
2968            Slog.v(TAG, "Ephemeral resolver NOT found");
2969        }
2970        return null;
2971    }
2972
2973    private @Nullable ComponentName getEphemeralInstallerLPr() {
2974        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2975        intent.addCategory(Intent.CATEGORY_DEFAULT);
2976        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2977
2978        final int resolveFlags =
2979                MATCH_DIRECT_BOOT_AWARE
2980                | MATCH_DIRECT_BOOT_UNAWARE
2981                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2982        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2983                resolveFlags, UserHandle.USER_SYSTEM);
2984        Iterator<ResolveInfo> iter = matches.iterator();
2985        while (iter.hasNext()) {
2986            final ResolveInfo rInfo = iter.next();
2987            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
2988            if (ps != null) {
2989                final PermissionsState permissionsState = ps.getPermissionsState();
2990                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
2991                    continue;
2992                }
2993            }
2994            iter.remove();
2995        }
2996        if (matches.size() == 0) {
2997            return null;
2998        } else if (matches.size() == 1) {
2999            return matches.get(0).getComponentInfo().getComponentName();
3000        } else {
3001            throw new RuntimeException(
3002                    "There must be at most one ephemeral installer; found " + matches);
3003        }
3004    }
3005
3006    private void primeDomainVerificationsLPw(int userId) {
3007        if (DEBUG_DOMAIN_VERIFICATION) {
3008            Slog.d(TAG, "Priming domain verifications in user " + userId);
3009        }
3010
3011        SystemConfig systemConfig = SystemConfig.getInstance();
3012        ArraySet<String> packages = systemConfig.getLinkedApps();
3013
3014        for (String packageName : packages) {
3015            PackageParser.Package pkg = mPackages.get(packageName);
3016            if (pkg != null) {
3017                if (!pkg.isSystemApp()) {
3018                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3019                    continue;
3020                }
3021
3022                ArraySet<String> domains = null;
3023                for (PackageParser.Activity a : pkg.activities) {
3024                    for (ActivityIntentInfo filter : a.intents) {
3025                        if (hasValidDomains(filter)) {
3026                            if (domains == null) {
3027                                domains = new ArraySet<String>();
3028                            }
3029                            domains.addAll(filter.getHostsList());
3030                        }
3031                    }
3032                }
3033
3034                if (domains != null && domains.size() > 0) {
3035                    if (DEBUG_DOMAIN_VERIFICATION) {
3036                        Slog.v(TAG, "      + " + packageName);
3037                    }
3038                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3039                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3040                    // and then 'always' in the per-user state actually used for intent resolution.
3041                    final IntentFilterVerificationInfo ivi;
3042                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3043                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3044                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3045                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3046                } else {
3047                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3048                            + "' does not handle web links");
3049                }
3050            } else {
3051                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3052            }
3053        }
3054
3055        scheduleWritePackageRestrictionsLocked(userId);
3056        scheduleWriteSettingsLocked();
3057    }
3058
3059    private void applyFactoryDefaultBrowserLPw(int userId) {
3060        // The default browser app's package name is stored in a string resource,
3061        // with a product-specific overlay used for vendor customization.
3062        String browserPkg = mContext.getResources().getString(
3063                com.android.internal.R.string.default_browser);
3064        if (!TextUtils.isEmpty(browserPkg)) {
3065            // non-empty string => required to be a known package
3066            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3067            if (ps == null) {
3068                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3069                browserPkg = null;
3070            } else {
3071                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3072            }
3073        }
3074
3075        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3076        // default.  If there's more than one, just leave everything alone.
3077        if (browserPkg == null) {
3078            calculateDefaultBrowserLPw(userId);
3079        }
3080    }
3081
3082    private void calculateDefaultBrowserLPw(int userId) {
3083        List<String> allBrowsers = resolveAllBrowserApps(userId);
3084        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3085        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3086    }
3087
3088    private List<String> resolveAllBrowserApps(int userId) {
3089        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3090        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3091                PackageManager.MATCH_ALL, userId);
3092
3093        final int count = list.size();
3094        List<String> result = new ArrayList<String>(count);
3095        for (int i=0; i<count; i++) {
3096            ResolveInfo info = list.get(i);
3097            if (info.activityInfo == null
3098                    || !info.handleAllWebDataURI
3099                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3100                    || result.contains(info.activityInfo.packageName)) {
3101                continue;
3102            }
3103            result.add(info.activityInfo.packageName);
3104        }
3105
3106        return result;
3107    }
3108
3109    private boolean packageIsBrowser(String packageName, int userId) {
3110        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3111                PackageManager.MATCH_ALL, userId);
3112        final int N = list.size();
3113        for (int i = 0; i < N; i++) {
3114            ResolveInfo info = list.get(i);
3115            if (packageName.equals(info.activityInfo.packageName)) {
3116                return true;
3117            }
3118        }
3119        return false;
3120    }
3121
3122    private void checkDefaultBrowser() {
3123        final int myUserId = UserHandle.myUserId();
3124        final String packageName = getDefaultBrowserPackageName(myUserId);
3125        if (packageName != null) {
3126            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3127            if (info == null) {
3128                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3129                synchronized (mPackages) {
3130                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3131                }
3132            }
3133        }
3134    }
3135
3136    @Override
3137    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3138            throws RemoteException {
3139        try {
3140            return super.onTransact(code, data, reply, flags);
3141        } catch (RuntimeException e) {
3142            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3143                Slog.wtf(TAG, "Package Manager Crash", e);
3144            }
3145            throw e;
3146        }
3147    }
3148
3149    static int[] appendInts(int[] cur, int[] add) {
3150        if (add == null) return cur;
3151        if (cur == null) return add;
3152        final int N = add.length;
3153        for (int i=0; i<N; i++) {
3154            cur = appendInt(cur, add[i]);
3155        }
3156        return cur;
3157    }
3158
3159    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3160        if (!sUserManager.exists(userId)) return null;
3161        if (ps == null) {
3162            return null;
3163        }
3164        final PackageParser.Package p = ps.pkg;
3165        if (p == null) {
3166            return null;
3167        }
3168
3169        final PermissionsState permissionsState = ps.getPermissionsState();
3170
3171        // Compute GIDs only if requested
3172        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3173                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3174        // Compute granted permissions only if package has requested permissions
3175        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3176                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3177        final PackageUserState state = ps.readUserState(userId);
3178
3179        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3180                && ps.isSystem()) {
3181            flags |= MATCH_ANY_USER;
3182        }
3183
3184        return PackageParser.generatePackageInfo(p, gids, flags,
3185                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3186    }
3187
3188    @Override
3189    public void checkPackageStartable(String packageName, int userId) {
3190        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3191
3192        synchronized (mPackages) {
3193            final PackageSetting ps = mSettings.mPackages.get(packageName);
3194            if (ps == null) {
3195                throw new SecurityException("Package " + packageName + " was not found!");
3196            }
3197
3198            if (!ps.getInstalled(userId)) {
3199                throw new SecurityException(
3200                        "Package " + packageName + " was not installed for user " + userId + "!");
3201            }
3202
3203            if (mSafeMode && !ps.isSystem()) {
3204                throw new SecurityException("Package " + packageName + " not a system app!");
3205            }
3206
3207            if (mFrozenPackages.contains(packageName)) {
3208                throw new SecurityException("Package " + packageName + " is currently frozen!");
3209            }
3210
3211            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3212                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3213                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3214            }
3215        }
3216    }
3217
3218    @Override
3219    public boolean isPackageAvailable(String packageName, int userId) {
3220        if (!sUserManager.exists(userId)) return false;
3221        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3222                false /* requireFullPermission */, false /* checkShell */, "is package available");
3223        synchronized (mPackages) {
3224            PackageParser.Package p = mPackages.get(packageName);
3225            if (p != null) {
3226                final PackageSetting ps = (PackageSetting) p.mExtras;
3227                if (ps != null) {
3228                    final PackageUserState state = ps.readUserState(userId);
3229                    if (state != null) {
3230                        return PackageParser.isAvailable(state);
3231                    }
3232                }
3233            }
3234        }
3235        return false;
3236    }
3237
3238    @Override
3239    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3240        if (!sUserManager.exists(userId)) return null;
3241        flags = updateFlagsForPackage(flags, userId, packageName);
3242        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3243                false /* requireFullPermission */, false /* checkShell */, "get package info");
3244
3245        // reader
3246        synchronized (mPackages) {
3247            // Normalize package name to hanlde renamed packages
3248            packageName = normalizePackageNameLPr(packageName);
3249
3250            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3251            PackageParser.Package p = null;
3252            if (matchFactoryOnly) {
3253                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3254                if (ps != null) {
3255                    return generatePackageInfo(ps, flags, userId);
3256                }
3257            }
3258            if (p == null) {
3259                p = mPackages.get(packageName);
3260                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3261                    return null;
3262                }
3263            }
3264            if (DEBUG_PACKAGE_INFO)
3265                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3266            if (p != null) {
3267                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3268            }
3269            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3270                final PackageSetting ps = mSettings.mPackages.get(packageName);
3271                return generatePackageInfo(ps, flags, userId);
3272            }
3273        }
3274        return null;
3275    }
3276
3277    @Override
3278    public String[] currentToCanonicalPackageNames(String[] names) {
3279        String[] out = new String[names.length];
3280        // reader
3281        synchronized (mPackages) {
3282            for (int i=names.length-1; i>=0; i--) {
3283                PackageSetting ps = mSettings.mPackages.get(names[i]);
3284                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3285            }
3286        }
3287        return out;
3288    }
3289
3290    @Override
3291    public String[] canonicalToCurrentPackageNames(String[] names) {
3292        String[] out = new String[names.length];
3293        // reader
3294        synchronized (mPackages) {
3295            for (int i=names.length-1; i>=0; i--) {
3296                String cur = mSettings.getRenamedPackageLPr(names[i]);
3297                out[i] = cur != null ? cur : names[i];
3298            }
3299        }
3300        return out;
3301    }
3302
3303    @Override
3304    public int getPackageUid(String packageName, int flags, int userId) {
3305        if (!sUserManager.exists(userId)) return -1;
3306        flags = updateFlagsForPackage(flags, userId, packageName);
3307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3308                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3309
3310        // reader
3311        synchronized (mPackages) {
3312            final PackageParser.Package p = mPackages.get(packageName);
3313            if (p != null && p.isMatch(flags)) {
3314                return UserHandle.getUid(userId, p.applicationInfo.uid);
3315            }
3316            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3317                final PackageSetting ps = mSettings.mPackages.get(packageName);
3318                if (ps != null && ps.isMatch(flags)) {
3319                    return UserHandle.getUid(userId, ps.appId);
3320                }
3321            }
3322        }
3323
3324        return -1;
3325    }
3326
3327    @Override
3328    public int[] getPackageGids(String packageName, int flags, int userId) {
3329        if (!sUserManager.exists(userId)) return null;
3330        flags = updateFlagsForPackage(flags, userId, packageName);
3331        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3332                false /* requireFullPermission */, false /* checkShell */,
3333                "getPackageGids");
3334
3335        // reader
3336        synchronized (mPackages) {
3337            final PackageParser.Package p = mPackages.get(packageName);
3338            if (p != null && p.isMatch(flags)) {
3339                PackageSetting ps = (PackageSetting) p.mExtras;
3340                // TODO: Shouldn't this be checking for package installed state for userId and
3341                // return null?
3342                return ps.getPermissionsState().computeGids(userId);
3343            }
3344            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3345                final PackageSetting ps = mSettings.mPackages.get(packageName);
3346                if (ps != null && ps.isMatch(flags)) {
3347                    return ps.getPermissionsState().computeGids(userId);
3348                }
3349            }
3350        }
3351
3352        return null;
3353    }
3354
3355    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3356        if (bp.perm != null) {
3357            return PackageParser.generatePermissionInfo(bp.perm, flags);
3358        }
3359        PermissionInfo pi = new PermissionInfo();
3360        pi.name = bp.name;
3361        pi.packageName = bp.sourcePackage;
3362        pi.nonLocalizedLabel = bp.name;
3363        pi.protectionLevel = bp.protectionLevel;
3364        return pi;
3365    }
3366
3367    @Override
3368    public PermissionInfo getPermissionInfo(String name, int flags) {
3369        // reader
3370        synchronized (mPackages) {
3371            final BasePermission p = mSettings.mPermissions.get(name);
3372            if (p != null) {
3373                return generatePermissionInfo(p, flags);
3374            }
3375            return null;
3376        }
3377    }
3378
3379    @Override
3380    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3381            int flags) {
3382        // reader
3383        synchronized (mPackages) {
3384            if (group != null && !mPermissionGroups.containsKey(group)) {
3385                // This is thrown as NameNotFoundException
3386                return null;
3387            }
3388
3389            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3390            for (BasePermission p : mSettings.mPermissions.values()) {
3391                if (group == null) {
3392                    if (p.perm == null || p.perm.info.group == null) {
3393                        out.add(generatePermissionInfo(p, flags));
3394                    }
3395                } else {
3396                    if (p.perm != null && group.equals(p.perm.info.group)) {
3397                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3398                    }
3399                }
3400            }
3401            return new ParceledListSlice<>(out);
3402        }
3403    }
3404
3405    @Override
3406    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3407        // reader
3408        synchronized (mPackages) {
3409            return PackageParser.generatePermissionGroupInfo(
3410                    mPermissionGroups.get(name), flags);
3411        }
3412    }
3413
3414    @Override
3415    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3416        // reader
3417        synchronized (mPackages) {
3418            final int N = mPermissionGroups.size();
3419            ArrayList<PermissionGroupInfo> out
3420                    = new ArrayList<PermissionGroupInfo>(N);
3421            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3422                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3423            }
3424            return new ParceledListSlice<>(out);
3425        }
3426    }
3427
3428    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3429            int userId) {
3430        if (!sUserManager.exists(userId)) return null;
3431        PackageSetting ps = mSettings.mPackages.get(packageName);
3432        if (ps != null) {
3433            if (ps.pkg == null) {
3434                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3435                if (pInfo != null) {
3436                    return pInfo.applicationInfo;
3437                }
3438                return null;
3439            }
3440            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3441                    ps.readUserState(userId), userId);
3442        }
3443        return null;
3444    }
3445
3446    @Override
3447    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3448        if (!sUserManager.exists(userId)) return null;
3449        flags = updateFlagsForApplication(flags, userId, packageName);
3450        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3451                false /* requireFullPermission */, false /* checkShell */, "get application info");
3452
3453        // writer
3454        synchronized (mPackages) {
3455            // Normalize package name to hanlde renamed packages
3456            packageName = normalizePackageNameLPr(packageName);
3457
3458            PackageParser.Package p = mPackages.get(packageName);
3459            if (DEBUG_PACKAGE_INFO) Log.v(
3460                    TAG, "getApplicationInfo " + packageName
3461                    + ": " + p);
3462            if (p != null) {
3463                PackageSetting ps = mSettings.mPackages.get(packageName);
3464                if (ps == null) return null;
3465                // Note: isEnabledLP() does not apply here - always return info
3466                return PackageParser.generateApplicationInfo(
3467                        p, flags, ps.readUserState(userId), userId);
3468            }
3469            if ("android".equals(packageName)||"system".equals(packageName)) {
3470                return mAndroidApplication;
3471            }
3472            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3473                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3474            }
3475        }
3476        return null;
3477    }
3478
3479    private String normalizePackageNameLPr(String packageName) {
3480        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3481        return normalizedPackageName != null ? normalizedPackageName : packageName;
3482    }
3483
3484    @Override
3485    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3486            final IPackageDataObserver observer) {
3487        mContext.enforceCallingOrSelfPermission(
3488                android.Manifest.permission.CLEAR_APP_CACHE, null);
3489        // Queue up an async operation since clearing cache may take a little while.
3490        mHandler.post(new Runnable() {
3491            public void run() {
3492                mHandler.removeCallbacks(this);
3493                boolean success = true;
3494                synchronized (mInstallLock) {
3495                    try {
3496                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3497                    } catch (InstallerException e) {
3498                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3499                        success = false;
3500                    }
3501                }
3502                if (observer != null) {
3503                    try {
3504                        observer.onRemoveCompleted(null, success);
3505                    } catch (RemoteException e) {
3506                        Slog.w(TAG, "RemoveException when invoking call back");
3507                    }
3508                }
3509            }
3510        });
3511    }
3512
3513    @Override
3514    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3515            final IntentSender pi) {
3516        mContext.enforceCallingOrSelfPermission(
3517                android.Manifest.permission.CLEAR_APP_CACHE, null);
3518        // Queue up an async operation since clearing cache may take a little while.
3519        mHandler.post(new Runnable() {
3520            public void run() {
3521                mHandler.removeCallbacks(this);
3522                boolean success = true;
3523                synchronized (mInstallLock) {
3524                    try {
3525                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3526                    } catch (InstallerException e) {
3527                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3528                        success = false;
3529                    }
3530                }
3531                if(pi != null) {
3532                    try {
3533                        // Callback via pending intent
3534                        int code = success ? 1 : 0;
3535                        pi.sendIntent(null, code, null,
3536                                null, null);
3537                    } catch (SendIntentException e1) {
3538                        Slog.i(TAG, "Failed to send pending intent");
3539                    }
3540                }
3541            }
3542        });
3543    }
3544
3545    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3546        synchronized (mInstallLock) {
3547            try {
3548                mInstaller.freeCache(volumeUuid, freeStorageSize);
3549            } catch (InstallerException e) {
3550                throw new IOException("Failed to free enough space", e);
3551            }
3552        }
3553    }
3554
3555    /**
3556     * Update given flags based on encryption status of current user.
3557     */
3558    private int updateFlags(int flags, int userId) {
3559        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3560                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3561            // Caller expressed an explicit opinion about what encryption
3562            // aware/unaware components they want to see, so fall through and
3563            // give them what they want
3564        } else {
3565            // Caller expressed no opinion, so match based on user state
3566            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3567                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3568            } else {
3569                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3570            }
3571        }
3572        return flags;
3573    }
3574
3575    private UserManagerInternal getUserManagerInternal() {
3576        if (mUserManagerInternal == null) {
3577            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3578        }
3579        return mUserManagerInternal;
3580    }
3581
3582    /**
3583     * Update given flags when being used to request {@link PackageInfo}.
3584     */
3585    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3586        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3587        boolean triaged = true;
3588        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3589                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3590            // Caller is asking for component details, so they'd better be
3591            // asking for specific encryption matching behavior, or be triaged
3592            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3593                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3594                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3595                triaged = false;
3596            }
3597        }
3598        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3599                | PackageManager.MATCH_SYSTEM_ONLY
3600                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3601            triaged = false;
3602        }
3603        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3604            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3605                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3606                    + Debug.getCallers(5));
3607        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3608                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3609            // If the caller wants all packages and has a restricted profile associated with it,
3610            // then match all users. This is to make sure that launchers that need to access work
3611            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3612            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3613            flags |= PackageManager.MATCH_ANY_USER;
3614        }
3615        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3616            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3617                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3618        }
3619        return updateFlags(flags, userId);
3620    }
3621
3622    /**
3623     * Update given flags when being used to request {@link ApplicationInfo}.
3624     */
3625    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3626        return updateFlagsForPackage(flags, userId, cookie);
3627    }
3628
3629    /**
3630     * Update given flags when being used to request {@link ComponentInfo}.
3631     */
3632    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3633        if (cookie instanceof Intent) {
3634            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3635                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3636            }
3637        }
3638
3639        boolean triaged = true;
3640        // Caller is asking for component details, so they'd better be
3641        // asking for specific encryption matching behavior, or be triaged
3642        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3643                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3644                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3645            triaged = false;
3646        }
3647        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3648            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3649                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3650        }
3651
3652        return updateFlags(flags, userId);
3653    }
3654
3655    /**
3656     * Update given flags when being used to request {@link ResolveInfo}.
3657     */
3658    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3659        // Safe mode means we shouldn't match any third-party components
3660        if (mSafeMode) {
3661            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3662        }
3663        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
3664        if (ephemeralPkgName != null) {
3665            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3666            flags |= PackageManager.MATCH_EPHEMERAL;
3667        }
3668
3669        return updateFlagsForComponent(flags, userId, cookie);
3670    }
3671
3672    @Override
3673    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3674        if (!sUserManager.exists(userId)) return null;
3675        flags = updateFlagsForComponent(flags, userId, component);
3676        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3677                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3678        synchronized (mPackages) {
3679            PackageParser.Activity a = mActivities.mActivities.get(component);
3680
3681            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3682            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3683                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3684                if (ps == null) return null;
3685                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3686                        userId);
3687            }
3688            if (mResolveComponentName.equals(component)) {
3689                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3690                        new PackageUserState(), userId);
3691            }
3692        }
3693        return null;
3694    }
3695
3696    @Override
3697    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3698            String resolvedType) {
3699        synchronized (mPackages) {
3700            if (component.equals(mResolveComponentName)) {
3701                // The resolver supports EVERYTHING!
3702                return true;
3703            }
3704            PackageParser.Activity a = mActivities.mActivities.get(component);
3705            if (a == null) {
3706                return false;
3707            }
3708            for (int i=0; i<a.intents.size(); i++) {
3709                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3710                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3711                    return true;
3712                }
3713            }
3714            return false;
3715        }
3716    }
3717
3718    @Override
3719    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3720        if (!sUserManager.exists(userId)) return null;
3721        flags = updateFlagsForComponent(flags, userId, component);
3722        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3723                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3724        synchronized (mPackages) {
3725            PackageParser.Activity a = mReceivers.mActivities.get(component);
3726            if (DEBUG_PACKAGE_INFO) Log.v(
3727                TAG, "getReceiverInfo " + component + ": " + a);
3728            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3729                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3730                if (ps == null) return null;
3731                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3732                        userId);
3733            }
3734        }
3735        return null;
3736    }
3737
3738    @Override
3739    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3740        if (!sUserManager.exists(userId)) return null;
3741        flags = updateFlagsForComponent(flags, userId, component);
3742        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3743                false /* requireFullPermission */, false /* checkShell */, "get service info");
3744        synchronized (mPackages) {
3745            PackageParser.Service s = mServices.mServices.get(component);
3746            if (DEBUG_PACKAGE_INFO) Log.v(
3747                TAG, "getServiceInfo " + component + ": " + s);
3748            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3749                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3750                if (ps == null) return null;
3751                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3752                        userId);
3753            }
3754        }
3755        return null;
3756    }
3757
3758    @Override
3759    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3760        if (!sUserManager.exists(userId)) return null;
3761        flags = updateFlagsForComponent(flags, userId, component);
3762        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3763                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3764        synchronized (mPackages) {
3765            PackageParser.Provider p = mProviders.mProviders.get(component);
3766            if (DEBUG_PACKAGE_INFO) Log.v(
3767                TAG, "getProviderInfo " + component + ": " + p);
3768            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3769                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3770                if (ps == null) return null;
3771                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3772                        userId);
3773            }
3774        }
3775        return null;
3776    }
3777
3778    @Override
3779    public String[] getSystemSharedLibraryNames() {
3780        Set<String> libSet;
3781        synchronized (mPackages) {
3782            libSet = mSharedLibraries.keySet();
3783            int size = libSet.size();
3784            if (size > 0) {
3785                String[] libs = new String[size];
3786                libSet.toArray(libs);
3787                return libs;
3788            }
3789        }
3790        return null;
3791    }
3792
3793    @Override
3794    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3795        synchronized (mPackages) {
3796            return mServicesSystemSharedLibraryPackageName;
3797        }
3798    }
3799
3800    @Override
3801    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3802        synchronized (mPackages) {
3803            return mSharedSystemSharedLibraryPackageName;
3804        }
3805    }
3806
3807    @Override
3808    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3809        synchronized (mPackages) {
3810            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3811
3812            final FeatureInfo fi = new FeatureInfo();
3813            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3814                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3815            res.add(fi);
3816
3817            return new ParceledListSlice<>(res);
3818        }
3819    }
3820
3821    @Override
3822    public boolean hasSystemFeature(String name, int version) {
3823        synchronized (mPackages) {
3824            final FeatureInfo feat = mAvailableFeatures.get(name);
3825            if (feat == null) {
3826                return false;
3827            } else {
3828                return feat.version >= version;
3829            }
3830        }
3831    }
3832
3833    @Override
3834    public int checkPermission(String permName, String pkgName, int userId) {
3835        if (!sUserManager.exists(userId)) {
3836            return PackageManager.PERMISSION_DENIED;
3837        }
3838
3839        synchronized (mPackages) {
3840            final PackageParser.Package p = mPackages.get(pkgName);
3841            if (p != null && p.mExtras != null) {
3842                final PackageSetting ps = (PackageSetting) p.mExtras;
3843                final PermissionsState permissionsState = ps.getPermissionsState();
3844                if (permissionsState.hasPermission(permName, userId)) {
3845                    return PackageManager.PERMISSION_GRANTED;
3846                }
3847                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3848                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3849                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3850                    return PackageManager.PERMISSION_GRANTED;
3851                }
3852            }
3853        }
3854
3855        return PackageManager.PERMISSION_DENIED;
3856    }
3857
3858    @Override
3859    public int checkUidPermission(String permName, int uid) {
3860        final int userId = UserHandle.getUserId(uid);
3861
3862        if (!sUserManager.exists(userId)) {
3863            return PackageManager.PERMISSION_DENIED;
3864        }
3865
3866        synchronized (mPackages) {
3867            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3868            if (obj != null) {
3869                final SettingBase ps = (SettingBase) obj;
3870                final PermissionsState permissionsState = ps.getPermissionsState();
3871                if (permissionsState.hasPermission(permName, userId)) {
3872                    return PackageManager.PERMISSION_GRANTED;
3873                }
3874                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3875                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3876                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3877                    return PackageManager.PERMISSION_GRANTED;
3878                }
3879            } else {
3880                ArraySet<String> perms = mSystemPermissions.get(uid);
3881                if (perms != null) {
3882                    if (perms.contains(permName)) {
3883                        return PackageManager.PERMISSION_GRANTED;
3884                    }
3885                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3886                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3887                        return PackageManager.PERMISSION_GRANTED;
3888                    }
3889                }
3890            }
3891        }
3892
3893        return PackageManager.PERMISSION_DENIED;
3894    }
3895
3896    @Override
3897    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3898        if (UserHandle.getCallingUserId() != userId) {
3899            mContext.enforceCallingPermission(
3900                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3901                    "isPermissionRevokedByPolicy for user " + userId);
3902        }
3903
3904        if (checkPermission(permission, packageName, userId)
3905                == PackageManager.PERMISSION_GRANTED) {
3906            return false;
3907        }
3908
3909        final long identity = Binder.clearCallingIdentity();
3910        try {
3911            final int flags = getPermissionFlags(permission, packageName, userId);
3912            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3913        } finally {
3914            Binder.restoreCallingIdentity(identity);
3915        }
3916    }
3917
3918    @Override
3919    public String getPermissionControllerPackageName() {
3920        synchronized (mPackages) {
3921            return mRequiredInstallerPackage;
3922        }
3923    }
3924
3925    /**
3926     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3927     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3928     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3929     * @param message the message to log on security exception
3930     */
3931    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3932            boolean checkShell, String message) {
3933        if (userId < 0) {
3934            throw new IllegalArgumentException("Invalid userId " + userId);
3935        }
3936        if (checkShell) {
3937            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3938        }
3939        if (userId == UserHandle.getUserId(callingUid)) return;
3940        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3941            if (requireFullPermission) {
3942                mContext.enforceCallingOrSelfPermission(
3943                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3944            } else {
3945                try {
3946                    mContext.enforceCallingOrSelfPermission(
3947                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3948                } catch (SecurityException se) {
3949                    mContext.enforceCallingOrSelfPermission(
3950                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3951                }
3952            }
3953        }
3954    }
3955
3956    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3957        if (callingUid == Process.SHELL_UID) {
3958            if (userHandle >= 0
3959                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3960                throw new SecurityException("Shell does not have permission to access user "
3961                        + userHandle);
3962            } else if (userHandle < 0) {
3963                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3964                        + Debug.getCallers(3));
3965            }
3966        }
3967    }
3968
3969    private BasePermission findPermissionTreeLP(String permName) {
3970        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3971            if (permName.startsWith(bp.name) &&
3972                    permName.length() > bp.name.length() &&
3973                    permName.charAt(bp.name.length()) == '.') {
3974                return bp;
3975            }
3976        }
3977        return null;
3978    }
3979
3980    private BasePermission checkPermissionTreeLP(String permName) {
3981        if (permName != null) {
3982            BasePermission bp = findPermissionTreeLP(permName);
3983            if (bp != null) {
3984                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3985                    return bp;
3986                }
3987                throw new SecurityException("Calling uid "
3988                        + Binder.getCallingUid()
3989                        + " is not allowed to add to permission tree "
3990                        + bp.name + " owned by uid " + bp.uid);
3991            }
3992        }
3993        throw new SecurityException("No permission tree found for " + permName);
3994    }
3995
3996    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3997        if (s1 == null) {
3998            return s2 == null;
3999        }
4000        if (s2 == null) {
4001            return false;
4002        }
4003        if (s1.getClass() != s2.getClass()) {
4004            return false;
4005        }
4006        return s1.equals(s2);
4007    }
4008
4009    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4010        if (pi1.icon != pi2.icon) return false;
4011        if (pi1.logo != pi2.logo) return false;
4012        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4013        if (!compareStrings(pi1.name, pi2.name)) return false;
4014        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4015        // We'll take care of setting this one.
4016        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4017        // These are not currently stored in settings.
4018        //if (!compareStrings(pi1.group, pi2.group)) return false;
4019        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4020        //if (pi1.labelRes != pi2.labelRes) return false;
4021        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4022        return true;
4023    }
4024
4025    int permissionInfoFootprint(PermissionInfo info) {
4026        int size = info.name.length();
4027        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4028        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4029        return size;
4030    }
4031
4032    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4033        int size = 0;
4034        for (BasePermission perm : mSettings.mPermissions.values()) {
4035            if (perm.uid == tree.uid) {
4036                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4037            }
4038        }
4039        return size;
4040    }
4041
4042    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4043        // We calculate the max size of permissions defined by this uid and throw
4044        // if that plus the size of 'info' would exceed our stated maximum.
4045        if (tree.uid != Process.SYSTEM_UID) {
4046            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4047            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4048                throw new SecurityException("Permission tree size cap exceeded");
4049            }
4050        }
4051    }
4052
4053    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4054        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4055            throw new SecurityException("Label must be specified in permission");
4056        }
4057        BasePermission tree = checkPermissionTreeLP(info.name);
4058        BasePermission bp = mSettings.mPermissions.get(info.name);
4059        boolean added = bp == null;
4060        boolean changed = true;
4061        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4062        if (added) {
4063            enforcePermissionCapLocked(info, tree);
4064            bp = new BasePermission(info.name, tree.sourcePackage,
4065                    BasePermission.TYPE_DYNAMIC);
4066        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4067            throw new SecurityException(
4068                    "Not allowed to modify non-dynamic permission "
4069                    + info.name);
4070        } else {
4071            if (bp.protectionLevel == fixedLevel
4072                    && bp.perm.owner.equals(tree.perm.owner)
4073                    && bp.uid == tree.uid
4074                    && comparePermissionInfos(bp.perm.info, info)) {
4075                changed = false;
4076            }
4077        }
4078        bp.protectionLevel = fixedLevel;
4079        info = new PermissionInfo(info);
4080        info.protectionLevel = fixedLevel;
4081        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4082        bp.perm.info.packageName = tree.perm.info.packageName;
4083        bp.uid = tree.uid;
4084        if (added) {
4085            mSettings.mPermissions.put(info.name, bp);
4086        }
4087        if (changed) {
4088            if (!async) {
4089                mSettings.writeLPr();
4090            } else {
4091                scheduleWriteSettingsLocked();
4092            }
4093        }
4094        return added;
4095    }
4096
4097    @Override
4098    public boolean addPermission(PermissionInfo info) {
4099        synchronized (mPackages) {
4100            return addPermissionLocked(info, false);
4101        }
4102    }
4103
4104    @Override
4105    public boolean addPermissionAsync(PermissionInfo info) {
4106        synchronized (mPackages) {
4107            return addPermissionLocked(info, true);
4108        }
4109    }
4110
4111    @Override
4112    public void removePermission(String name) {
4113        synchronized (mPackages) {
4114            checkPermissionTreeLP(name);
4115            BasePermission bp = mSettings.mPermissions.get(name);
4116            if (bp != null) {
4117                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4118                    throw new SecurityException(
4119                            "Not allowed to modify non-dynamic permission "
4120                            + name);
4121                }
4122                mSettings.mPermissions.remove(name);
4123                mSettings.writeLPr();
4124            }
4125        }
4126    }
4127
4128    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4129            BasePermission bp) {
4130        int index = pkg.requestedPermissions.indexOf(bp.name);
4131        if (index == -1) {
4132            throw new SecurityException("Package " + pkg.packageName
4133                    + " has not requested permission " + bp.name);
4134        }
4135        if (!bp.isRuntime() && !bp.isDevelopment()) {
4136            throw new SecurityException("Permission " + bp.name
4137                    + " is not a changeable permission type");
4138        }
4139    }
4140
4141    @Override
4142    public void grantRuntimePermission(String packageName, String name, final int userId) {
4143        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4144    }
4145
4146    private void grantRuntimePermission(String packageName, String name, final int userId,
4147            boolean overridePolicy) {
4148        if (!sUserManager.exists(userId)) {
4149            Log.e(TAG, "No such user:" + userId);
4150            return;
4151        }
4152
4153        mContext.enforceCallingOrSelfPermission(
4154                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4155                "grantRuntimePermission");
4156
4157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4158                true /* requireFullPermission */, true /* checkShell */,
4159                "grantRuntimePermission");
4160
4161        final int uid;
4162        final SettingBase sb;
4163
4164        synchronized (mPackages) {
4165            final PackageParser.Package pkg = mPackages.get(packageName);
4166            if (pkg == null) {
4167                throw new IllegalArgumentException("Unknown package: " + packageName);
4168            }
4169
4170            final BasePermission bp = mSettings.mPermissions.get(name);
4171            if (bp == null) {
4172                throw new IllegalArgumentException("Unknown permission: " + name);
4173            }
4174
4175            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4176
4177            // If a permission review is required for legacy apps we represent
4178            // their permissions as always granted runtime ones since we need
4179            // to keep the review required permission flag per user while an
4180            // install permission's state is shared across all users.
4181            if (mPermissionReviewRequired
4182                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4183                    && bp.isRuntime()) {
4184                return;
4185            }
4186
4187            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4188            sb = (SettingBase) pkg.mExtras;
4189            if (sb == null) {
4190                throw new IllegalArgumentException("Unknown package: " + packageName);
4191            }
4192
4193            final PermissionsState permissionsState = sb.getPermissionsState();
4194
4195            final int flags = permissionsState.getPermissionFlags(name, userId);
4196            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4197                throw new SecurityException("Cannot grant system fixed permission "
4198                        + name + " for package " + packageName);
4199            }
4200            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4201                throw new SecurityException("Cannot grant policy fixed permission "
4202                        + name + " for package " + packageName);
4203            }
4204
4205            if (bp.isDevelopment()) {
4206                // Development permissions must be handled specially, since they are not
4207                // normal runtime permissions.  For now they apply to all users.
4208                if (permissionsState.grantInstallPermission(bp) !=
4209                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4210                    scheduleWriteSettingsLocked();
4211                }
4212                return;
4213            }
4214
4215            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4216                throw new SecurityException("Cannot grant non-ephemeral permission"
4217                        + name + " for package " + packageName);
4218            }
4219
4220            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4221                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4222                return;
4223            }
4224
4225            final int result = permissionsState.grantRuntimePermission(bp, userId);
4226            switch (result) {
4227                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4228                    return;
4229                }
4230
4231                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4232                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4233                    mHandler.post(new Runnable() {
4234                        @Override
4235                        public void run() {
4236                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4237                        }
4238                    });
4239                }
4240                break;
4241            }
4242
4243            if (bp.isRuntime()) {
4244                logPermissionGranted(mContext, name, packageName);
4245            }
4246
4247            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4248
4249            // Not critical if that is lost - app has to request again.
4250            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4251        }
4252
4253        // Only need to do this if user is initialized. Otherwise it's a new user
4254        // and there are no processes running as the user yet and there's no need
4255        // to make an expensive call to remount processes for the changed permissions.
4256        if (READ_EXTERNAL_STORAGE.equals(name)
4257                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4258            final long token = Binder.clearCallingIdentity();
4259            try {
4260                if (sUserManager.isInitialized(userId)) {
4261                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4262                            StorageManagerInternal.class);
4263                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4264                }
4265            } finally {
4266                Binder.restoreCallingIdentity(token);
4267            }
4268        }
4269    }
4270
4271    @Override
4272    public void revokeRuntimePermission(String packageName, String name, int userId) {
4273        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4274    }
4275
4276    private void revokeRuntimePermission(String packageName, String name, int userId,
4277            boolean overridePolicy) {
4278        if (!sUserManager.exists(userId)) {
4279            Log.e(TAG, "No such user:" + userId);
4280            return;
4281        }
4282
4283        mContext.enforceCallingOrSelfPermission(
4284                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4285                "revokeRuntimePermission");
4286
4287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4288                true /* requireFullPermission */, true /* checkShell */,
4289                "revokeRuntimePermission");
4290
4291        final int appId;
4292
4293        synchronized (mPackages) {
4294            final PackageParser.Package pkg = mPackages.get(packageName);
4295            if (pkg == null) {
4296                throw new IllegalArgumentException("Unknown package: " + packageName);
4297            }
4298
4299            final BasePermission bp = mSettings.mPermissions.get(name);
4300            if (bp == null) {
4301                throw new IllegalArgumentException("Unknown permission: " + name);
4302            }
4303
4304            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4305
4306            // If a permission review is required for legacy apps we represent
4307            // their permissions as always granted runtime ones since we need
4308            // to keep the review required permission flag per user while an
4309            // install permission's state is shared across all users.
4310            if (mPermissionReviewRequired
4311                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4312                    && bp.isRuntime()) {
4313                return;
4314            }
4315
4316            SettingBase sb = (SettingBase) pkg.mExtras;
4317            if (sb == null) {
4318                throw new IllegalArgumentException("Unknown package: " + packageName);
4319            }
4320
4321            final PermissionsState permissionsState = sb.getPermissionsState();
4322
4323            final int flags = permissionsState.getPermissionFlags(name, userId);
4324            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4325                throw new SecurityException("Cannot revoke system fixed permission "
4326                        + name + " for package " + packageName);
4327            }
4328            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4329                throw new SecurityException("Cannot revoke policy fixed permission "
4330                        + name + " for package " + packageName);
4331            }
4332
4333            if (bp.isDevelopment()) {
4334                // Development permissions must be handled specially, since they are not
4335                // normal runtime permissions.  For now they apply to all users.
4336                if (permissionsState.revokeInstallPermission(bp) !=
4337                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4338                    scheduleWriteSettingsLocked();
4339                }
4340                return;
4341            }
4342
4343            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4344                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4345                return;
4346            }
4347
4348            if (bp.isRuntime()) {
4349                logPermissionRevoked(mContext, name, packageName);
4350            }
4351
4352            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4353
4354            // Critical, after this call app should never have the permission.
4355            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4356
4357            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4358        }
4359
4360        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4361    }
4362
4363    /**
4364     * Get the first event id for the permission.
4365     *
4366     * <p>There are four events for each permission: <ul>
4367     *     <li>Request permission: first id + 0</li>
4368     *     <li>Grant permission: first id + 1</li>
4369     *     <li>Request for permission denied: first id + 2</li>
4370     *     <li>Revoke permission: first id + 3</li>
4371     * </ul></p>
4372     *
4373     * @param name name of the permission
4374     *
4375     * @return The first event id for the permission
4376     */
4377    private static int getBaseEventId(@NonNull String name) {
4378        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4379
4380        if (eventIdIndex == -1) {
4381            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4382                    || "user".equals(Build.TYPE)) {
4383                Log.i(TAG, "Unknown permission " + name);
4384
4385                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4386            } else {
4387                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4388                //
4389                // Also update
4390                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4391                // - metrics_constants.proto
4392                throw new IllegalStateException("Unknown permission " + name);
4393            }
4394        }
4395
4396        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4397    }
4398
4399    /**
4400     * Log that a permission was revoked.
4401     *
4402     * @param context Context of the caller
4403     * @param name name of the permission
4404     * @param packageName package permission if for
4405     */
4406    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4407            @NonNull String packageName) {
4408        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4409    }
4410
4411    /**
4412     * Log that a permission request was granted.
4413     *
4414     * @param context Context of the caller
4415     * @param name name of the permission
4416     * @param packageName package permission if for
4417     */
4418    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4419            @NonNull String packageName) {
4420        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4421    }
4422
4423    @Override
4424    public void resetRuntimePermissions() {
4425        mContext.enforceCallingOrSelfPermission(
4426                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4427                "revokeRuntimePermission");
4428
4429        int callingUid = Binder.getCallingUid();
4430        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4431            mContext.enforceCallingOrSelfPermission(
4432                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4433                    "resetRuntimePermissions");
4434        }
4435
4436        synchronized (mPackages) {
4437            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4438            for (int userId : UserManagerService.getInstance().getUserIds()) {
4439                final int packageCount = mPackages.size();
4440                for (int i = 0; i < packageCount; i++) {
4441                    PackageParser.Package pkg = mPackages.valueAt(i);
4442                    if (!(pkg.mExtras instanceof PackageSetting)) {
4443                        continue;
4444                    }
4445                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4446                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4447                }
4448            }
4449        }
4450    }
4451
4452    @Override
4453    public int getPermissionFlags(String name, String packageName, int userId) {
4454        if (!sUserManager.exists(userId)) {
4455            return 0;
4456        }
4457
4458        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4459
4460        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4461                true /* requireFullPermission */, false /* checkShell */,
4462                "getPermissionFlags");
4463
4464        synchronized (mPackages) {
4465            final PackageParser.Package pkg = mPackages.get(packageName);
4466            if (pkg == null) {
4467                return 0;
4468            }
4469
4470            final BasePermission bp = mSettings.mPermissions.get(name);
4471            if (bp == null) {
4472                return 0;
4473            }
4474
4475            SettingBase sb = (SettingBase) pkg.mExtras;
4476            if (sb == null) {
4477                return 0;
4478            }
4479
4480            PermissionsState permissionsState = sb.getPermissionsState();
4481            return permissionsState.getPermissionFlags(name, userId);
4482        }
4483    }
4484
4485    @Override
4486    public void updatePermissionFlags(String name, String packageName, int flagMask,
4487            int flagValues, int userId) {
4488        if (!sUserManager.exists(userId)) {
4489            return;
4490        }
4491
4492        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4493
4494        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4495                true /* requireFullPermission */, true /* checkShell */,
4496                "updatePermissionFlags");
4497
4498        // Only the system can change these flags and nothing else.
4499        if (getCallingUid() != Process.SYSTEM_UID) {
4500            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4501            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4502            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4503            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4504            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4505        }
4506
4507        synchronized (mPackages) {
4508            final PackageParser.Package pkg = mPackages.get(packageName);
4509            if (pkg == null) {
4510                throw new IllegalArgumentException("Unknown package: " + packageName);
4511            }
4512
4513            final BasePermission bp = mSettings.mPermissions.get(name);
4514            if (bp == null) {
4515                throw new IllegalArgumentException("Unknown permission: " + name);
4516            }
4517
4518            SettingBase sb = (SettingBase) pkg.mExtras;
4519            if (sb == null) {
4520                throw new IllegalArgumentException("Unknown package: " + packageName);
4521            }
4522
4523            PermissionsState permissionsState = sb.getPermissionsState();
4524
4525            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4526
4527            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4528                // Install and runtime permissions are stored in different places,
4529                // so figure out what permission changed and persist the change.
4530                if (permissionsState.getInstallPermissionState(name) != null) {
4531                    scheduleWriteSettingsLocked();
4532                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4533                        || hadState) {
4534                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4535                }
4536            }
4537        }
4538    }
4539
4540    /**
4541     * Update the permission flags for all packages and runtime permissions of a user in order
4542     * to allow device or profile owner to remove POLICY_FIXED.
4543     */
4544    @Override
4545    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4546        if (!sUserManager.exists(userId)) {
4547            return;
4548        }
4549
4550        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4551
4552        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4553                true /* requireFullPermission */, true /* checkShell */,
4554                "updatePermissionFlagsForAllApps");
4555
4556        // Only the system can change system fixed flags.
4557        if (getCallingUid() != Process.SYSTEM_UID) {
4558            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4559            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4560        }
4561
4562        synchronized (mPackages) {
4563            boolean changed = false;
4564            final int packageCount = mPackages.size();
4565            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4566                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4567                SettingBase sb = (SettingBase) pkg.mExtras;
4568                if (sb == null) {
4569                    continue;
4570                }
4571                PermissionsState permissionsState = sb.getPermissionsState();
4572                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4573                        userId, flagMask, flagValues);
4574            }
4575            if (changed) {
4576                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4577            }
4578        }
4579    }
4580
4581    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4582        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4583                != PackageManager.PERMISSION_GRANTED
4584            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4585                != PackageManager.PERMISSION_GRANTED) {
4586            throw new SecurityException(message + " requires "
4587                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4588                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4589        }
4590    }
4591
4592    @Override
4593    public boolean shouldShowRequestPermissionRationale(String permissionName,
4594            String packageName, int userId) {
4595        if (UserHandle.getCallingUserId() != userId) {
4596            mContext.enforceCallingPermission(
4597                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4598                    "canShowRequestPermissionRationale for user " + userId);
4599        }
4600
4601        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4602        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4603            return false;
4604        }
4605
4606        if (checkPermission(permissionName, packageName, userId)
4607                == PackageManager.PERMISSION_GRANTED) {
4608            return false;
4609        }
4610
4611        final int flags;
4612
4613        final long identity = Binder.clearCallingIdentity();
4614        try {
4615            flags = getPermissionFlags(permissionName,
4616                    packageName, userId);
4617        } finally {
4618            Binder.restoreCallingIdentity(identity);
4619        }
4620
4621        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4622                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4623                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4624
4625        if ((flags & fixedFlags) != 0) {
4626            return false;
4627        }
4628
4629        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4630    }
4631
4632    @Override
4633    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4634        mContext.enforceCallingOrSelfPermission(
4635                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4636                "addOnPermissionsChangeListener");
4637
4638        synchronized (mPackages) {
4639            mOnPermissionChangeListeners.addListenerLocked(listener);
4640        }
4641    }
4642
4643    @Override
4644    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4645        synchronized (mPackages) {
4646            mOnPermissionChangeListeners.removeListenerLocked(listener);
4647        }
4648    }
4649
4650    @Override
4651    public boolean isProtectedBroadcast(String actionName) {
4652        synchronized (mPackages) {
4653            if (mProtectedBroadcasts.contains(actionName)) {
4654                return true;
4655            } else if (actionName != null) {
4656                // TODO: remove these terrible hacks
4657                if (actionName.startsWith("android.net.netmon.lingerExpired")
4658                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4659                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4660                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4661                    return true;
4662                }
4663            }
4664        }
4665        return false;
4666    }
4667
4668    @Override
4669    public int checkSignatures(String pkg1, String pkg2) {
4670        synchronized (mPackages) {
4671            final PackageParser.Package p1 = mPackages.get(pkg1);
4672            final PackageParser.Package p2 = mPackages.get(pkg2);
4673            if (p1 == null || p1.mExtras == null
4674                    || p2 == null || p2.mExtras == null) {
4675                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4676            }
4677            return compareSignatures(p1.mSignatures, p2.mSignatures);
4678        }
4679    }
4680
4681    @Override
4682    public int checkUidSignatures(int uid1, int uid2) {
4683        // Map to base uids.
4684        uid1 = UserHandle.getAppId(uid1);
4685        uid2 = UserHandle.getAppId(uid2);
4686        // reader
4687        synchronized (mPackages) {
4688            Signature[] s1;
4689            Signature[] s2;
4690            Object obj = mSettings.getUserIdLPr(uid1);
4691            if (obj != null) {
4692                if (obj instanceof SharedUserSetting) {
4693                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4694                } else if (obj instanceof PackageSetting) {
4695                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4696                } else {
4697                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4698                }
4699            } else {
4700                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4701            }
4702            obj = mSettings.getUserIdLPr(uid2);
4703            if (obj != null) {
4704                if (obj instanceof SharedUserSetting) {
4705                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4706                } else if (obj instanceof PackageSetting) {
4707                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4708                } else {
4709                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4710                }
4711            } else {
4712                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4713            }
4714            return compareSignatures(s1, s2);
4715        }
4716    }
4717
4718    /**
4719     * This method should typically only be used when granting or revoking
4720     * permissions, since the app may immediately restart after this call.
4721     * <p>
4722     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4723     * guard your work against the app being relaunched.
4724     */
4725    private void killUid(int appId, int userId, String reason) {
4726        final long identity = Binder.clearCallingIdentity();
4727        try {
4728            IActivityManager am = ActivityManager.getService();
4729            if (am != null) {
4730                try {
4731                    am.killUid(appId, userId, reason);
4732                } catch (RemoteException e) {
4733                    /* ignore - same process */
4734                }
4735            }
4736        } finally {
4737            Binder.restoreCallingIdentity(identity);
4738        }
4739    }
4740
4741    /**
4742     * Compares two sets of signatures. Returns:
4743     * <br />
4744     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4745     * <br />
4746     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4747     * <br />
4748     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4749     * <br />
4750     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4751     * <br />
4752     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4753     */
4754    static int compareSignatures(Signature[] s1, Signature[] s2) {
4755        if (s1 == null) {
4756            return s2 == null
4757                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4758                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4759        }
4760
4761        if (s2 == null) {
4762            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4763        }
4764
4765        if (s1.length != s2.length) {
4766            return PackageManager.SIGNATURE_NO_MATCH;
4767        }
4768
4769        // Since both signature sets are of size 1, we can compare without HashSets.
4770        if (s1.length == 1) {
4771            return s1[0].equals(s2[0]) ?
4772                    PackageManager.SIGNATURE_MATCH :
4773                    PackageManager.SIGNATURE_NO_MATCH;
4774        }
4775
4776        ArraySet<Signature> set1 = new ArraySet<Signature>();
4777        for (Signature sig : s1) {
4778            set1.add(sig);
4779        }
4780        ArraySet<Signature> set2 = new ArraySet<Signature>();
4781        for (Signature sig : s2) {
4782            set2.add(sig);
4783        }
4784        // Make sure s2 contains all signatures in s1.
4785        if (set1.equals(set2)) {
4786            return PackageManager.SIGNATURE_MATCH;
4787        }
4788        return PackageManager.SIGNATURE_NO_MATCH;
4789    }
4790
4791    /**
4792     * If the database version for this type of package (internal storage or
4793     * external storage) is less than the version where package signatures
4794     * were updated, return true.
4795     */
4796    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4797        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4798        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4799    }
4800
4801    /**
4802     * Used for backward compatibility to make sure any packages with
4803     * certificate chains get upgraded to the new style. {@code existingSigs}
4804     * will be in the old format (since they were stored on disk from before the
4805     * system upgrade) and {@code scannedSigs} will be in the newer format.
4806     */
4807    private int compareSignaturesCompat(PackageSignatures existingSigs,
4808            PackageParser.Package scannedPkg) {
4809        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4810            return PackageManager.SIGNATURE_NO_MATCH;
4811        }
4812
4813        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4814        for (Signature sig : existingSigs.mSignatures) {
4815            existingSet.add(sig);
4816        }
4817        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4818        for (Signature sig : scannedPkg.mSignatures) {
4819            try {
4820                Signature[] chainSignatures = sig.getChainSignatures();
4821                for (Signature chainSig : chainSignatures) {
4822                    scannedCompatSet.add(chainSig);
4823                }
4824            } catch (CertificateEncodingException e) {
4825                scannedCompatSet.add(sig);
4826            }
4827        }
4828        /*
4829         * Make sure the expanded scanned set contains all signatures in the
4830         * existing one.
4831         */
4832        if (scannedCompatSet.equals(existingSet)) {
4833            // Migrate the old signatures to the new scheme.
4834            existingSigs.assignSignatures(scannedPkg.mSignatures);
4835            // The new KeySets will be re-added later in the scanning process.
4836            synchronized (mPackages) {
4837                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4838            }
4839            return PackageManager.SIGNATURE_MATCH;
4840        }
4841        return PackageManager.SIGNATURE_NO_MATCH;
4842    }
4843
4844    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4845        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4846        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4847    }
4848
4849    private int compareSignaturesRecover(PackageSignatures existingSigs,
4850            PackageParser.Package scannedPkg) {
4851        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4852            return PackageManager.SIGNATURE_NO_MATCH;
4853        }
4854
4855        String msg = null;
4856        try {
4857            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4858                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4859                        + scannedPkg.packageName);
4860                return PackageManager.SIGNATURE_MATCH;
4861            }
4862        } catch (CertificateException e) {
4863            msg = e.getMessage();
4864        }
4865
4866        logCriticalInfo(Log.INFO,
4867                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4868        return PackageManager.SIGNATURE_NO_MATCH;
4869    }
4870
4871    @Override
4872    public List<String> getAllPackages() {
4873        synchronized (mPackages) {
4874            return new ArrayList<String>(mPackages.keySet());
4875        }
4876    }
4877
4878    @Override
4879    public String[] getPackagesForUid(int uid) {
4880        final int userId = UserHandle.getUserId(uid);
4881        uid = UserHandle.getAppId(uid);
4882        // reader
4883        synchronized (mPackages) {
4884            Object obj = mSettings.getUserIdLPr(uid);
4885            if (obj instanceof SharedUserSetting) {
4886                final SharedUserSetting sus = (SharedUserSetting) obj;
4887                final int N = sus.packages.size();
4888                String[] res = new String[N];
4889                final Iterator<PackageSetting> it = sus.packages.iterator();
4890                int i = 0;
4891                while (it.hasNext()) {
4892                    PackageSetting ps = it.next();
4893                    if (ps.getInstalled(userId)) {
4894                        res[i++] = ps.name;
4895                    } else {
4896                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4897                    }
4898                }
4899                return res;
4900            } else if (obj instanceof PackageSetting) {
4901                final PackageSetting ps = (PackageSetting) obj;
4902                return new String[] { ps.name };
4903            }
4904        }
4905        return null;
4906    }
4907
4908    @Override
4909    public String getNameForUid(int uid) {
4910        // reader
4911        synchronized (mPackages) {
4912            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4913            if (obj instanceof SharedUserSetting) {
4914                final SharedUserSetting sus = (SharedUserSetting) obj;
4915                return sus.name + ":" + sus.userId;
4916            } else if (obj instanceof PackageSetting) {
4917                final PackageSetting ps = (PackageSetting) obj;
4918                return ps.name;
4919            }
4920        }
4921        return null;
4922    }
4923
4924    @Override
4925    public int getUidForSharedUser(String sharedUserName) {
4926        if(sharedUserName == null) {
4927            return -1;
4928        }
4929        // reader
4930        synchronized (mPackages) {
4931            SharedUserSetting suid;
4932            try {
4933                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4934                if (suid != null) {
4935                    return suid.userId;
4936                }
4937            } catch (PackageManagerException ignore) {
4938                // can't happen, but, still need to catch it
4939            }
4940            return -1;
4941        }
4942    }
4943
4944    @Override
4945    public int getFlagsForUid(int uid) {
4946        synchronized (mPackages) {
4947            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4948            if (obj instanceof SharedUserSetting) {
4949                final SharedUserSetting sus = (SharedUserSetting) obj;
4950                return sus.pkgFlags;
4951            } else if (obj instanceof PackageSetting) {
4952                final PackageSetting ps = (PackageSetting) obj;
4953                return ps.pkgFlags;
4954            }
4955        }
4956        return 0;
4957    }
4958
4959    @Override
4960    public int getPrivateFlagsForUid(int uid) {
4961        synchronized (mPackages) {
4962            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4963            if (obj instanceof SharedUserSetting) {
4964                final SharedUserSetting sus = (SharedUserSetting) obj;
4965                return sus.pkgPrivateFlags;
4966            } else if (obj instanceof PackageSetting) {
4967                final PackageSetting ps = (PackageSetting) obj;
4968                return ps.pkgPrivateFlags;
4969            }
4970        }
4971        return 0;
4972    }
4973
4974    @Override
4975    public boolean isUidPrivileged(int uid) {
4976        uid = UserHandle.getAppId(uid);
4977        // reader
4978        synchronized (mPackages) {
4979            Object obj = mSettings.getUserIdLPr(uid);
4980            if (obj instanceof SharedUserSetting) {
4981                final SharedUserSetting sus = (SharedUserSetting) obj;
4982                final Iterator<PackageSetting> it = sus.packages.iterator();
4983                while (it.hasNext()) {
4984                    if (it.next().isPrivileged()) {
4985                        return true;
4986                    }
4987                }
4988            } else if (obj instanceof PackageSetting) {
4989                final PackageSetting ps = (PackageSetting) obj;
4990                return ps.isPrivileged();
4991            }
4992        }
4993        return false;
4994    }
4995
4996    @Override
4997    public String[] getAppOpPermissionPackages(String permissionName) {
4998        synchronized (mPackages) {
4999            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5000            if (pkgs == null) {
5001                return null;
5002            }
5003            return pkgs.toArray(new String[pkgs.size()]);
5004        }
5005    }
5006
5007    @Override
5008    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5009            int flags, int userId) {
5010        try {
5011            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5012
5013            if (!sUserManager.exists(userId)) return null;
5014            flags = updateFlagsForResolve(flags, userId, intent);
5015            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5016                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5017
5018            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5019            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5020                    flags, userId);
5021            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5022
5023            final ResolveInfo bestChoice =
5024                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5025            return bestChoice;
5026        } finally {
5027            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5028        }
5029    }
5030
5031    @Override
5032    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5033            IntentFilter filter, int match, ComponentName activity) {
5034        final int userId = UserHandle.getCallingUserId();
5035        if (DEBUG_PREFERRED) {
5036            Log.v(TAG, "setLastChosenActivity intent=" + intent
5037                + " resolvedType=" + resolvedType
5038                + " flags=" + flags
5039                + " filter=" + filter
5040                + " match=" + match
5041                + " activity=" + activity);
5042            filter.dump(new PrintStreamPrinter(System.out), "    ");
5043        }
5044        intent.setComponent(null);
5045        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5046                userId);
5047        // Find any earlier preferred or last chosen entries and nuke them
5048        findPreferredActivity(intent, resolvedType,
5049                flags, query, 0, false, true, false, userId);
5050        // Add the new activity as the last chosen for this filter
5051        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5052                "Setting last chosen");
5053    }
5054
5055    @Override
5056    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5057        final int userId = UserHandle.getCallingUserId();
5058        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5059        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5060                userId);
5061        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5062                false, false, false, userId);
5063    }
5064
5065    private boolean isEphemeralDisabled() {
5066        // ephemeral apps have been disabled across the board
5067        if (DISABLE_EPHEMERAL_APPS) {
5068            return true;
5069        }
5070        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5071        if (!mSystemReady) {
5072            return true;
5073        }
5074        // we can't get a content resolver until the system is ready; these checks must happen last
5075        final ContentResolver resolver = mContext.getContentResolver();
5076        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5077            return true;
5078        }
5079        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5080    }
5081
5082    private boolean isEphemeralAllowed(
5083            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5084            boolean skipPackageCheck) {
5085        // Short circuit and return early if possible.
5086        if (isEphemeralDisabled()) {
5087            return false;
5088        }
5089        final int callingUser = UserHandle.getCallingUserId();
5090        if (callingUser != UserHandle.USER_SYSTEM) {
5091            return false;
5092        }
5093        if (mEphemeralResolverConnection == null) {
5094            return false;
5095        }
5096        if (mEphemeralInstallerComponent == null) {
5097            return false;
5098        }
5099        if (intent.getComponent() != null) {
5100            return false;
5101        }
5102        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5103            return false;
5104        }
5105        if (!skipPackageCheck && intent.getPackage() != null) {
5106            return false;
5107        }
5108        final boolean isWebUri = hasWebURI(intent);
5109        if (!isWebUri || intent.getData().getHost() == null) {
5110            return false;
5111        }
5112        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5113        synchronized (mPackages) {
5114            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5115            for (int n = 0; n < count; n++) {
5116                ResolveInfo info = resolvedActivities.get(n);
5117                String packageName = info.activityInfo.packageName;
5118                PackageSetting ps = mSettings.mPackages.get(packageName);
5119                if (ps != null) {
5120                    // Try to get the status from User settings first
5121                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5122                    int status = (int) (packedStatus >> 32);
5123                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5124                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5125                        if (DEBUG_EPHEMERAL) {
5126                            Slog.v(TAG, "DENY ephemeral apps;"
5127                                + " pkg: " + packageName + ", status: " + status);
5128                        }
5129                        return false;
5130                    }
5131                }
5132            }
5133        }
5134        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5135        return true;
5136    }
5137
5138    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5139            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5140            int userId) {
5141        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5142                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5143                        callingPackage, userId));
5144        mHandler.sendMessage(msg);
5145    }
5146
5147    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5148            int flags, List<ResolveInfo> query, int userId) {
5149        if (query != null) {
5150            final int N = query.size();
5151            if (N == 1) {
5152                return query.get(0);
5153            } else if (N > 1) {
5154                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5155                // If there is more than one activity with the same priority,
5156                // then let the user decide between them.
5157                ResolveInfo r0 = query.get(0);
5158                ResolveInfo r1 = query.get(1);
5159                if (DEBUG_INTENT_MATCHING || debug) {
5160                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5161                            + r1.activityInfo.name + "=" + r1.priority);
5162                }
5163                // If the first activity has a higher priority, or a different
5164                // default, then it is always desirable to pick it.
5165                if (r0.priority != r1.priority
5166                        || r0.preferredOrder != r1.preferredOrder
5167                        || r0.isDefault != r1.isDefault) {
5168                    return query.get(0);
5169                }
5170                // If we have saved a preference for a preferred activity for
5171                // this Intent, use that.
5172                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5173                        flags, query, r0.priority, true, false, debug, userId);
5174                if (ri != null) {
5175                    return ri;
5176                }
5177                ri = new ResolveInfo(mResolveInfo);
5178                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5179                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5180                // If all of the options come from the same package, show the application's
5181                // label and icon instead of the generic resolver's.
5182                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5183                // and then throw away the ResolveInfo itself, meaning that the caller loses
5184                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5185                // a fallback for this case; we only set the target package's resources on
5186                // the ResolveInfo, not the ActivityInfo.
5187                final String intentPackage = intent.getPackage();
5188                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5189                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5190                    ri.resolvePackageName = intentPackage;
5191                    if (userNeedsBadging(userId)) {
5192                        ri.noResourceId = true;
5193                    } else {
5194                        ri.icon = appi.icon;
5195                    }
5196                    ri.iconResourceId = appi.icon;
5197                    ri.labelRes = appi.labelRes;
5198                }
5199                ri.activityInfo.applicationInfo = new ApplicationInfo(
5200                        ri.activityInfo.applicationInfo);
5201                if (userId != 0) {
5202                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5203                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5204                }
5205                // Make sure that the resolver is displayable in car mode
5206                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5207                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5208                return ri;
5209            }
5210        }
5211        return null;
5212    }
5213
5214    /**
5215     * Return true if the given list is not empty and all of its contents have
5216     * an activityInfo with the given package name.
5217     */
5218    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5219        if (ArrayUtils.isEmpty(list)) {
5220            return false;
5221        }
5222        for (int i = 0, N = list.size(); i < N; i++) {
5223            final ResolveInfo ri = list.get(i);
5224            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5225            if (ai == null || !packageName.equals(ai.packageName)) {
5226                return false;
5227            }
5228        }
5229        return true;
5230    }
5231
5232    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5233            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5234        final int N = query.size();
5235        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5236                .get(userId);
5237        // Get the list of persistent preferred activities that handle the intent
5238        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5239        List<PersistentPreferredActivity> pprefs = ppir != null
5240                ? ppir.queryIntent(intent, resolvedType,
5241                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5242                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5243                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5244                : null;
5245        if (pprefs != null && pprefs.size() > 0) {
5246            final int M = pprefs.size();
5247            for (int i=0; i<M; i++) {
5248                final PersistentPreferredActivity ppa = pprefs.get(i);
5249                if (DEBUG_PREFERRED || debug) {
5250                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5251                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5252                            + "\n  component=" + ppa.mComponent);
5253                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5254                }
5255                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5256                        flags | MATCH_DISABLED_COMPONENTS, userId);
5257                if (DEBUG_PREFERRED || debug) {
5258                    Slog.v(TAG, "Found persistent preferred activity:");
5259                    if (ai != null) {
5260                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5261                    } else {
5262                        Slog.v(TAG, "  null");
5263                    }
5264                }
5265                if (ai == null) {
5266                    // This previously registered persistent preferred activity
5267                    // component is no longer known. Ignore it and do NOT remove it.
5268                    continue;
5269                }
5270                for (int j=0; j<N; j++) {
5271                    final ResolveInfo ri = query.get(j);
5272                    if (!ri.activityInfo.applicationInfo.packageName
5273                            .equals(ai.applicationInfo.packageName)) {
5274                        continue;
5275                    }
5276                    if (!ri.activityInfo.name.equals(ai.name)) {
5277                        continue;
5278                    }
5279                    //  Found a persistent preference that can handle the intent.
5280                    if (DEBUG_PREFERRED || debug) {
5281                        Slog.v(TAG, "Returning persistent preferred activity: " +
5282                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5283                    }
5284                    return ri;
5285                }
5286            }
5287        }
5288        return null;
5289    }
5290
5291    // TODO: handle preferred activities missing while user has amnesia
5292    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5293            List<ResolveInfo> query, int priority, boolean always,
5294            boolean removeMatches, boolean debug, int userId) {
5295        if (!sUserManager.exists(userId)) return null;
5296        flags = updateFlagsForResolve(flags, userId, intent);
5297        // writer
5298        synchronized (mPackages) {
5299            if (intent.getSelector() != null) {
5300                intent = intent.getSelector();
5301            }
5302            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5303
5304            // Try to find a matching persistent preferred activity.
5305            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5306                    debug, userId);
5307
5308            // If a persistent preferred activity matched, use it.
5309            if (pri != null) {
5310                return pri;
5311            }
5312
5313            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5314            // Get the list of preferred activities that handle the intent
5315            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5316            List<PreferredActivity> prefs = pir != null
5317                    ? pir.queryIntent(intent, resolvedType,
5318                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5319                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5320                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5321                    : null;
5322            if (prefs != null && prefs.size() > 0) {
5323                boolean changed = false;
5324                try {
5325                    // First figure out how good the original match set is.
5326                    // We will only allow preferred activities that came
5327                    // from the same match quality.
5328                    int match = 0;
5329
5330                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5331
5332                    final int N = query.size();
5333                    for (int j=0; j<N; j++) {
5334                        final ResolveInfo ri = query.get(j);
5335                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5336                                + ": 0x" + Integer.toHexString(match));
5337                        if (ri.match > match) {
5338                            match = ri.match;
5339                        }
5340                    }
5341
5342                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5343                            + Integer.toHexString(match));
5344
5345                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5346                    final int M = prefs.size();
5347                    for (int i=0; i<M; i++) {
5348                        final PreferredActivity pa = prefs.get(i);
5349                        if (DEBUG_PREFERRED || debug) {
5350                            Slog.v(TAG, "Checking PreferredActivity ds="
5351                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5352                                    + "\n  component=" + pa.mPref.mComponent);
5353                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5354                        }
5355                        if (pa.mPref.mMatch != match) {
5356                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5357                                    + Integer.toHexString(pa.mPref.mMatch));
5358                            continue;
5359                        }
5360                        // If it's not an "always" type preferred activity and that's what we're
5361                        // looking for, skip it.
5362                        if (always && !pa.mPref.mAlways) {
5363                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5364                            continue;
5365                        }
5366                        final ActivityInfo ai = getActivityInfo(
5367                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5368                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5369                                userId);
5370                        if (DEBUG_PREFERRED || debug) {
5371                            Slog.v(TAG, "Found preferred activity:");
5372                            if (ai != null) {
5373                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5374                            } else {
5375                                Slog.v(TAG, "  null");
5376                            }
5377                        }
5378                        if (ai == null) {
5379                            // This previously registered preferred activity
5380                            // component is no longer known.  Most likely an update
5381                            // to the app was installed and in the new version this
5382                            // component no longer exists.  Clean it up by removing
5383                            // it from the preferred activities list, and skip it.
5384                            Slog.w(TAG, "Removing dangling preferred activity: "
5385                                    + pa.mPref.mComponent);
5386                            pir.removeFilter(pa);
5387                            changed = true;
5388                            continue;
5389                        }
5390                        for (int j=0; j<N; j++) {
5391                            final ResolveInfo ri = query.get(j);
5392                            if (!ri.activityInfo.applicationInfo.packageName
5393                                    .equals(ai.applicationInfo.packageName)) {
5394                                continue;
5395                            }
5396                            if (!ri.activityInfo.name.equals(ai.name)) {
5397                                continue;
5398                            }
5399
5400                            if (removeMatches) {
5401                                pir.removeFilter(pa);
5402                                changed = true;
5403                                if (DEBUG_PREFERRED) {
5404                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5405                                }
5406                                break;
5407                            }
5408
5409                            // Okay we found a previously set preferred or last chosen app.
5410                            // If the result set is different from when this
5411                            // was created, we need to clear it and re-ask the
5412                            // user their preference, if we're looking for an "always" type entry.
5413                            if (always && !pa.mPref.sameSet(query)) {
5414                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5415                                        + intent + " type " + resolvedType);
5416                                if (DEBUG_PREFERRED) {
5417                                    Slog.v(TAG, "Removing preferred activity since set changed "
5418                                            + pa.mPref.mComponent);
5419                                }
5420                                pir.removeFilter(pa);
5421                                // Re-add the filter as a "last chosen" entry (!always)
5422                                PreferredActivity lastChosen = new PreferredActivity(
5423                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5424                                pir.addFilter(lastChosen);
5425                                changed = true;
5426                                return null;
5427                            }
5428
5429                            // Yay! Either the set matched or we're looking for the last chosen
5430                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5431                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5432                            return ri;
5433                        }
5434                    }
5435                } finally {
5436                    if (changed) {
5437                        if (DEBUG_PREFERRED) {
5438                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5439                        }
5440                        scheduleWritePackageRestrictionsLocked(userId);
5441                    }
5442                }
5443            }
5444        }
5445        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5446        return null;
5447    }
5448
5449    /*
5450     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5451     */
5452    @Override
5453    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5454            int targetUserId) {
5455        mContext.enforceCallingOrSelfPermission(
5456                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5457        List<CrossProfileIntentFilter> matches =
5458                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5459        if (matches != null) {
5460            int size = matches.size();
5461            for (int i = 0; i < size; i++) {
5462                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5463            }
5464        }
5465        if (hasWebURI(intent)) {
5466            // cross-profile app linking works only towards the parent.
5467            final UserInfo parent = getProfileParent(sourceUserId);
5468            synchronized(mPackages) {
5469                int flags = updateFlagsForResolve(0, parent.id, intent);
5470                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5471                        intent, resolvedType, flags, sourceUserId, parent.id);
5472                return xpDomainInfo != null;
5473            }
5474        }
5475        return false;
5476    }
5477
5478    private UserInfo getProfileParent(int userId) {
5479        final long identity = Binder.clearCallingIdentity();
5480        try {
5481            return sUserManager.getProfileParent(userId);
5482        } finally {
5483            Binder.restoreCallingIdentity(identity);
5484        }
5485    }
5486
5487    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5488            String resolvedType, int userId) {
5489        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5490        if (resolver != null) {
5491            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5492                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5493        }
5494        return null;
5495    }
5496
5497    @Override
5498    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5499            String resolvedType, int flags, int userId) {
5500        try {
5501            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5502
5503            return new ParceledListSlice<>(
5504                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5505        } finally {
5506            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5507        }
5508    }
5509
5510    /**
5511     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5512     * ephemeral, returns {@code null}.
5513     */
5514    private String getEphemeralPackageName(int callingUid) {
5515        final int appId = UserHandle.getAppId(callingUid);
5516        synchronized (mPackages) {
5517            final Object obj = mSettings.getUserIdLPr(appId);
5518            if (obj instanceof PackageSetting) {
5519                final PackageSetting ps = (PackageSetting) obj;
5520                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5521            }
5522        }
5523        return null;
5524    }
5525
5526    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5527            String resolvedType, int flags, int userId) {
5528        if (!sUserManager.exists(userId)) return Collections.emptyList();
5529        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5530        flags = updateFlagsForResolve(flags, userId, intent);
5531        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5532                false /* requireFullPermission */, false /* checkShell */,
5533                "query intent activities");
5534        ComponentName comp = intent.getComponent();
5535        if (comp == null) {
5536            if (intent.getSelector() != null) {
5537                intent = intent.getSelector();
5538                comp = intent.getComponent();
5539            }
5540        }
5541
5542        if (comp != null) {
5543            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5544            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5545            if (ai != null) {
5546                final ResolveInfo ri = new ResolveInfo();
5547                ri.activityInfo = ai;
5548                list.add(ri);
5549            }
5550            return list;
5551        }
5552
5553        // reader
5554        boolean sortResult = false;
5555        boolean addEphemeral = false;
5556        List<ResolveInfo> result;
5557        final String pkgName = intent.getPackage();
5558        synchronized (mPackages) {
5559            if (pkgName == null) {
5560                List<CrossProfileIntentFilter> matchingFilters =
5561                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5562                // Check for results that need to skip the current profile.
5563                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5564                        resolvedType, flags, userId);
5565                if (xpResolveInfo != null) {
5566                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5567                    xpResult.add(xpResolveInfo);
5568                    return filterForEphemeral(
5569                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5570                }
5571
5572                // Check for results in the current profile.
5573                result = filterIfNotSystemUser(mActivities.queryIntent(
5574                        intent, resolvedType, flags, userId), userId);
5575                addEphemeral =
5576                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5577
5578                // Check for cross profile results.
5579                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5580                xpResolveInfo = queryCrossProfileIntents(
5581                        matchingFilters, intent, resolvedType, flags, userId,
5582                        hasNonNegativePriorityResult);
5583                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5584                    boolean isVisibleToUser = filterIfNotSystemUser(
5585                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5586                    if (isVisibleToUser) {
5587                        result.add(xpResolveInfo);
5588                        sortResult = true;
5589                    }
5590                }
5591                if (hasWebURI(intent)) {
5592                    CrossProfileDomainInfo xpDomainInfo = null;
5593                    final UserInfo parent = getProfileParent(userId);
5594                    if (parent != null) {
5595                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5596                                flags, userId, parent.id);
5597                    }
5598                    if (xpDomainInfo != null) {
5599                        if (xpResolveInfo != null) {
5600                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5601                            // in the result.
5602                            result.remove(xpResolveInfo);
5603                        }
5604                        if (result.size() == 0 && !addEphemeral) {
5605                            // No result in current profile, but found candidate in parent user.
5606                            // And we are not going to add emphemeral app, so we can return the
5607                            // result straight away.
5608                            result.add(xpDomainInfo.resolveInfo);
5609                            return filterForEphemeral(result, ephemeralPkgName);
5610                        }
5611                    } else if (result.size() <= 1 && !addEphemeral) {
5612                        // No result in parent user and <= 1 result in current profile, and we
5613                        // are not going to add emphemeral app, so we can return the result without
5614                        // further processing.
5615                        return filterForEphemeral(result, ephemeralPkgName);
5616                    }
5617                    // We have more than one candidate (combining results from current and parent
5618                    // profile), so we need filtering and sorting.
5619                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5620                            intent, flags, result, xpDomainInfo, userId);
5621                    sortResult = true;
5622                }
5623            } else {
5624                final PackageParser.Package pkg = mPackages.get(pkgName);
5625                if (pkg != null) {
5626                    result = filterIfNotSystemUser(
5627                            mActivities.queryIntentForPackage(
5628                                    intent, resolvedType, flags, pkg.activities, userId),
5629                            userId);
5630                } else {
5631                    // the caller wants to resolve for a particular package; however, there
5632                    // were no installed results, so, try to find an ephemeral result
5633                    addEphemeral = isEphemeralAllowed(
5634                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5635                    result = new ArrayList<ResolveInfo>();
5636                }
5637            }
5638        }
5639        if (addEphemeral) {
5640            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5641            final EphemeralRequest requestObject = new EphemeralRequest(
5642                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5643                    null /*launchIntent*/, null /*callingPackage*/, userId);
5644            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5645                    mContext, mEphemeralResolverConnection, requestObject);
5646            if (intentInfo != null) {
5647                if (DEBUG_EPHEMERAL) {
5648                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5649                }
5650                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5651                ephemeralInstaller.ephemeralResponse = intentInfo;
5652                // make sure this resolver is the default
5653                ephemeralInstaller.isDefault = true;
5654                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5655                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5656                // add a non-generic filter
5657                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5658                ephemeralInstaller.filter.addDataPath(
5659                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5660                result.add(ephemeralInstaller);
5661            }
5662            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5663        }
5664        if (sortResult) {
5665            Collections.sort(result, mResolvePrioritySorter);
5666        }
5667        return filterForEphemeral(result, ephemeralPkgName);
5668    }
5669
5670    private static class CrossProfileDomainInfo {
5671        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5672        ResolveInfo resolveInfo;
5673        /* Best domain verification status of the activities found in the other profile */
5674        int bestDomainVerificationStatus;
5675    }
5676
5677    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5678            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5679        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5680                sourceUserId)) {
5681            return null;
5682        }
5683        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5684                resolvedType, flags, parentUserId);
5685
5686        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5687            return null;
5688        }
5689        CrossProfileDomainInfo result = null;
5690        int size = resultTargetUser.size();
5691        for (int i = 0; i < size; i++) {
5692            ResolveInfo riTargetUser = resultTargetUser.get(i);
5693            // Intent filter verification is only for filters that specify a host. So don't return
5694            // those that handle all web uris.
5695            if (riTargetUser.handleAllWebDataURI) {
5696                continue;
5697            }
5698            String packageName = riTargetUser.activityInfo.packageName;
5699            PackageSetting ps = mSettings.mPackages.get(packageName);
5700            if (ps == null) {
5701                continue;
5702            }
5703            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5704            int status = (int)(verificationState >> 32);
5705            if (result == null) {
5706                result = new CrossProfileDomainInfo();
5707                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5708                        sourceUserId, parentUserId);
5709                result.bestDomainVerificationStatus = status;
5710            } else {
5711                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5712                        result.bestDomainVerificationStatus);
5713            }
5714        }
5715        // Don't consider matches with status NEVER across profiles.
5716        if (result != null && result.bestDomainVerificationStatus
5717                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5718            return null;
5719        }
5720        return result;
5721    }
5722
5723    /**
5724     * Verification statuses are ordered from the worse to the best, except for
5725     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5726     */
5727    private int bestDomainVerificationStatus(int status1, int status2) {
5728        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5729            return status2;
5730        }
5731        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5732            return status1;
5733        }
5734        return (int) MathUtils.max(status1, status2);
5735    }
5736
5737    private boolean isUserEnabled(int userId) {
5738        long callingId = Binder.clearCallingIdentity();
5739        try {
5740            UserInfo userInfo = sUserManager.getUserInfo(userId);
5741            return userInfo != null && userInfo.isEnabled();
5742        } finally {
5743            Binder.restoreCallingIdentity(callingId);
5744        }
5745    }
5746
5747    /**
5748     * Filter out activities with systemUserOnly flag set, when current user is not System.
5749     *
5750     * @return filtered list
5751     */
5752    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5753        if (userId == UserHandle.USER_SYSTEM) {
5754            return resolveInfos;
5755        }
5756        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5757            ResolveInfo info = resolveInfos.get(i);
5758            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5759                resolveInfos.remove(i);
5760            }
5761        }
5762        return resolveInfos;
5763    }
5764
5765    /**
5766     * Filters out ephemeral activities.
5767     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5768     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5769     *
5770     * @param resolveInfos The pre-filtered list of resolved activities
5771     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5772     *          is performed.
5773     * @return A filtered list of resolved activities.
5774     */
5775    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5776            String ephemeralPkgName) {
5777        if (ephemeralPkgName == null) {
5778            return resolveInfos;
5779        }
5780        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5781            ResolveInfo info = resolveInfos.get(i);
5782            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5783            // allow activities that are defined in the provided package
5784            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5785                continue;
5786            }
5787            // allow activities that have been explicitly exposed to ephemeral apps
5788            if (!isEphemeralApp
5789                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5790                continue;
5791            }
5792            resolveInfos.remove(i);
5793        }
5794        return resolveInfos;
5795    }
5796
5797    /**
5798     * @param resolveInfos list of resolve infos in descending priority order
5799     * @return if the list contains a resolve info with non-negative priority
5800     */
5801    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5802        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5803    }
5804
5805    private static boolean hasWebURI(Intent intent) {
5806        if (intent.getData() == null) {
5807            return false;
5808        }
5809        final String scheme = intent.getScheme();
5810        if (TextUtils.isEmpty(scheme)) {
5811            return false;
5812        }
5813        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5814    }
5815
5816    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5817            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5818            int userId) {
5819        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5820
5821        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5822            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5823                    candidates.size());
5824        }
5825
5826        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5827        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5828        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5829        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5830        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5831        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5832
5833        synchronized (mPackages) {
5834            final int count = candidates.size();
5835            // First, try to use linked apps. Partition the candidates into four lists:
5836            // one for the final results, one for the "do not use ever", one for "undefined status"
5837            // and finally one for "browser app type".
5838            for (int n=0; n<count; n++) {
5839                ResolveInfo info = candidates.get(n);
5840                String packageName = info.activityInfo.packageName;
5841                PackageSetting ps = mSettings.mPackages.get(packageName);
5842                if (ps != null) {
5843                    // Add to the special match all list (Browser use case)
5844                    if (info.handleAllWebDataURI) {
5845                        matchAllList.add(info);
5846                        continue;
5847                    }
5848                    // Try to get the status from User settings first
5849                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5850                    int status = (int)(packedStatus >> 32);
5851                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5852                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5853                        if (DEBUG_DOMAIN_VERIFICATION) {
5854                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5855                                    + " : linkgen=" + linkGeneration);
5856                        }
5857                        // Use link-enabled generation as preferredOrder, i.e.
5858                        // prefer newly-enabled over earlier-enabled.
5859                        info.preferredOrder = linkGeneration;
5860                        alwaysList.add(info);
5861                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5862                        if (DEBUG_DOMAIN_VERIFICATION) {
5863                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5864                        }
5865                        neverList.add(info);
5866                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5867                        if (DEBUG_DOMAIN_VERIFICATION) {
5868                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5869                        }
5870                        alwaysAskList.add(info);
5871                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5872                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5873                        if (DEBUG_DOMAIN_VERIFICATION) {
5874                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5875                        }
5876                        undefinedList.add(info);
5877                    }
5878                }
5879            }
5880
5881            // We'll want to include browser possibilities in a few cases
5882            boolean includeBrowser = false;
5883
5884            // First try to add the "always" resolution(s) for the current user, if any
5885            if (alwaysList.size() > 0) {
5886                result.addAll(alwaysList);
5887            } else {
5888                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5889                result.addAll(undefinedList);
5890                // Maybe add one for the other profile.
5891                if (xpDomainInfo != null && (
5892                        xpDomainInfo.bestDomainVerificationStatus
5893                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5894                    result.add(xpDomainInfo.resolveInfo);
5895                }
5896                includeBrowser = true;
5897            }
5898
5899            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5900            // If there were 'always' entries their preferred order has been set, so we also
5901            // back that off to make the alternatives equivalent
5902            if (alwaysAskList.size() > 0) {
5903                for (ResolveInfo i : result) {
5904                    i.preferredOrder = 0;
5905                }
5906                result.addAll(alwaysAskList);
5907                includeBrowser = true;
5908            }
5909
5910            if (includeBrowser) {
5911                // Also add browsers (all of them or only the default one)
5912                if (DEBUG_DOMAIN_VERIFICATION) {
5913                    Slog.v(TAG, "   ...including browsers in candidate set");
5914                }
5915                if ((matchFlags & MATCH_ALL) != 0) {
5916                    result.addAll(matchAllList);
5917                } else {
5918                    // Browser/generic handling case.  If there's a default browser, go straight
5919                    // to that (but only if there is no other higher-priority match).
5920                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5921                    int maxMatchPrio = 0;
5922                    ResolveInfo defaultBrowserMatch = null;
5923                    final int numCandidates = matchAllList.size();
5924                    for (int n = 0; n < numCandidates; n++) {
5925                        ResolveInfo info = matchAllList.get(n);
5926                        // track the highest overall match priority...
5927                        if (info.priority > maxMatchPrio) {
5928                            maxMatchPrio = info.priority;
5929                        }
5930                        // ...and the highest-priority default browser match
5931                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5932                            if (defaultBrowserMatch == null
5933                                    || (defaultBrowserMatch.priority < info.priority)) {
5934                                if (debug) {
5935                                    Slog.v(TAG, "Considering default browser match " + info);
5936                                }
5937                                defaultBrowserMatch = info;
5938                            }
5939                        }
5940                    }
5941                    if (defaultBrowserMatch != null
5942                            && defaultBrowserMatch.priority >= maxMatchPrio
5943                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5944                    {
5945                        if (debug) {
5946                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5947                        }
5948                        result.add(defaultBrowserMatch);
5949                    } else {
5950                        result.addAll(matchAllList);
5951                    }
5952                }
5953
5954                // If there is nothing selected, add all candidates and remove the ones that the user
5955                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5956                if (result.size() == 0) {
5957                    result.addAll(candidates);
5958                    result.removeAll(neverList);
5959                }
5960            }
5961        }
5962        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5963            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5964                    result.size());
5965            for (ResolveInfo info : result) {
5966                Slog.v(TAG, "  + " + info.activityInfo);
5967            }
5968        }
5969        return result;
5970    }
5971
5972    // Returns a packed value as a long:
5973    //
5974    // high 'int'-sized word: link status: undefined/ask/never/always.
5975    // low 'int'-sized word: relative priority among 'always' results.
5976    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5977        long result = ps.getDomainVerificationStatusForUser(userId);
5978        // if none available, get the master status
5979        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5980            if (ps.getIntentFilterVerificationInfo() != null) {
5981                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5982            }
5983        }
5984        return result;
5985    }
5986
5987    private ResolveInfo querySkipCurrentProfileIntents(
5988            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5989            int flags, int sourceUserId) {
5990        if (matchingFilters != null) {
5991            int size = matchingFilters.size();
5992            for (int i = 0; i < size; i ++) {
5993                CrossProfileIntentFilter filter = matchingFilters.get(i);
5994                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5995                    // Checking if there are activities in the target user that can handle the
5996                    // intent.
5997                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5998                            resolvedType, flags, sourceUserId);
5999                    if (resolveInfo != null) {
6000                        return resolveInfo;
6001                    }
6002                }
6003            }
6004        }
6005        return null;
6006    }
6007
6008    // Return matching ResolveInfo in target user if any.
6009    private ResolveInfo queryCrossProfileIntents(
6010            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6011            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6012        if (matchingFilters != null) {
6013            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6014            // match the same intent. For performance reasons, it is better not to
6015            // run queryIntent twice for the same userId
6016            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6017            int size = matchingFilters.size();
6018            for (int i = 0; i < size; i++) {
6019                CrossProfileIntentFilter filter = matchingFilters.get(i);
6020                int targetUserId = filter.getTargetUserId();
6021                boolean skipCurrentProfile =
6022                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6023                boolean skipCurrentProfileIfNoMatchFound =
6024                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6025                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6026                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6027                    // Checking if there are activities in the target user that can handle the
6028                    // intent.
6029                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6030                            resolvedType, flags, sourceUserId);
6031                    if (resolveInfo != null) return resolveInfo;
6032                    alreadyTriedUserIds.put(targetUserId, true);
6033                }
6034            }
6035        }
6036        return null;
6037    }
6038
6039    /**
6040     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6041     * will forward the intent to the filter's target user.
6042     * Otherwise, returns null.
6043     */
6044    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6045            String resolvedType, int flags, int sourceUserId) {
6046        int targetUserId = filter.getTargetUserId();
6047        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6048                resolvedType, flags, targetUserId);
6049        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6050            // If all the matches in the target profile are suspended, return null.
6051            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6052                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6053                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6054                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6055                            targetUserId);
6056                }
6057            }
6058        }
6059        return null;
6060    }
6061
6062    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6063            int sourceUserId, int targetUserId) {
6064        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6065        long ident = Binder.clearCallingIdentity();
6066        boolean targetIsProfile;
6067        try {
6068            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6069        } finally {
6070            Binder.restoreCallingIdentity(ident);
6071        }
6072        String className;
6073        if (targetIsProfile) {
6074            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6075        } else {
6076            className = FORWARD_INTENT_TO_PARENT;
6077        }
6078        ComponentName forwardingActivityComponentName = new ComponentName(
6079                mAndroidApplication.packageName, className);
6080        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6081                sourceUserId);
6082        if (!targetIsProfile) {
6083            forwardingActivityInfo.showUserIcon = targetUserId;
6084            forwardingResolveInfo.noResourceId = true;
6085        }
6086        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6087        forwardingResolveInfo.priority = 0;
6088        forwardingResolveInfo.preferredOrder = 0;
6089        forwardingResolveInfo.match = 0;
6090        forwardingResolveInfo.isDefault = true;
6091        forwardingResolveInfo.filter = filter;
6092        forwardingResolveInfo.targetUserId = targetUserId;
6093        return forwardingResolveInfo;
6094    }
6095
6096    @Override
6097    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6098            Intent[] specifics, String[] specificTypes, Intent intent,
6099            String resolvedType, int flags, int userId) {
6100        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6101                specificTypes, intent, resolvedType, flags, userId));
6102    }
6103
6104    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6105            Intent[] specifics, String[] specificTypes, Intent intent,
6106            String resolvedType, int flags, int userId) {
6107        if (!sUserManager.exists(userId)) return Collections.emptyList();
6108        flags = updateFlagsForResolve(flags, userId, intent);
6109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6110                false /* requireFullPermission */, false /* checkShell */,
6111                "query intent activity options");
6112        final String resultsAction = intent.getAction();
6113
6114        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6115                | PackageManager.GET_RESOLVED_FILTER, userId);
6116
6117        if (DEBUG_INTENT_MATCHING) {
6118            Log.v(TAG, "Query " + intent + ": " + results);
6119        }
6120
6121        int specificsPos = 0;
6122        int N;
6123
6124        // todo: note that the algorithm used here is O(N^2).  This
6125        // isn't a problem in our current environment, but if we start running
6126        // into situations where we have more than 5 or 10 matches then this
6127        // should probably be changed to something smarter...
6128
6129        // First we go through and resolve each of the specific items
6130        // that were supplied, taking care of removing any corresponding
6131        // duplicate items in the generic resolve list.
6132        if (specifics != null) {
6133            for (int i=0; i<specifics.length; i++) {
6134                final Intent sintent = specifics[i];
6135                if (sintent == null) {
6136                    continue;
6137                }
6138
6139                if (DEBUG_INTENT_MATCHING) {
6140                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6141                }
6142
6143                String action = sintent.getAction();
6144                if (resultsAction != null && resultsAction.equals(action)) {
6145                    // If this action was explicitly requested, then don't
6146                    // remove things that have it.
6147                    action = null;
6148                }
6149
6150                ResolveInfo ri = null;
6151                ActivityInfo ai = null;
6152
6153                ComponentName comp = sintent.getComponent();
6154                if (comp == null) {
6155                    ri = resolveIntent(
6156                        sintent,
6157                        specificTypes != null ? specificTypes[i] : null,
6158                            flags, userId);
6159                    if (ri == null) {
6160                        continue;
6161                    }
6162                    if (ri == mResolveInfo) {
6163                        // ACK!  Must do something better with this.
6164                    }
6165                    ai = ri.activityInfo;
6166                    comp = new ComponentName(ai.applicationInfo.packageName,
6167                            ai.name);
6168                } else {
6169                    ai = getActivityInfo(comp, flags, userId);
6170                    if (ai == null) {
6171                        continue;
6172                    }
6173                }
6174
6175                // Look for any generic query activities that are duplicates
6176                // of this specific one, and remove them from the results.
6177                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6178                N = results.size();
6179                int j;
6180                for (j=specificsPos; j<N; j++) {
6181                    ResolveInfo sri = results.get(j);
6182                    if ((sri.activityInfo.name.equals(comp.getClassName())
6183                            && sri.activityInfo.applicationInfo.packageName.equals(
6184                                    comp.getPackageName()))
6185                        || (action != null && sri.filter.matchAction(action))) {
6186                        results.remove(j);
6187                        if (DEBUG_INTENT_MATCHING) Log.v(
6188                            TAG, "Removing duplicate item from " + j
6189                            + " due to specific " + specificsPos);
6190                        if (ri == null) {
6191                            ri = sri;
6192                        }
6193                        j--;
6194                        N--;
6195                    }
6196                }
6197
6198                // Add this specific item to its proper place.
6199                if (ri == null) {
6200                    ri = new ResolveInfo();
6201                    ri.activityInfo = ai;
6202                }
6203                results.add(specificsPos, ri);
6204                ri.specificIndex = i;
6205                specificsPos++;
6206            }
6207        }
6208
6209        // Now we go through the remaining generic results and remove any
6210        // duplicate actions that are found here.
6211        N = results.size();
6212        for (int i=specificsPos; i<N-1; i++) {
6213            final ResolveInfo rii = results.get(i);
6214            if (rii.filter == null) {
6215                continue;
6216            }
6217
6218            // Iterate over all of the actions of this result's intent
6219            // filter...  typically this should be just one.
6220            final Iterator<String> it = rii.filter.actionsIterator();
6221            if (it == null) {
6222                continue;
6223            }
6224            while (it.hasNext()) {
6225                final String action = it.next();
6226                if (resultsAction != null && resultsAction.equals(action)) {
6227                    // If this action was explicitly requested, then don't
6228                    // remove things that have it.
6229                    continue;
6230                }
6231                for (int j=i+1; j<N; j++) {
6232                    final ResolveInfo rij = results.get(j);
6233                    if (rij.filter != null && rij.filter.hasAction(action)) {
6234                        results.remove(j);
6235                        if (DEBUG_INTENT_MATCHING) Log.v(
6236                            TAG, "Removing duplicate item from " + j
6237                            + " due to action " + action + " at " + i);
6238                        j--;
6239                        N--;
6240                    }
6241                }
6242            }
6243
6244            // If the caller didn't request filter information, drop it now
6245            // so we don't have to marshall/unmarshall it.
6246            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6247                rii.filter = null;
6248            }
6249        }
6250
6251        // Filter out the caller activity if so requested.
6252        if (caller != null) {
6253            N = results.size();
6254            for (int i=0; i<N; i++) {
6255                ActivityInfo ainfo = results.get(i).activityInfo;
6256                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6257                        && caller.getClassName().equals(ainfo.name)) {
6258                    results.remove(i);
6259                    break;
6260                }
6261            }
6262        }
6263
6264        // If the caller didn't request filter information,
6265        // drop them now so we don't have to
6266        // marshall/unmarshall it.
6267        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6268            N = results.size();
6269            for (int i=0; i<N; i++) {
6270                results.get(i).filter = null;
6271            }
6272        }
6273
6274        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6275        return results;
6276    }
6277
6278    @Override
6279    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6280            String resolvedType, int flags, int userId) {
6281        return new ParceledListSlice<>(
6282                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6283    }
6284
6285    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6286            String resolvedType, int flags, int userId) {
6287        if (!sUserManager.exists(userId)) return Collections.emptyList();
6288        flags = updateFlagsForResolve(flags, userId, intent);
6289        ComponentName comp = intent.getComponent();
6290        if (comp == null) {
6291            if (intent.getSelector() != null) {
6292                intent = intent.getSelector();
6293                comp = intent.getComponent();
6294            }
6295        }
6296        if (comp != null) {
6297            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6298            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6299            if (ai != null) {
6300                ResolveInfo ri = new ResolveInfo();
6301                ri.activityInfo = ai;
6302                list.add(ri);
6303            }
6304            return list;
6305        }
6306
6307        // reader
6308        synchronized (mPackages) {
6309            String pkgName = intent.getPackage();
6310            if (pkgName == null) {
6311                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6312            }
6313            final PackageParser.Package pkg = mPackages.get(pkgName);
6314            if (pkg != null) {
6315                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6316                        userId);
6317            }
6318            return Collections.emptyList();
6319        }
6320    }
6321
6322    @Override
6323    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6324        if (!sUserManager.exists(userId)) return null;
6325        flags = updateFlagsForResolve(flags, userId, intent);
6326        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6327        if (query != null) {
6328            if (query.size() >= 1) {
6329                // If there is more than one service with the same priority,
6330                // just arbitrarily pick the first one.
6331                return query.get(0);
6332            }
6333        }
6334        return null;
6335    }
6336
6337    @Override
6338    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6339            String resolvedType, int flags, int userId) {
6340        return new ParceledListSlice<>(
6341                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6342    }
6343
6344    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6345            String resolvedType, int flags, int userId) {
6346        if (!sUserManager.exists(userId)) return Collections.emptyList();
6347        flags = updateFlagsForResolve(flags, userId, intent);
6348        ComponentName comp = intent.getComponent();
6349        if (comp == null) {
6350            if (intent.getSelector() != null) {
6351                intent = intent.getSelector();
6352                comp = intent.getComponent();
6353            }
6354        }
6355        if (comp != null) {
6356            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6357            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6358            if (si != null) {
6359                final ResolveInfo ri = new ResolveInfo();
6360                ri.serviceInfo = si;
6361                list.add(ri);
6362            }
6363            return list;
6364        }
6365
6366        // reader
6367        synchronized (mPackages) {
6368            String pkgName = intent.getPackage();
6369            if (pkgName == null) {
6370                return mServices.queryIntent(intent, resolvedType, flags, userId);
6371            }
6372            final PackageParser.Package pkg = mPackages.get(pkgName);
6373            if (pkg != null) {
6374                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6375                        userId);
6376            }
6377            return Collections.emptyList();
6378        }
6379    }
6380
6381    @Override
6382    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6383            String resolvedType, int flags, int userId) {
6384        return new ParceledListSlice<>(
6385                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6386    }
6387
6388    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6389            Intent intent, String resolvedType, int flags, int userId) {
6390        if (!sUserManager.exists(userId)) return Collections.emptyList();
6391        flags = updateFlagsForResolve(flags, userId, intent);
6392        ComponentName comp = intent.getComponent();
6393        if (comp == null) {
6394            if (intent.getSelector() != null) {
6395                intent = intent.getSelector();
6396                comp = intent.getComponent();
6397            }
6398        }
6399        if (comp != null) {
6400            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6401            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6402            if (pi != null) {
6403                final ResolveInfo ri = new ResolveInfo();
6404                ri.providerInfo = pi;
6405                list.add(ri);
6406            }
6407            return list;
6408        }
6409
6410        // reader
6411        synchronized (mPackages) {
6412            String pkgName = intent.getPackage();
6413            if (pkgName == null) {
6414                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6415            }
6416            final PackageParser.Package pkg = mPackages.get(pkgName);
6417            if (pkg != null) {
6418                return mProviders.queryIntentForPackage(
6419                        intent, resolvedType, flags, pkg.providers, userId);
6420            }
6421            return Collections.emptyList();
6422        }
6423    }
6424
6425    @Override
6426    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6427        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6428        flags = updateFlagsForPackage(flags, userId, null);
6429        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6430        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6431                true /* requireFullPermission */, false /* checkShell */,
6432                "get installed packages");
6433
6434        // writer
6435        synchronized (mPackages) {
6436            ArrayList<PackageInfo> list;
6437            if (listUninstalled) {
6438                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6439                for (PackageSetting ps : mSettings.mPackages.values()) {
6440                    final PackageInfo pi;
6441                    if (ps.pkg != null) {
6442                        pi = generatePackageInfo(ps, flags, userId);
6443                    } else {
6444                        pi = generatePackageInfo(ps, flags, userId);
6445                    }
6446                    if (pi != null) {
6447                        list.add(pi);
6448                    }
6449                }
6450            } else {
6451                list = new ArrayList<PackageInfo>(mPackages.size());
6452                for (PackageParser.Package p : mPackages.values()) {
6453                    final PackageInfo pi =
6454                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6455                    if (pi != null) {
6456                        list.add(pi);
6457                    }
6458                }
6459            }
6460
6461            return new ParceledListSlice<PackageInfo>(list);
6462        }
6463    }
6464
6465    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6466            String[] permissions, boolean[] tmp, int flags, int userId) {
6467        int numMatch = 0;
6468        final PermissionsState permissionsState = ps.getPermissionsState();
6469        for (int i=0; i<permissions.length; i++) {
6470            final String permission = permissions[i];
6471            if (permissionsState.hasPermission(permission, userId)) {
6472                tmp[i] = true;
6473                numMatch++;
6474            } else {
6475                tmp[i] = false;
6476            }
6477        }
6478        if (numMatch == 0) {
6479            return;
6480        }
6481        final PackageInfo pi;
6482        if (ps.pkg != null) {
6483            pi = generatePackageInfo(ps, flags, userId);
6484        } else {
6485            pi = generatePackageInfo(ps, flags, userId);
6486        }
6487        // The above might return null in cases of uninstalled apps or install-state
6488        // skew across users/profiles.
6489        if (pi != null) {
6490            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6491                if (numMatch == permissions.length) {
6492                    pi.requestedPermissions = permissions;
6493                } else {
6494                    pi.requestedPermissions = new String[numMatch];
6495                    numMatch = 0;
6496                    for (int i=0; i<permissions.length; i++) {
6497                        if (tmp[i]) {
6498                            pi.requestedPermissions[numMatch] = permissions[i];
6499                            numMatch++;
6500                        }
6501                    }
6502                }
6503            }
6504            list.add(pi);
6505        }
6506    }
6507
6508    @Override
6509    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6510            String[] permissions, int flags, int userId) {
6511        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6512        flags = updateFlagsForPackage(flags, userId, permissions);
6513        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6514                true /* requireFullPermission */, false /* checkShell */,
6515                "get packages holding permissions");
6516        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6517
6518        // writer
6519        synchronized (mPackages) {
6520            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6521            boolean[] tmpBools = new boolean[permissions.length];
6522            if (listUninstalled) {
6523                for (PackageSetting ps : mSettings.mPackages.values()) {
6524                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6525                            userId);
6526                }
6527            } else {
6528                for (PackageParser.Package pkg : mPackages.values()) {
6529                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6530                    if (ps != null) {
6531                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6532                                userId);
6533                    }
6534                }
6535            }
6536
6537            return new ParceledListSlice<PackageInfo>(list);
6538        }
6539    }
6540
6541    @Override
6542    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6543        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6544        flags = updateFlagsForApplication(flags, userId, null);
6545        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6546
6547        // writer
6548        synchronized (mPackages) {
6549            ArrayList<ApplicationInfo> list;
6550            if (listUninstalled) {
6551                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6552                for (PackageSetting ps : mSettings.mPackages.values()) {
6553                    ApplicationInfo ai;
6554                    int effectiveFlags = flags;
6555                    if (ps.isSystem()) {
6556                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6557                    }
6558                    if (ps.pkg != null) {
6559                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6560                                ps.readUserState(userId), userId);
6561                    } else {
6562                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6563                                userId);
6564                    }
6565                    if (ai != null) {
6566                        list.add(ai);
6567                    }
6568                }
6569            } else {
6570                list = new ArrayList<ApplicationInfo>(mPackages.size());
6571                for (PackageParser.Package p : mPackages.values()) {
6572                    if (p.mExtras != null) {
6573                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6574                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6575                        if (ai != null) {
6576                            list.add(ai);
6577                        }
6578                    }
6579                }
6580            }
6581
6582            return new ParceledListSlice<ApplicationInfo>(list);
6583        }
6584    }
6585
6586    @Override
6587    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6588        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6589            return null;
6590        }
6591
6592        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6593                "getEphemeralApplications");
6594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6595                true /* requireFullPermission */, false /* checkShell */,
6596                "getEphemeralApplications");
6597        synchronized (mPackages) {
6598            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6599                    .getEphemeralApplicationsLPw(userId);
6600            if (ephemeralApps != null) {
6601                return new ParceledListSlice<>(ephemeralApps);
6602            }
6603        }
6604        return null;
6605    }
6606
6607    @Override
6608    public boolean isEphemeralApplication(String packageName, int userId) {
6609        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6610                true /* requireFullPermission */, false /* checkShell */,
6611                "isEphemeral");
6612        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6613            return false;
6614        }
6615
6616        if (!isCallerSameApp(packageName)) {
6617            return false;
6618        }
6619        synchronized (mPackages) {
6620            PackageParser.Package pkg = mPackages.get(packageName);
6621            if (pkg != null) {
6622                return pkg.applicationInfo.isEphemeralApp();
6623            }
6624        }
6625        return false;
6626    }
6627
6628    @Override
6629    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6630        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6631            return null;
6632        }
6633
6634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6635                true /* requireFullPermission */, false /* checkShell */,
6636                "getCookie");
6637        if (!isCallerSameApp(packageName)) {
6638            return null;
6639        }
6640        synchronized (mPackages) {
6641            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6642                    packageName, userId);
6643        }
6644    }
6645
6646    @Override
6647    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6648        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6649            return true;
6650        }
6651
6652        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6653                true /* requireFullPermission */, true /* checkShell */,
6654                "setCookie");
6655        if (!isCallerSameApp(packageName)) {
6656            return false;
6657        }
6658        synchronized (mPackages) {
6659            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6660                    packageName, cookie, userId);
6661        }
6662    }
6663
6664    @Override
6665    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6666        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6667            return null;
6668        }
6669
6670        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6671                "getEphemeralApplicationIcon");
6672        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6673                true /* requireFullPermission */, false /* checkShell */,
6674                "getEphemeralApplicationIcon");
6675        synchronized (mPackages) {
6676            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6677                    packageName, userId);
6678        }
6679    }
6680
6681    private boolean isCallerSameApp(String packageName) {
6682        PackageParser.Package pkg = mPackages.get(packageName);
6683        return pkg != null
6684                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6685    }
6686
6687    @Override
6688    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6689        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6690    }
6691
6692    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6693        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6694
6695        // reader
6696        synchronized (mPackages) {
6697            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6698            final int userId = UserHandle.getCallingUserId();
6699            while (i.hasNext()) {
6700                final PackageParser.Package p = i.next();
6701                if (p.applicationInfo == null) continue;
6702
6703                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6704                        && !p.applicationInfo.isDirectBootAware();
6705                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6706                        && p.applicationInfo.isDirectBootAware();
6707
6708                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6709                        && (!mSafeMode || isSystemApp(p))
6710                        && (matchesUnaware || matchesAware)) {
6711                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6712                    if (ps != null) {
6713                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6714                                ps.readUserState(userId), userId);
6715                        if (ai != null) {
6716                            finalList.add(ai);
6717                        }
6718                    }
6719                }
6720            }
6721        }
6722
6723        return finalList;
6724    }
6725
6726    @Override
6727    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6728        if (!sUserManager.exists(userId)) return null;
6729        flags = updateFlagsForComponent(flags, userId, name);
6730        // reader
6731        synchronized (mPackages) {
6732            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6733            PackageSetting ps = provider != null
6734                    ? mSettings.mPackages.get(provider.owner.packageName)
6735                    : null;
6736            return ps != null
6737                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6738                    ? PackageParser.generateProviderInfo(provider, flags,
6739                            ps.readUserState(userId), userId)
6740                    : null;
6741        }
6742    }
6743
6744    /**
6745     * @deprecated
6746     */
6747    @Deprecated
6748    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6749        // reader
6750        synchronized (mPackages) {
6751            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6752                    .entrySet().iterator();
6753            final int userId = UserHandle.getCallingUserId();
6754            while (i.hasNext()) {
6755                Map.Entry<String, PackageParser.Provider> entry = i.next();
6756                PackageParser.Provider p = entry.getValue();
6757                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6758
6759                if (ps != null && p.syncable
6760                        && (!mSafeMode || (p.info.applicationInfo.flags
6761                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6762                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6763                            ps.readUserState(userId), userId);
6764                    if (info != null) {
6765                        outNames.add(entry.getKey());
6766                        outInfo.add(info);
6767                    }
6768                }
6769            }
6770        }
6771    }
6772
6773    @Override
6774    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6775            int uid, int flags) {
6776        final int userId = processName != null ? UserHandle.getUserId(uid)
6777                : UserHandle.getCallingUserId();
6778        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6779        flags = updateFlagsForComponent(flags, userId, processName);
6780
6781        ArrayList<ProviderInfo> finalList = null;
6782        // reader
6783        synchronized (mPackages) {
6784            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6785            while (i.hasNext()) {
6786                final PackageParser.Provider p = i.next();
6787                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6788                if (ps != null && p.info.authority != null
6789                        && (processName == null
6790                                || (p.info.processName.equals(processName)
6791                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6792                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6793                    if (finalList == null) {
6794                        finalList = new ArrayList<ProviderInfo>(3);
6795                    }
6796                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6797                            ps.readUserState(userId), userId);
6798                    if (info != null) {
6799                        finalList.add(info);
6800                    }
6801                }
6802            }
6803        }
6804
6805        if (finalList != null) {
6806            Collections.sort(finalList, mProviderInitOrderSorter);
6807            return new ParceledListSlice<ProviderInfo>(finalList);
6808        }
6809
6810        return ParceledListSlice.emptyList();
6811    }
6812
6813    @Override
6814    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6815        // reader
6816        synchronized (mPackages) {
6817            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6818            return PackageParser.generateInstrumentationInfo(i, flags);
6819        }
6820    }
6821
6822    @Override
6823    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6824            String targetPackage, int flags) {
6825        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6826    }
6827
6828    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6829            int flags) {
6830        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6831
6832        // reader
6833        synchronized (mPackages) {
6834            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6835            while (i.hasNext()) {
6836                final PackageParser.Instrumentation p = i.next();
6837                if (targetPackage == null
6838                        || targetPackage.equals(p.info.targetPackage)) {
6839                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6840                            flags);
6841                    if (ii != null) {
6842                        finalList.add(ii);
6843                    }
6844                }
6845            }
6846        }
6847
6848        return finalList;
6849    }
6850
6851    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6852        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6853        if (overlays == null) {
6854            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6855            return;
6856        }
6857        for (PackageParser.Package opkg : overlays.values()) {
6858            // Not much to do if idmap fails: we already logged the error
6859            // and we certainly don't want to abort installation of pkg simply
6860            // because an overlay didn't fit properly. For these reasons,
6861            // ignore the return value of createIdmapForPackagePairLI.
6862            createIdmapForPackagePairLI(pkg, opkg);
6863        }
6864    }
6865
6866    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6867            PackageParser.Package opkg) {
6868        if (!opkg.mTrustedOverlay) {
6869            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6870                    opkg.baseCodePath + ": overlay not trusted");
6871            return false;
6872        }
6873        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6874        if (overlaySet == null) {
6875            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6876                    opkg.baseCodePath + " but target package has no known overlays");
6877            return false;
6878        }
6879        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6880        // TODO: generate idmap for split APKs
6881        try {
6882            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6883        } catch (InstallerException e) {
6884            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6885                    + opkg.baseCodePath);
6886            return false;
6887        }
6888        PackageParser.Package[] overlayArray =
6889            overlaySet.values().toArray(new PackageParser.Package[0]);
6890        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6891            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6892                return p1.mOverlayPriority - p2.mOverlayPriority;
6893            }
6894        };
6895        Arrays.sort(overlayArray, cmp);
6896
6897        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6898        int i = 0;
6899        for (PackageParser.Package p : overlayArray) {
6900            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6901        }
6902        return true;
6903    }
6904
6905    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6906        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6907        try {
6908            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6909        } finally {
6910            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6911        }
6912    }
6913
6914    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6915        final File[] files = dir.listFiles();
6916        if (ArrayUtils.isEmpty(files)) {
6917            Log.d(TAG, "No files in app dir " + dir);
6918            return;
6919        }
6920
6921        if (DEBUG_PACKAGE_SCANNING) {
6922            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6923                    + " flags=0x" + Integer.toHexString(parseFlags));
6924        }
6925        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
6926                mSeparateProcesses, mOnlyCore, mMetrics);
6927
6928        // Submit files for parsing in parallel
6929        int fileCount = 0;
6930        for (File file : files) {
6931            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6932                    && !PackageInstallerService.isStageName(file.getName());
6933            if (!isPackage) {
6934                // Ignore entries which are not packages
6935                continue;
6936            }
6937            parallelPackageParser.submit(file, parseFlags);
6938            fileCount++;
6939        }
6940
6941        // Process results one by one
6942        for (; fileCount > 0; fileCount--) {
6943            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
6944            Throwable throwable = parseResult.throwable;
6945            int errorCode = PackageManager.INSTALL_SUCCEEDED;
6946
6947            if (throwable == null) {
6948                try {
6949                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
6950                            currentTime, null);
6951                } catch (PackageManagerException e) {
6952                    errorCode = e.error;
6953                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
6954                }
6955            } else if (throwable instanceof PackageParser.PackageParserException) {
6956                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
6957                        throwable;
6958                errorCode = e.error;
6959                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
6960            } else {
6961                throw new IllegalStateException("Unexpected exception occurred while parsing "
6962                        + parseResult.scanFile, throwable);
6963            }
6964
6965            // Delete invalid userdata apps
6966            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6967                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
6968                logCriticalInfo(Log.WARN,
6969                        "Deleting invalid package at " + parseResult.scanFile);
6970                removeCodePathLI(parseResult.scanFile);
6971            }
6972        }
6973        parallelPackageParser.close();
6974    }
6975
6976    private static File getSettingsProblemFile() {
6977        File dataDir = Environment.getDataDirectory();
6978        File systemDir = new File(dataDir, "system");
6979        File fname = new File(systemDir, "uiderrors.txt");
6980        return fname;
6981    }
6982
6983    static void reportSettingsProblem(int priority, String msg) {
6984        logCriticalInfo(priority, msg);
6985    }
6986
6987    static void logCriticalInfo(int priority, String msg) {
6988        Slog.println(priority, TAG, msg);
6989        EventLogTags.writePmCriticalInfo(msg);
6990        try {
6991            File fname = getSettingsProblemFile();
6992            FileOutputStream out = new FileOutputStream(fname, true);
6993            PrintWriter pw = new FastPrintWriter(out);
6994            SimpleDateFormat formatter = new SimpleDateFormat();
6995            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6996            pw.println(dateString + ": " + msg);
6997            pw.close();
6998            FileUtils.setPermissions(
6999                    fname.toString(),
7000                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7001                    -1, -1);
7002        } catch (java.io.IOException e) {
7003        }
7004    }
7005
7006    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7007        if (srcFile.isDirectory()) {
7008            final File baseFile = new File(pkg.baseCodePath);
7009            long maxModifiedTime = baseFile.lastModified();
7010            if (pkg.splitCodePaths != null) {
7011                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7012                    final File splitFile = new File(pkg.splitCodePaths[i]);
7013                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7014                }
7015            }
7016            return maxModifiedTime;
7017        }
7018        return srcFile.lastModified();
7019    }
7020
7021    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7022            final int policyFlags) throws PackageManagerException {
7023        // When upgrading from pre-N MR1, verify the package time stamp using the package
7024        // directory and not the APK file.
7025        final long lastModifiedTime = mIsPreNMR1Upgrade
7026                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7027        if (ps != null
7028                && ps.codePath.equals(srcFile)
7029                && ps.timeStamp == lastModifiedTime
7030                && !isCompatSignatureUpdateNeeded(pkg)
7031                && !isRecoverSignatureUpdateNeeded(pkg)) {
7032            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7033            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7034            ArraySet<PublicKey> signingKs;
7035            synchronized (mPackages) {
7036                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7037            }
7038            if (ps.signatures.mSignatures != null
7039                    && ps.signatures.mSignatures.length != 0
7040                    && signingKs != null) {
7041                // Optimization: reuse the existing cached certificates
7042                // if the package appears to be unchanged.
7043                pkg.mSignatures = ps.signatures.mSignatures;
7044                pkg.mSigningKeys = signingKs;
7045                return;
7046            }
7047
7048            Slog.w(TAG, "PackageSetting for " + ps.name
7049                    + " is missing signatures.  Collecting certs again to recover them.");
7050        } else {
7051            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7052        }
7053
7054        try {
7055            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7056            PackageParser.collectCertificates(pkg, policyFlags);
7057        } catch (PackageParserException e) {
7058            throw PackageManagerException.from(e);
7059        } finally {
7060            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7061        }
7062    }
7063
7064    /**
7065     *  Traces a package scan.
7066     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7067     */
7068    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7069            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7070        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7071        try {
7072            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7073        } finally {
7074            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7075        }
7076    }
7077
7078    /**
7079     *  Scans a package and returns the newly parsed package.
7080     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7081     */
7082    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7083            long currentTime, UserHandle user) throws PackageManagerException {
7084        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7085        PackageParser pp = new PackageParser();
7086        pp.setSeparateProcesses(mSeparateProcesses);
7087        pp.setOnlyCoreApps(mOnlyCore);
7088        pp.setDisplayMetrics(mMetrics);
7089
7090        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7091            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7092        }
7093
7094        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7095        final PackageParser.Package pkg;
7096        try {
7097            pkg = pp.parsePackage(scanFile, parseFlags);
7098        } catch (PackageParserException e) {
7099            throw PackageManagerException.from(e);
7100        } finally {
7101            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7102        }
7103
7104        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7105    }
7106
7107    /**
7108     *  Scans a package and returns the newly parsed package.
7109     *  @throws PackageManagerException on a parse error.
7110     */
7111    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7112            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7113            throws PackageManagerException {
7114        // If the package has children and this is the first dive in the function
7115        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7116        // packages (parent and children) would be successfully scanned before the
7117        // actual scan since scanning mutates internal state and we want to atomically
7118        // install the package and its children.
7119        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7120            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7121                scanFlags |= SCAN_CHECK_ONLY;
7122            }
7123        } else {
7124            scanFlags &= ~SCAN_CHECK_ONLY;
7125        }
7126
7127        // Scan the parent
7128        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7129                scanFlags, currentTime, user);
7130
7131        // Scan the children
7132        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7133        for (int i = 0; i < childCount; i++) {
7134            PackageParser.Package childPackage = pkg.childPackages.get(i);
7135            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7136                    currentTime, user);
7137        }
7138
7139
7140        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7141            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7142        }
7143
7144        return scannedPkg;
7145    }
7146
7147    /**
7148     *  Scans a package and returns the newly parsed package.
7149     *  @throws PackageManagerException on a parse error.
7150     */
7151    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7152            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7153            throws PackageManagerException {
7154        PackageSetting ps = null;
7155        PackageSetting updatedPkg;
7156        // reader
7157        synchronized (mPackages) {
7158            // Look to see if we already know about this package.
7159            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7160            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7161                // This package has been renamed to its original name.  Let's
7162                // use that.
7163                ps = mSettings.getPackageLPr(oldName);
7164            }
7165            // If there was no original package, see one for the real package name.
7166            if (ps == null) {
7167                ps = mSettings.getPackageLPr(pkg.packageName);
7168            }
7169            // Check to see if this package could be hiding/updating a system
7170            // package.  Must look for it either under the original or real
7171            // package name depending on our state.
7172            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7173            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7174
7175            // If this is a package we don't know about on the system partition, we
7176            // may need to remove disabled child packages on the system partition
7177            // or may need to not add child packages if the parent apk is updated
7178            // on the data partition and no longer defines this child package.
7179            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7180                // If this is a parent package for an updated system app and this system
7181                // app got an OTA update which no longer defines some of the child packages
7182                // we have to prune them from the disabled system packages.
7183                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7184                if (disabledPs != null) {
7185                    final int scannedChildCount = (pkg.childPackages != null)
7186                            ? pkg.childPackages.size() : 0;
7187                    final int disabledChildCount = disabledPs.childPackageNames != null
7188                            ? disabledPs.childPackageNames.size() : 0;
7189                    for (int i = 0; i < disabledChildCount; i++) {
7190                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7191                        boolean disabledPackageAvailable = false;
7192                        for (int j = 0; j < scannedChildCount; j++) {
7193                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7194                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7195                                disabledPackageAvailable = true;
7196                                break;
7197                            }
7198                         }
7199                         if (!disabledPackageAvailable) {
7200                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7201                         }
7202                    }
7203                }
7204            }
7205        }
7206
7207        boolean updatedPkgBetter = false;
7208        // First check if this is a system package that may involve an update
7209        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7210            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7211            // it needs to drop FLAG_PRIVILEGED.
7212            if (locationIsPrivileged(scanFile)) {
7213                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7214            } else {
7215                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7216            }
7217
7218            if (ps != null && !ps.codePath.equals(scanFile)) {
7219                // The path has changed from what was last scanned...  check the
7220                // version of the new path against what we have stored to determine
7221                // what to do.
7222                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7223                if (pkg.mVersionCode <= ps.versionCode) {
7224                    // The system package has been updated and the code path does not match
7225                    // Ignore entry. Skip it.
7226                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7227                            + " ignored: updated version " + ps.versionCode
7228                            + " better than this " + pkg.mVersionCode);
7229                    if (!updatedPkg.codePath.equals(scanFile)) {
7230                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7231                                + ps.name + " changing from " + updatedPkg.codePathString
7232                                + " to " + scanFile);
7233                        updatedPkg.codePath = scanFile;
7234                        updatedPkg.codePathString = scanFile.toString();
7235                        updatedPkg.resourcePath = scanFile;
7236                        updatedPkg.resourcePathString = scanFile.toString();
7237                    }
7238                    updatedPkg.pkg = pkg;
7239                    updatedPkg.versionCode = pkg.mVersionCode;
7240
7241                    // Update the disabled system child packages to point to the package too.
7242                    final int childCount = updatedPkg.childPackageNames != null
7243                            ? updatedPkg.childPackageNames.size() : 0;
7244                    for (int i = 0; i < childCount; i++) {
7245                        String childPackageName = updatedPkg.childPackageNames.get(i);
7246                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7247                                childPackageName);
7248                        if (updatedChildPkg != null) {
7249                            updatedChildPkg.pkg = pkg;
7250                            updatedChildPkg.versionCode = pkg.mVersionCode;
7251                        }
7252                    }
7253
7254                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7255                            + scanFile + " ignored: updated version " + ps.versionCode
7256                            + " better than this " + pkg.mVersionCode);
7257                } else {
7258                    // The current app on the system partition is better than
7259                    // what we have updated to on the data partition; switch
7260                    // back to the system partition version.
7261                    // At this point, its safely assumed that package installation for
7262                    // apps in system partition will go through. If not there won't be a working
7263                    // version of the app
7264                    // writer
7265                    synchronized (mPackages) {
7266                        // Just remove the loaded entries from package lists.
7267                        mPackages.remove(ps.name);
7268                    }
7269
7270                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7271                            + " reverting from " + ps.codePathString
7272                            + ": new version " + pkg.mVersionCode
7273                            + " better than installed " + ps.versionCode);
7274
7275                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7276                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7277                    synchronized (mInstallLock) {
7278                        args.cleanUpResourcesLI();
7279                    }
7280                    synchronized (mPackages) {
7281                        mSettings.enableSystemPackageLPw(ps.name);
7282                    }
7283                    updatedPkgBetter = true;
7284                }
7285            }
7286        }
7287
7288        if (updatedPkg != null) {
7289            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7290            // initially
7291            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7292
7293            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7294            // flag set initially
7295            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7296                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7297            }
7298        }
7299
7300        // Verify certificates against what was last scanned
7301        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7302
7303        /*
7304         * A new system app appeared, but we already had a non-system one of the
7305         * same name installed earlier.
7306         */
7307        boolean shouldHideSystemApp = false;
7308        if (updatedPkg == null && ps != null
7309                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7310            /*
7311             * Check to make sure the signatures match first. If they don't,
7312             * wipe the installed application and its data.
7313             */
7314            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7315                    != PackageManager.SIGNATURE_MATCH) {
7316                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7317                        + " signatures don't match existing userdata copy; removing");
7318                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7319                        "scanPackageInternalLI")) {
7320                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7321                }
7322                ps = null;
7323            } else {
7324                /*
7325                 * If the newly-added system app is an older version than the
7326                 * already installed version, hide it. It will be scanned later
7327                 * and re-added like an update.
7328                 */
7329                if (pkg.mVersionCode <= ps.versionCode) {
7330                    shouldHideSystemApp = true;
7331                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7332                            + " but new version " + pkg.mVersionCode + " better than installed "
7333                            + ps.versionCode + "; hiding system");
7334                } else {
7335                    /*
7336                     * The newly found system app is a newer version that the
7337                     * one previously installed. Simply remove the
7338                     * already-installed application and replace it with our own
7339                     * while keeping the application data.
7340                     */
7341                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7342                            + " reverting from " + ps.codePathString + ": new version "
7343                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7344                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7345                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7346                    synchronized (mInstallLock) {
7347                        args.cleanUpResourcesLI();
7348                    }
7349                }
7350            }
7351        }
7352
7353        // The apk is forward locked (not public) if its code and resources
7354        // are kept in different files. (except for app in either system or
7355        // vendor path).
7356        // TODO grab this value from PackageSettings
7357        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7358            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7359                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7360            }
7361        }
7362
7363        // TODO: extend to support forward-locked splits
7364        String resourcePath = null;
7365        String baseResourcePath = null;
7366        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7367            if (ps != null && ps.resourcePathString != null) {
7368                resourcePath = ps.resourcePathString;
7369                baseResourcePath = ps.resourcePathString;
7370            } else {
7371                // Should not happen at all. Just log an error.
7372                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7373            }
7374        } else {
7375            resourcePath = pkg.codePath;
7376            baseResourcePath = pkg.baseCodePath;
7377        }
7378
7379        // Set application objects path explicitly.
7380        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7381        pkg.setApplicationInfoCodePath(pkg.codePath);
7382        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7383        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7384        pkg.setApplicationInfoResourcePath(resourcePath);
7385        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7386        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7387
7388        // Note that we invoke the following method only if we are about to unpack an application
7389        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7390                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7391
7392        /*
7393         * If the system app should be overridden by a previously installed
7394         * data, hide the system app now and let the /data/app scan pick it up
7395         * again.
7396         */
7397        if (shouldHideSystemApp) {
7398            synchronized (mPackages) {
7399                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7400            }
7401        }
7402
7403        return scannedPkg;
7404    }
7405
7406    private static String fixProcessName(String defProcessName,
7407            String processName) {
7408        if (processName == null) {
7409            return defProcessName;
7410        }
7411        return processName;
7412    }
7413
7414    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7415            throws PackageManagerException {
7416        if (pkgSetting.signatures.mSignatures != null) {
7417            // Already existing package. Make sure signatures match
7418            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7419                    == PackageManager.SIGNATURE_MATCH;
7420            if (!match) {
7421                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7422                        == PackageManager.SIGNATURE_MATCH;
7423            }
7424            if (!match) {
7425                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7426                        == PackageManager.SIGNATURE_MATCH;
7427            }
7428            if (!match) {
7429                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7430                        + pkg.packageName + " signatures do not match the "
7431                        + "previously installed version; ignoring!");
7432            }
7433        }
7434
7435        // Check for shared user signatures
7436        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7437            // Already existing package. Make sure signatures match
7438            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7439                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7440            if (!match) {
7441                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7442                        == PackageManager.SIGNATURE_MATCH;
7443            }
7444            if (!match) {
7445                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7446                        == PackageManager.SIGNATURE_MATCH;
7447            }
7448            if (!match) {
7449                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7450                        "Package " + pkg.packageName
7451                        + " has no signatures that match those in shared user "
7452                        + pkgSetting.sharedUser.name + "; ignoring!");
7453            }
7454        }
7455    }
7456
7457    /**
7458     * Enforces that only the system UID or root's UID can call a method exposed
7459     * via Binder.
7460     *
7461     * @param message used as message if SecurityException is thrown
7462     * @throws SecurityException if the caller is not system or root
7463     */
7464    private static final void enforceSystemOrRoot(String message) {
7465        final int uid = Binder.getCallingUid();
7466        if (uid != Process.SYSTEM_UID && uid != 0) {
7467            throw new SecurityException(message);
7468        }
7469    }
7470
7471    @Override
7472    public void performFstrimIfNeeded() {
7473        enforceSystemOrRoot("Only the system can request fstrim");
7474
7475        // Before everything else, see whether we need to fstrim.
7476        try {
7477            IStorageManager sm = PackageHelper.getStorageManager();
7478            if (sm != null) {
7479                boolean doTrim = false;
7480                final long interval = android.provider.Settings.Global.getLong(
7481                        mContext.getContentResolver(),
7482                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7483                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7484                if (interval > 0) {
7485                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7486                    if (timeSinceLast > interval) {
7487                        doTrim = true;
7488                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7489                                + "; running immediately");
7490                    }
7491                }
7492                if (doTrim) {
7493                    final boolean dexOptDialogShown;
7494                    synchronized (mPackages) {
7495                        dexOptDialogShown = mDexOptDialogShown;
7496                    }
7497                    if (!isFirstBoot() && dexOptDialogShown) {
7498                        try {
7499                            ActivityManager.getService().showBootMessage(
7500                                    mContext.getResources().getString(
7501                                            R.string.android_upgrading_fstrim), true);
7502                        } catch (RemoteException e) {
7503                        }
7504                    }
7505                    sm.runMaintenance();
7506                }
7507            } else {
7508                Slog.e(TAG, "storageManager service unavailable!");
7509            }
7510        } catch (RemoteException e) {
7511            // Can't happen; StorageManagerService is local
7512        }
7513    }
7514
7515    @Override
7516    public void updatePackagesIfNeeded() {
7517        enforceSystemOrRoot("Only the system can request package update");
7518
7519        // We need to re-extract after an OTA.
7520        boolean causeUpgrade = isUpgrade();
7521
7522        // First boot or factory reset.
7523        // Note: we also handle devices that are upgrading to N right now as if it is their
7524        //       first boot, as they do not have profile data.
7525        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7526
7527        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7528        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7529
7530        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7531            return;
7532        }
7533
7534        List<PackageParser.Package> pkgs;
7535        synchronized (mPackages) {
7536            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7537        }
7538
7539        final long startTime = System.nanoTime();
7540        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7541                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7542
7543        final int elapsedTimeSeconds =
7544                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7545
7546        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7547        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7548        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7549        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7550        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7551    }
7552
7553    /**
7554     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7555     * containing statistics about the invocation. The array consists of three elements,
7556     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7557     * and {@code numberOfPackagesFailed}.
7558     */
7559    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7560            String compilerFilter) {
7561
7562        int numberOfPackagesVisited = 0;
7563        int numberOfPackagesOptimized = 0;
7564        int numberOfPackagesSkipped = 0;
7565        int numberOfPackagesFailed = 0;
7566        final int numberOfPackagesToDexopt = pkgs.size();
7567
7568        for (PackageParser.Package pkg : pkgs) {
7569            numberOfPackagesVisited++;
7570
7571            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7572                if (DEBUG_DEXOPT) {
7573                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7574                }
7575                numberOfPackagesSkipped++;
7576                continue;
7577            }
7578
7579            if (DEBUG_DEXOPT) {
7580                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7581                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7582            }
7583
7584            if (showDialog) {
7585                try {
7586                    ActivityManager.getService().showBootMessage(
7587                            mContext.getResources().getString(R.string.android_upgrading_apk,
7588                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7589                } catch (RemoteException e) {
7590                }
7591                synchronized (mPackages) {
7592                    mDexOptDialogShown = true;
7593                }
7594            }
7595
7596            // If the OTA updates a system app which was previously preopted to a non-preopted state
7597            // the app might end up being verified at runtime. That's because by default the apps
7598            // are verify-profile but for preopted apps there's no profile.
7599            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7600            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7601            // filter (by default interpret-only).
7602            // Note that at this stage unused apps are already filtered.
7603            if (isSystemApp(pkg) &&
7604                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7605                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7606                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7607            }
7608
7609            // If the OTA updates a system app which was previously preopted to a non-preopted state
7610            // the app might end up being verified at runtime. That's because by default the apps
7611            // are verify-profile but for preopted apps there's no profile.
7612            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7613            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7614            // filter (by default interpret-only).
7615            // Note that at this stage unused apps are already filtered.
7616            if (isSystemApp(pkg) &&
7617                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7618                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7619                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7620            }
7621
7622            // checkProfiles is false to avoid merging profiles during boot which
7623            // might interfere with background compilation (b/28612421).
7624            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7625            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7626            // trade-off worth doing to save boot time work.
7627            int dexOptStatus = performDexOptTraced(pkg.packageName,
7628                    false /* checkProfiles */,
7629                    compilerFilter,
7630                    false /* force */);
7631            switch (dexOptStatus) {
7632                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7633                    numberOfPackagesOptimized++;
7634                    break;
7635                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7636                    numberOfPackagesSkipped++;
7637                    break;
7638                case PackageDexOptimizer.DEX_OPT_FAILED:
7639                    numberOfPackagesFailed++;
7640                    break;
7641                default:
7642                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7643                    break;
7644            }
7645        }
7646
7647        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7648                numberOfPackagesFailed };
7649    }
7650
7651    @Override
7652    public void notifyPackageUse(String packageName, int reason) {
7653        synchronized (mPackages) {
7654            PackageParser.Package p = mPackages.get(packageName);
7655            if (p == null) {
7656                return;
7657            }
7658            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7659        }
7660    }
7661
7662    @Override
7663    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7664        int userId = UserHandle.getCallingUserId();
7665        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7666        if (ai == null) {
7667            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7668                + loadingPackageName + ", user=" + userId);
7669            return;
7670        }
7671        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7672    }
7673
7674    // TODO: this is not used nor needed. Delete it.
7675    @Override
7676    public boolean performDexOptIfNeeded(String packageName) {
7677        int dexOptStatus = performDexOptTraced(packageName,
7678                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7679        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7680    }
7681
7682    @Override
7683    public boolean performDexOpt(String packageName,
7684            boolean checkProfiles, int compileReason, boolean force) {
7685        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7686                getCompilerFilterForReason(compileReason), force);
7687        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7688    }
7689
7690    @Override
7691    public boolean performDexOptMode(String packageName,
7692            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7693        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7694                targetCompilerFilter, force);
7695        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7696    }
7697
7698    private int performDexOptTraced(String packageName,
7699                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7700        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7701        try {
7702            return performDexOptInternal(packageName, checkProfiles,
7703                    targetCompilerFilter, force);
7704        } finally {
7705            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7706        }
7707    }
7708
7709    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7710    // if the package can now be considered up to date for the given filter.
7711    private int performDexOptInternal(String packageName,
7712                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7713        PackageParser.Package p;
7714        synchronized (mPackages) {
7715            p = mPackages.get(packageName);
7716            if (p == null) {
7717                // Package could not be found. Report failure.
7718                return PackageDexOptimizer.DEX_OPT_FAILED;
7719            }
7720            mPackageUsage.maybeWriteAsync(mPackages);
7721            mCompilerStats.maybeWriteAsync();
7722        }
7723        long callingId = Binder.clearCallingIdentity();
7724        try {
7725            synchronized (mInstallLock) {
7726                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7727                        targetCompilerFilter, force);
7728            }
7729        } finally {
7730            Binder.restoreCallingIdentity(callingId);
7731        }
7732    }
7733
7734    public ArraySet<String> getOptimizablePackages() {
7735        ArraySet<String> pkgs = new ArraySet<String>();
7736        synchronized (mPackages) {
7737            for (PackageParser.Package p : mPackages.values()) {
7738                if (PackageDexOptimizer.canOptimizePackage(p)) {
7739                    pkgs.add(p.packageName);
7740                }
7741            }
7742        }
7743        return pkgs;
7744    }
7745
7746    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7747            boolean checkProfiles, String targetCompilerFilter,
7748            boolean force) {
7749        // Select the dex optimizer based on the force parameter.
7750        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7751        //       allocate an object here.
7752        PackageDexOptimizer pdo = force
7753                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7754                : mPackageDexOptimizer;
7755
7756        // Optimize all dependencies first. Note: we ignore the return value and march on
7757        // on errors.
7758        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7759        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7760        if (!deps.isEmpty()) {
7761            for (PackageParser.Package depPackage : deps) {
7762                // TODO: Analyze and investigate if we (should) profile libraries.
7763                // Currently this will do a full compilation of the library by default.
7764                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7765                        false /* checkProfiles */,
7766                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7767                        getOrCreateCompilerPackageStats(depPackage));
7768            }
7769        }
7770        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7771                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7772    }
7773
7774    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7775        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7776            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7777            Set<String> collectedNames = new HashSet<>();
7778            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7779
7780            retValue.remove(p);
7781
7782            return retValue;
7783        } else {
7784            return Collections.emptyList();
7785        }
7786    }
7787
7788    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7789            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7790        if (!collectedNames.contains(p.packageName)) {
7791            collectedNames.add(p.packageName);
7792            collected.add(p);
7793
7794            if (p.usesLibraries != null) {
7795                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7796            }
7797            if (p.usesOptionalLibraries != null) {
7798                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7799                        collectedNames);
7800            }
7801        }
7802    }
7803
7804    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7805            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7806        for (String libName : libs) {
7807            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7808            if (libPkg != null) {
7809                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7810            }
7811        }
7812    }
7813
7814    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7815        synchronized (mPackages) {
7816            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7817            if (lib != null && lib.apk != null) {
7818                return mPackages.get(lib.apk);
7819            }
7820        }
7821        return null;
7822    }
7823
7824    public void shutdown() {
7825        mPackageUsage.writeNow(mPackages);
7826        mCompilerStats.writeNow();
7827    }
7828
7829    @Override
7830    public void dumpProfiles(String packageName) {
7831        PackageParser.Package pkg;
7832        synchronized (mPackages) {
7833            pkg = mPackages.get(packageName);
7834            if (pkg == null) {
7835                throw new IllegalArgumentException("Unknown package: " + packageName);
7836            }
7837        }
7838        /* Only the shell, root, or the app user should be able to dump profiles. */
7839        int callingUid = Binder.getCallingUid();
7840        if (callingUid != Process.SHELL_UID &&
7841            callingUid != Process.ROOT_UID &&
7842            callingUid != pkg.applicationInfo.uid) {
7843            throw new SecurityException("dumpProfiles");
7844        }
7845
7846        synchronized (mInstallLock) {
7847            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7848            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7849            try {
7850                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7851                String codePaths = TextUtils.join(";", allCodePaths);
7852                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7853            } catch (InstallerException e) {
7854                Slog.w(TAG, "Failed to dump profiles", e);
7855            }
7856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7857        }
7858    }
7859
7860    @Override
7861    public void forceDexOpt(String packageName) {
7862        enforceSystemOrRoot("forceDexOpt");
7863
7864        PackageParser.Package pkg;
7865        synchronized (mPackages) {
7866            pkg = mPackages.get(packageName);
7867            if (pkg == null) {
7868                throw new IllegalArgumentException("Unknown package: " + packageName);
7869            }
7870        }
7871
7872        synchronized (mInstallLock) {
7873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7874
7875            // Whoever is calling forceDexOpt wants a fully compiled package.
7876            // Don't use profiles since that may cause compilation to be skipped.
7877            final int res = performDexOptInternalWithDependenciesLI(pkg,
7878                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7879                    true /* force */);
7880
7881            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7882            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7883                throw new IllegalStateException("Failed to dexopt: " + res);
7884            }
7885        }
7886    }
7887
7888    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7889        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7890            Slog.w(TAG, "Unable to update from " + oldPkg.name
7891                    + " to " + newPkg.packageName
7892                    + ": old package not in system partition");
7893            return false;
7894        } else if (mPackages.get(oldPkg.name) != null) {
7895            Slog.w(TAG, "Unable to update from " + oldPkg.name
7896                    + " to " + newPkg.packageName
7897                    + ": old package still exists");
7898            return false;
7899        }
7900        return true;
7901    }
7902
7903    void removeCodePathLI(File codePath) {
7904        if (codePath.isDirectory()) {
7905            try {
7906                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7907            } catch (InstallerException e) {
7908                Slog.w(TAG, "Failed to remove code path", e);
7909            }
7910        } else {
7911            codePath.delete();
7912        }
7913    }
7914
7915    private int[] resolveUserIds(int userId) {
7916        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7917    }
7918
7919    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7920        if (pkg == null) {
7921            Slog.wtf(TAG, "Package was null!", new Throwable());
7922            return;
7923        }
7924        clearAppDataLeafLIF(pkg, userId, flags);
7925        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7926        for (int i = 0; i < childCount; i++) {
7927            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7928        }
7929    }
7930
7931    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7932        final PackageSetting ps;
7933        synchronized (mPackages) {
7934            ps = mSettings.mPackages.get(pkg.packageName);
7935        }
7936        for (int realUserId : resolveUserIds(userId)) {
7937            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7938            try {
7939                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7940                        ceDataInode);
7941            } catch (InstallerException e) {
7942                Slog.w(TAG, String.valueOf(e));
7943            }
7944        }
7945    }
7946
7947    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7948        if (pkg == null) {
7949            Slog.wtf(TAG, "Package was null!", new Throwable());
7950            return;
7951        }
7952        destroyAppDataLeafLIF(pkg, userId, flags);
7953        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7954        for (int i = 0; i < childCount; i++) {
7955            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7956        }
7957    }
7958
7959    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7960        final PackageSetting ps;
7961        synchronized (mPackages) {
7962            ps = mSettings.mPackages.get(pkg.packageName);
7963        }
7964        for (int realUserId : resolveUserIds(userId)) {
7965            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7966            try {
7967                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7968                        ceDataInode);
7969            } catch (InstallerException e) {
7970                Slog.w(TAG, String.valueOf(e));
7971            }
7972        }
7973    }
7974
7975    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7976        if (pkg == null) {
7977            Slog.wtf(TAG, "Package was null!", new Throwable());
7978            return;
7979        }
7980        destroyAppProfilesLeafLIF(pkg);
7981        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7982        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7983        for (int i = 0; i < childCount; i++) {
7984            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7985            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7986                    true /* removeBaseMarker */);
7987        }
7988    }
7989
7990    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7991            boolean removeBaseMarker) {
7992        if (pkg.isForwardLocked()) {
7993            return;
7994        }
7995
7996        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7997            try {
7998                path = PackageManagerServiceUtils.realpath(new File(path));
7999            } catch (IOException e) {
8000                // TODO: Should we return early here ?
8001                Slog.w(TAG, "Failed to get canonical path", e);
8002                continue;
8003            }
8004
8005            final String useMarker = path.replace('/', '@');
8006            for (int realUserId : resolveUserIds(userId)) {
8007                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8008                if (removeBaseMarker) {
8009                    File foreignUseMark = new File(profileDir, useMarker);
8010                    if (foreignUseMark.exists()) {
8011                        if (!foreignUseMark.delete()) {
8012                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8013                                    + pkg.packageName);
8014                        }
8015                    }
8016                }
8017
8018                File[] markers = profileDir.listFiles();
8019                if (markers != null) {
8020                    final String searchString = "@" + pkg.packageName + "@";
8021                    // We also delete all markers that contain the package name we're
8022                    // uninstalling. These are associated with secondary dex-files belonging
8023                    // to the package. Reconstructing the path of these dex files is messy
8024                    // in general.
8025                    for (File marker : markers) {
8026                        if (marker.getName().indexOf(searchString) > 0) {
8027                            if (!marker.delete()) {
8028                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8029                                    + pkg.packageName);
8030                            }
8031                        }
8032                    }
8033                }
8034            }
8035        }
8036    }
8037
8038    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8039        try {
8040            mInstaller.destroyAppProfiles(pkg.packageName);
8041        } catch (InstallerException e) {
8042            Slog.w(TAG, String.valueOf(e));
8043        }
8044    }
8045
8046    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8047        if (pkg == null) {
8048            Slog.wtf(TAG, "Package was null!", new Throwable());
8049            return;
8050        }
8051        clearAppProfilesLeafLIF(pkg);
8052        // We don't remove the base foreign use marker when clearing profiles because
8053        // we will rename it when the app is updated. Unlike the actual profile contents,
8054        // the foreign use marker is good across installs.
8055        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8056        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8057        for (int i = 0; i < childCount; i++) {
8058            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8059        }
8060    }
8061
8062    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8063        try {
8064            mInstaller.clearAppProfiles(pkg.packageName);
8065        } catch (InstallerException e) {
8066            Slog.w(TAG, String.valueOf(e));
8067        }
8068    }
8069
8070    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8071            long lastUpdateTime) {
8072        // Set parent install/update time
8073        PackageSetting ps = (PackageSetting) pkg.mExtras;
8074        if (ps != null) {
8075            ps.firstInstallTime = firstInstallTime;
8076            ps.lastUpdateTime = lastUpdateTime;
8077        }
8078        // Set children install/update time
8079        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8080        for (int i = 0; i < childCount; i++) {
8081            PackageParser.Package childPkg = pkg.childPackages.get(i);
8082            ps = (PackageSetting) childPkg.mExtras;
8083            if (ps != null) {
8084                ps.firstInstallTime = firstInstallTime;
8085                ps.lastUpdateTime = lastUpdateTime;
8086            }
8087        }
8088    }
8089
8090    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8091            PackageParser.Package changingLib) {
8092        if (file.path != null) {
8093            usesLibraryFiles.add(file.path);
8094            return;
8095        }
8096        PackageParser.Package p = mPackages.get(file.apk);
8097        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8098            // If we are doing this while in the middle of updating a library apk,
8099            // then we need to make sure to use that new apk for determining the
8100            // dependencies here.  (We haven't yet finished committing the new apk
8101            // to the package manager state.)
8102            if (p == null || p.packageName.equals(changingLib.packageName)) {
8103                p = changingLib;
8104            }
8105        }
8106        if (p != null) {
8107            usesLibraryFiles.addAll(p.getAllCodePaths());
8108        }
8109    }
8110
8111    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8112            PackageParser.Package changingLib) throws PackageManagerException {
8113        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8114            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8115            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8116            for (int i=0; i<N; i++) {
8117                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8118                if (file == null) {
8119                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8120                            "Package " + pkg.packageName + " requires unavailable shared library "
8121                            + pkg.usesLibraries.get(i) + "; failing!");
8122                }
8123                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8124            }
8125            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8126            for (int i=0; i<N; i++) {
8127                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8128                if (file == null) {
8129                    Slog.w(TAG, "Package " + pkg.packageName
8130                            + " desires unavailable shared library "
8131                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8132                } else {
8133                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8134                }
8135            }
8136            N = usesLibraryFiles.size();
8137            if (N > 0) {
8138                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8139            } else {
8140                pkg.usesLibraryFiles = null;
8141            }
8142        }
8143    }
8144
8145    private static boolean hasString(List<String> list, List<String> which) {
8146        if (list == null) {
8147            return false;
8148        }
8149        for (int i=list.size()-1; i>=0; i--) {
8150            for (int j=which.size()-1; j>=0; j--) {
8151                if (which.get(j).equals(list.get(i))) {
8152                    return true;
8153                }
8154            }
8155        }
8156        return false;
8157    }
8158
8159    private void updateAllSharedLibrariesLPw() {
8160        for (PackageParser.Package pkg : mPackages.values()) {
8161            try {
8162                updateSharedLibrariesLPr(pkg, null);
8163            } catch (PackageManagerException e) {
8164                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8165            }
8166        }
8167    }
8168
8169    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8170            PackageParser.Package changingPkg) {
8171        ArrayList<PackageParser.Package> res = null;
8172        for (PackageParser.Package pkg : mPackages.values()) {
8173            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8174                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8175                if (res == null) {
8176                    res = new ArrayList<PackageParser.Package>();
8177                }
8178                res.add(pkg);
8179                try {
8180                    updateSharedLibrariesLPr(pkg, changingPkg);
8181                } catch (PackageManagerException e) {
8182                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8183                }
8184            }
8185        }
8186        return res;
8187    }
8188
8189    /**
8190     * Derive the value of the {@code cpuAbiOverride} based on the provided
8191     * value and an optional stored value from the package settings.
8192     */
8193    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8194        String cpuAbiOverride = null;
8195
8196        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8197            cpuAbiOverride = null;
8198        } else if (abiOverride != null) {
8199            cpuAbiOverride = abiOverride;
8200        } else if (settings != null) {
8201            cpuAbiOverride = settings.cpuAbiOverrideString;
8202        }
8203
8204        return cpuAbiOverride;
8205    }
8206
8207    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8208            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8209                    throws PackageManagerException {
8210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8211        // If the package has children and this is the first dive in the function
8212        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8213        // whether all packages (parent and children) would be successfully scanned
8214        // before the actual scan since scanning mutates internal state and we want
8215        // to atomically install the package and its children.
8216        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8217            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8218                scanFlags |= SCAN_CHECK_ONLY;
8219            }
8220        } else {
8221            scanFlags &= ~SCAN_CHECK_ONLY;
8222        }
8223
8224        final PackageParser.Package scannedPkg;
8225        try {
8226            // Scan the parent
8227            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8228            // Scan the children
8229            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8230            for (int i = 0; i < childCount; i++) {
8231                PackageParser.Package childPkg = pkg.childPackages.get(i);
8232                scanPackageLI(childPkg, policyFlags,
8233                        scanFlags, currentTime, user);
8234            }
8235        } finally {
8236            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8237        }
8238
8239        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8240            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8241        }
8242
8243        return scannedPkg;
8244    }
8245
8246    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8247            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8248        boolean success = false;
8249        try {
8250            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8251                    currentTime, user);
8252            success = true;
8253            return res;
8254        } finally {
8255            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8256                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8257                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8258                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8259                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8260            }
8261        }
8262    }
8263
8264    /**
8265     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8266     */
8267    private static boolean apkHasCode(String fileName) {
8268        StrictJarFile jarFile = null;
8269        try {
8270            jarFile = new StrictJarFile(fileName,
8271                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8272            return jarFile.findEntry("classes.dex") != null;
8273        } catch (IOException ignore) {
8274        } finally {
8275            try {
8276                if (jarFile != null) {
8277                    jarFile.close();
8278                }
8279            } catch (IOException ignore) {}
8280        }
8281        return false;
8282    }
8283
8284    /**
8285     * Enforces code policy for the package. This ensures that if an APK has
8286     * declared hasCode="true" in its manifest that the APK actually contains
8287     * code.
8288     *
8289     * @throws PackageManagerException If bytecode could not be found when it should exist
8290     */
8291    private static void assertCodePolicy(PackageParser.Package pkg)
8292            throws PackageManagerException {
8293        final boolean shouldHaveCode =
8294                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8295        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8296            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8297                    "Package " + pkg.baseCodePath + " code is missing");
8298        }
8299
8300        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8301            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8302                final boolean splitShouldHaveCode =
8303                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8304                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8305                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8306                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8307                }
8308            }
8309        }
8310    }
8311
8312    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8313            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8314                    throws PackageManagerException {
8315        if (DEBUG_PACKAGE_SCANNING) {
8316            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8317                Log.d(TAG, "Scanning package " + pkg.packageName);
8318        }
8319
8320        applyPolicy(pkg, policyFlags);
8321
8322        assertPackageIsValid(pkg, policyFlags, scanFlags);
8323
8324        // Initialize package source and resource directories
8325        final File scanFile = new File(pkg.codePath);
8326        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8327        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8328
8329        SharedUserSetting suid = null;
8330        PackageSetting pkgSetting = null;
8331
8332        // Getting the package setting may have a side-effect, so if we
8333        // are only checking if scan would succeed, stash a copy of the
8334        // old setting to restore at the end.
8335        PackageSetting nonMutatedPs = null;
8336
8337        // We keep references to the derived CPU Abis from settings in oder to reuse
8338        // them in the case where we're not upgrading or booting for the first time.
8339        String primaryCpuAbiFromSettings = null;
8340        String secondaryCpuAbiFromSettings = null;
8341
8342        // writer
8343        synchronized (mPackages) {
8344            if (pkg.mSharedUserId != null) {
8345                // SIDE EFFECTS; may potentially allocate a new shared user
8346                suid = mSettings.getSharedUserLPw(
8347                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8348                if (DEBUG_PACKAGE_SCANNING) {
8349                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8350                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8351                                + "): packages=" + suid.packages);
8352                }
8353            }
8354
8355            // Check if we are renaming from an original package name.
8356            PackageSetting origPackage = null;
8357            String realName = null;
8358            if (pkg.mOriginalPackages != null) {
8359                // This package may need to be renamed to a previously
8360                // installed name.  Let's check on that...
8361                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8362                if (pkg.mOriginalPackages.contains(renamed)) {
8363                    // This package had originally been installed as the
8364                    // original name, and we have already taken care of
8365                    // transitioning to the new one.  Just update the new
8366                    // one to continue using the old name.
8367                    realName = pkg.mRealPackage;
8368                    if (!pkg.packageName.equals(renamed)) {
8369                        // Callers into this function may have already taken
8370                        // care of renaming the package; only do it here if
8371                        // it is not already done.
8372                        pkg.setPackageName(renamed);
8373                    }
8374                } else {
8375                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8376                        if ((origPackage = mSettings.getPackageLPr(
8377                                pkg.mOriginalPackages.get(i))) != null) {
8378                            // We do have the package already installed under its
8379                            // original name...  should we use it?
8380                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8381                                // New package is not compatible with original.
8382                                origPackage = null;
8383                                continue;
8384                            } else if (origPackage.sharedUser != null) {
8385                                // Make sure uid is compatible between packages.
8386                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8387                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8388                                            + " to " + pkg.packageName + ": old uid "
8389                                            + origPackage.sharedUser.name
8390                                            + " differs from " + pkg.mSharedUserId);
8391                                    origPackage = null;
8392                                    continue;
8393                                }
8394                                // TODO: Add case when shared user id is added [b/28144775]
8395                            } else {
8396                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8397                                        + pkg.packageName + " to old name " + origPackage.name);
8398                            }
8399                            break;
8400                        }
8401                    }
8402                }
8403            }
8404
8405            if (mTransferedPackages.contains(pkg.packageName)) {
8406                Slog.w(TAG, "Package " + pkg.packageName
8407                        + " was transferred to another, but its .apk remains");
8408            }
8409
8410            // See comments in nonMutatedPs declaration
8411            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8412                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8413                if (foundPs != null) {
8414                    nonMutatedPs = new PackageSetting(foundPs);
8415                }
8416            }
8417
8418            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8419                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8420                if (foundPs != null) {
8421                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8422                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8423                }
8424            }
8425
8426            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8427            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8428                PackageManagerService.reportSettingsProblem(Log.WARN,
8429                        "Package " + pkg.packageName + " shared user changed from "
8430                                + (pkgSetting.sharedUser != null
8431                                        ? pkgSetting.sharedUser.name : "<nothing>")
8432                                + " to "
8433                                + (suid != null ? suid.name : "<nothing>")
8434                                + "; replacing with new");
8435                pkgSetting = null;
8436            }
8437            final PackageSetting oldPkgSetting =
8438                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8439            final PackageSetting disabledPkgSetting =
8440                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8441            if (pkgSetting == null) {
8442                final String parentPackageName = (pkg.parentPackage != null)
8443                        ? pkg.parentPackage.packageName : null;
8444                // REMOVE SharedUserSetting from method; update in a separate call
8445                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8446                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8447                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8448                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8449                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8450                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8451                        UserManagerService.getInstance());
8452                // SIDE EFFECTS; updates system state; move elsewhere
8453                if (origPackage != null) {
8454                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8455                }
8456                mSettings.addUserToSettingLPw(pkgSetting);
8457            } else {
8458                // REMOVE SharedUserSetting from method; update in a separate call.
8459                //
8460                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8461                // secondaryCpuAbi are not known at this point so we always update them
8462                // to null here, only to reset them at a later point.
8463                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8464                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8465                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8466                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8467                        UserManagerService.getInstance());
8468            }
8469            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8470            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8471
8472            // SIDE EFFECTS; modifies system state; move elsewhere
8473            if (pkgSetting.origPackage != null) {
8474                // If we are first transitioning from an original package,
8475                // fix up the new package's name now.  We need to do this after
8476                // looking up the package under its new name, so getPackageLP
8477                // can take care of fiddling things correctly.
8478                pkg.setPackageName(origPackage.name);
8479
8480                // File a report about this.
8481                String msg = "New package " + pkgSetting.realName
8482                        + " renamed to replace old package " + pkgSetting.name;
8483                reportSettingsProblem(Log.WARN, msg);
8484
8485                // Make a note of it.
8486                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8487                    mTransferedPackages.add(origPackage.name);
8488                }
8489
8490                // No longer need to retain this.
8491                pkgSetting.origPackage = null;
8492            }
8493
8494            // SIDE EFFECTS; modifies system state; move elsewhere
8495            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8496                // Make a note of it.
8497                mTransferedPackages.add(pkg.packageName);
8498            }
8499
8500            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8501                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8502            }
8503
8504            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8505                // Check all shared libraries and map to their actual file path.
8506                // We only do this here for apps not on a system dir, because those
8507                // are the only ones that can fail an install due to this.  We
8508                // will take care of the system apps by updating all of their
8509                // library paths after the scan is done.
8510                updateSharedLibrariesLPr(pkg, null);
8511            }
8512
8513            if (mFoundPolicyFile) {
8514                SELinuxMMAC.assignSeinfoValue(pkg);
8515            }
8516
8517            pkg.applicationInfo.uid = pkgSetting.appId;
8518            pkg.mExtras = pkgSetting;
8519            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8520                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8521                    // We just determined the app is signed correctly, so bring
8522                    // over the latest parsed certs.
8523                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8524                } else {
8525                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8526                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8527                                "Package " + pkg.packageName + " upgrade keys do not match the "
8528                                + "previously installed version");
8529                    } else {
8530                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8531                        String msg = "System package " + pkg.packageName
8532                                + " signature changed; retaining data.";
8533                        reportSettingsProblem(Log.WARN, msg);
8534                    }
8535                }
8536            } else {
8537                try {
8538                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8539                    verifySignaturesLP(pkgSetting, pkg);
8540                    // We just determined the app is signed correctly, so bring
8541                    // over the latest parsed certs.
8542                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8543                } catch (PackageManagerException e) {
8544                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8545                        throw e;
8546                    }
8547                    // The signature has changed, but this package is in the system
8548                    // image...  let's recover!
8549                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8550                    // However...  if this package is part of a shared user, but it
8551                    // doesn't match the signature of the shared user, let's fail.
8552                    // What this means is that you can't change the signatures
8553                    // associated with an overall shared user, which doesn't seem all
8554                    // that unreasonable.
8555                    if (pkgSetting.sharedUser != null) {
8556                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8557                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8558                            throw new PackageManagerException(
8559                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8560                                    "Signature mismatch for shared user: "
8561                                            + pkgSetting.sharedUser);
8562                        }
8563                    }
8564                    // File a report about this.
8565                    String msg = "System package " + pkg.packageName
8566                            + " signature changed; retaining data.";
8567                    reportSettingsProblem(Log.WARN, msg);
8568                }
8569            }
8570
8571            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8572                // This package wants to adopt ownership of permissions from
8573                // another package.
8574                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8575                    final String origName = pkg.mAdoptPermissions.get(i);
8576                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8577                    if (orig != null) {
8578                        if (verifyPackageUpdateLPr(orig, pkg)) {
8579                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8580                                    + pkg.packageName);
8581                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8582                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8583                        }
8584                    }
8585                }
8586            }
8587        }
8588
8589        pkg.applicationInfo.processName = fixProcessName(
8590                pkg.applicationInfo.packageName,
8591                pkg.applicationInfo.processName);
8592
8593        if (pkg != mPlatformPackage) {
8594            // Get all of our default paths setup
8595            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8596        }
8597
8598        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8599
8600        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8601            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8602                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8603                derivePackageAbi(
8604                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8605                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8606
8607                // Some system apps still use directory structure for native libraries
8608                // in which case we might end up not detecting abi solely based on apk
8609                // structure. Try to detect abi based on directory structure.
8610                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8611                        pkg.applicationInfo.primaryCpuAbi == null) {
8612                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8613                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8614                }
8615            } else {
8616                // This is not a first boot or an upgrade, don't bother deriving the
8617                // ABI during the scan. Instead, trust the value that was stored in the
8618                // package setting.
8619                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8620                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8621
8622                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8623
8624                if (DEBUG_ABI_SELECTION) {
8625                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8626                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8627                        pkg.applicationInfo.secondaryCpuAbi);
8628                }
8629            }
8630        } else {
8631            if ((scanFlags & SCAN_MOVE) != 0) {
8632                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8633                // but we already have this packages package info in the PackageSetting. We just
8634                // use that and derive the native library path based on the new codepath.
8635                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8636                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8637            }
8638
8639            // Set native library paths again. For moves, the path will be updated based on the
8640            // ABIs we've determined above. For non-moves, the path will be updated based on the
8641            // ABIs we determined during compilation, but the path will depend on the final
8642            // package path (after the rename away from the stage path).
8643            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8644        }
8645
8646        // This is a special case for the "system" package, where the ABI is
8647        // dictated by the zygote configuration (and init.rc). We should keep track
8648        // of this ABI so that we can deal with "normal" applications that run under
8649        // the same UID correctly.
8650        if (mPlatformPackage == pkg) {
8651            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8652                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8653        }
8654
8655        // If there's a mismatch between the abi-override in the package setting
8656        // and the abiOverride specified for the install. Warn about this because we
8657        // would've already compiled the app without taking the package setting into
8658        // account.
8659        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8660            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8661                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8662                        " for package " + pkg.packageName);
8663            }
8664        }
8665
8666        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8667        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8668        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8669
8670        // Copy the derived override back to the parsed package, so that we can
8671        // update the package settings accordingly.
8672        pkg.cpuAbiOverride = cpuAbiOverride;
8673
8674        if (DEBUG_ABI_SELECTION) {
8675            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8676                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8677                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8678        }
8679
8680        // Push the derived path down into PackageSettings so we know what to
8681        // clean up at uninstall time.
8682        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8683
8684        if (DEBUG_ABI_SELECTION) {
8685            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8686                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8687                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8688        }
8689
8690        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8691        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8692            // We don't do this here during boot because we can do it all
8693            // at once after scanning all existing packages.
8694            //
8695            // We also do this *before* we perform dexopt on this package, so that
8696            // we can avoid redundant dexopts, and also to make sure we've got the
8697            // code and package path correct.
8698            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8699        }
8700
8701        if (mFactoryTest && pkg.requestedPermissions.contains(
8702                android.Manifest.permission.FACTORY_TEST)) {
8703            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8704        }
8705
8706        if (isSystemApp(pkg)) {
8707            pkgSetting.isOrphaned = true;
8708        }
8709
8710        // Take care of first install / last update times.
8711        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8712        if (currentTime != 0) {
8713            if (pkgSetting.firstInstallTime == 0) {
8714                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8715            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8716                pkgSetting.lastUpdateTime = currentTime;
8717            }
8718        } else if (pkgSetting.firstInstallTime == 0) {
8719            // We need *something*.  Take time time stamp of the file.
8720            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8721        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8722            if (scanFileTime != pkgSetting.timeStamp) {
8723                // A package on the system image has changed; consider this
8724                // to be an update.
8725                pkgSetting.lastUpdateTime = scanFileTime;
8726            }
8727        }
8728        pkgSetting.setTimeStamp(scanFileTime);
8729
8730        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8731            if (nonMutatedPs != null) {
8732                synchronized (mPackages) {
8733                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8734                }
8735            }
8736        } else {
8737            // Modify state for the given package setting
8738            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8739                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8740        }
8741        return pkg;
8742    }
8743
8744    /**
8745     * Applies policy to the parsed package based upon the given policy flags.
8746     * Ensures the package is in a good state.
8747     * <p>
8748     * Implementation detail: This method must NOT have any side effect. It would
8749     * ideally be static, but, it requires locks to read system state.
8750     */
8751    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8752        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8753            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8754            if (pkg.applicationInfo.isDirectBootAware()) {
8755                // we're direct boot aware; set for all components
8756                for (PackageParser.Service s : pkg.services) {
8757                    s.info.encryptionAware = s.info.directBootAware = true;
8758                }
8759                for (PackageParser.Provider p : pkg.providers) {
8760                    p.info.encryptionAware = p.info.directBootAware = true;
8761                }
8762                for (PackageParser.Activity a : pkg.activities) {
8763                    a.info.encryptionAware = a.info.directBootAware = true;
8764                }
8765                for (PackageParser.Activity r : pkg.receivers) {
8766                    r.info.encryptionAware = r.info.directBootAware = true;
8767                }
8768            }
8769        } else {
8770            // Only allow system apps to be flagged as core apps.
8771            pkg.coreApp = false;
8772            // clear flags not applicable to regular apps
8773            pkg.applicationInfo.privateFlags &=
8774                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8775            pkg.applicationInfo.privateFlags &=
8776                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8777        }
8778        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8779
8780        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8781            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8782        }
8783
8784        if (!isSystemApp(pkg)) {
8785            // Only system apps can use these features.
8786            pkg.mOriginalPackages = null;
8787            pkg.mRealPackage = null;
8788            pkg.mAdoptPermissions = null;
8789        }
8790    }
8791
8792    /**
8793     * Asserts the parsed package is valid according to teh given policy. If the
8794     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8795     * <p>
8796     * Implementation detail: This method must NOT have any side effects. It would
8797     * ideally be static, but, it requires locks to read system state.
8798     *
8799     * @throws PackageManagerException If the package fails any of the validation checks
8800     */
8801    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8802            throws PackageManagerException {
8803        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8804            assertCodePolicy(pkg);
8805        }
8806
8807        if (pkg.applicationInfo.getCodePath() == null ||
8808                pkg.applicationInfo.getResourcePath() == null) {
8809            // Bail out. The resource and code paths haven't been set.
8810            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8811                    "Code and resource paths haven't been set correctly");
8812        }
8813
8814        // Make sure we're not adding any bogus keyset info
8815        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8816        ksms.assertScannedPackageValid(pkg);
8817
8818        synchronized (mPackages) {
8819            // The special "android" package can only be defined once
8820            if (pkg.packageName.equals("android")) {
8821                if (mAndroidApplication != null) {
8822                    Slog.w(TAG, "*************************************************");
8823                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8824                    Slog.w(TAG, " codePath=" + pkg.codePath);
8825                    Slog.w(TAG, "*************************************************");
8826                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8827                            "Core android package being redefined.  Skipping.");
8828                }
8829            }
8830
8831            // A package name must be unique; don't allow duplicates
8832            if (mPackages.containsKey(pkg.packageName)
8833                    || mSharedLibraries.containsKey(pkg.packageName)) {
8834                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8835                        "Application package " + pkg.packageName
8836                        + " already installed.  Skipping duplicate.");
8837            }
8838
8839            // Only privileged apps and updated privileged apps can add child packages.
8840            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8841                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8842                    throw new PackageManagerException("Only privileged apps can add child "
8843                            + "packages. Ignoring package " + pkg.packageName);
8844                }
8845                final int childCount = pkg.childPackages.size();
8846                for (int i = 0; i < childCount; i++) {
8847                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8848                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8849                            childPkg.packageName)) {
8850                        throw new PackageManagerException("Can't override child of "
8851                                + "another disabled app. Ignoring package " + pkg.packageName);
8852                    }
8853                }
8854            }
8855
8856            // If we're only installing presumed-existing packages, require that the
8857            // scanned APK is both already known and at the path previously established
8858            // for it.  Previously unknown packages we pick up normally, but if we have an
8859            // a priori expectation about this package's install presence, enforce it.
8860            // With a singular exception for new system packages. When an OTA contains
8861            // a new system package, we allow the codepath to change from a system location
8862            // to the user-installed location. If we don't allow this change, any newer,
8863            // user-installed version of the application will be ignored.
8864            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8865                if (mExpectingBetter.containsKey(pkg.packageName)) {
8866                    logCriticalInfo(Log.WARN,
8867                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8868                } else {
8869                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8870                    if (known != null) {
8871                        if (DEBUG_PACKAGE_SCANNING) {
8872                            Log.d(TAG, "Examining " + pkg.codePath
8873                                    + " and requiring known paths " + known.codePathString
8874                                    + " & " + known.resourcePathString);
8875                        }
8876                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8877                                || !pkg.applicationInfo.getResourcePath().equals(
8878                                        known.resourcePathString)) {
8879                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8880                                    "Application package " + pkg.packageName
8881                                    + " found at " + pkg.applicationInfo.getCodePath()
8882                                    + " but expected at " + known.codePathString
8883                                    + "; ignoring.");
8884                        }
8885                    }
8886                }
8887            }
8888
8889            // Verify that this new package doesn't have any content providers
8890            // that conflict with existing packages.  Only do this if the
8891            // package isn't already installed, since we don't want to break
8892            // things that are installed.
8893            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8894                final int N = pkg.providers.size();
8895                int i;
8896                for (i=0; i<N; i++) {
8897                    PackageParser.Provider p = pkg.providers.get(i);
8898                    if (p.info.authority != null) {
8899                        String names[] = p.info.authority.split(";");
8900                        for (int j = 0; j < names.length; j++) {
8901                            if (mProvidersByAuthority.containsKey(names[j])) {
8902                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8903                                final String otherPackageName =
8904                                        ((other != null && other.getComponentName() != null) ?
8905                                                other.getComponentName().getPackageName() : "?");
8906                                throw new PackageManagerException(
8907                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8908                                        "Can't install because provider name " + names[j]
8909                                                + " (in package " + pkg.applicationInfo.packageName
8910                                                + ") is already used by " + otherPackageName);
8911                            }
8912                        }
8913                    }
8914                }
8915            }
8916        }
8917    }
8918
8919    /**
8920     * Adds a scanned package to the system. When this method is finished, the package will
8921     * be available for query, resolution, etc...
8922     */
8923    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8924            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8925        final String pkgName = pkg.packageName;
8926        if (mCustomResolverComponentName != null &&
8927                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8928            setUpCustomResolverActivity(pkg);
8929        }
8930
8931        if (pkg.packageName.equals("android")) {
8932            synchronized (mPackages) {
8933                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8934                    // Set up information for our fall-back user intent resolution activity.
8935                    mPlatformPackage = pkg;
8936                    pkg.mVersionCode = mSdkVersion;
8937                    mAndroidApplication = pkg.applicationInfo;
8938
8939                    if (!mResolverReplaced) {
8940                        mResolveActivity.applicationInfo = mAndroidApplication;
8941                        mResolveActivity.name = ResolverActivity.class.getName();
8942                        mResolveActivity.packageName = mAndroidApplication.packageName;
8943                        mResolveActivity.processName = "system:ui";
8944                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8945                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8946                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8947                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8948                        mResolveActivity.exported = true;
8949                        mResolveActivity.enabled = true;
8950                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8951                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8952                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8953                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8954                                | ActivityInfo.CONFIG_ORIENTATION
8955                                | ActivityInfo.CONFIG_KEYBOARD
8956                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8957                        mResolveInfo.activityInfo = mResolveActivity;
8958                        mResolveInfo.priority = 0;
8959                        mResolveInfo.preferredOrder = 0;
8960                        mResolveInfo.match = 0;
8961                        mResolveComponentName = new ComponentName(
8962                                mAndroidApplication.packageName, mResolveActivity.name);
8963                    }
8964                }
8965            }
8966        }
8967
8968        ArrayList<PackageParser.Package> clientLibPkgs = null;
8969        // writer
8970        synchronized (mPackages) {
8971            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8972                // Only system apps can add new shared libraries.
8973                if (pkg.libraryNames != null) {
8974                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8975                        String name = pkg.libraryNames.get(i);
8976                        boolean allowed = false;
8977                        if (pkg.isUpdatedSystemApp()) {
8978                            // New library entries can only be added through the
8979                            // system image.  This is important to get rid of a lot
8980                            // of nasty edge cases: for example if we allowed a non-
8981                            // system update of the app to add a library, then uninstalling
8982                            // the update would make the library go away, and assumptions
8983                            // we made such as through app install filtering would now
8984                            // have allowed apps on the device which aren't compatible
8985                            // with it.  Better to just have the restriction here, be
8986                            // conservative, and create many fewer cases that can negatively
8987                            // impact the user experience.
8988                            final PackageSetting sysPs = mSettings
8989                                    .getDisabledSystemPkgLPr(pkg.packageName);
8990                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8991                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8992                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8993                                        allowed = true;
8994                                        break;
8995                                    }
8996                                }
8997                            }
8998                        } else {
8999                            allowed = true;
9000                        }
9001                        if (allowed) {
9002                            if (!mSharedLibraries.containsKey(name)) {
9003                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
9004                            } else if (!name.equals(pkg.packageName)) {
9005                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9006                                        + name + " already exists; skipping");
9007                            }
9008                        } else {
9009                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9010                                    + name + " that is not declared on system image; skipping");
9011                        }
9012                    }
9013                    if ((scanFlags & SCAN_BOOTING) == 0) {
9014                        // If we are not booting, we need to update any applications
9015                        // that are clients of our shared library.  If we are booting,
9016                        // this will all be done once the scan is complete.
9017                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9018                    }
9019                }
9020            }
9021        }
9022
9023        if ((scanFlags & SCAN_BOOTING) != 0) {
9024            // No apps can run during boot scan, so they don't need to be frozen
9025        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9026            // Caller asked to not kill app, so it's probably not frozen
9027        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9028            // Caller asked us to ignore frozen check for some reason; they
9029            // probably didn't know the package name
9030        } else {
9031            // We're doing major surgery on this package, so it better be frozen
9032            // right now to keep it from launching
9033            checkPackageFrozen(pkgName);
9034        }
9035
9036        // Also need to kill any apps that are dependent on the library.
9037        if (clientLibPkgs != null) {
9038            for (int i=0; i<clientLibPkgs.size(); i++) {
9039                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9040                killApplication(clientPkg.applicationInfo.packageName,
9041                        clientPkg.applicationInfo.uid, "update lib");
9042            }
9043        }
9044
9045        // writer
9046        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9047
9048        boolean createIdmapFailed = false;
9049        synchronized (mPackages) {
9050            // We don't expect installation to fail beyond this point
9051
9052            if (pkgSetting.pkg != null) {
9053                // Note that |user| might be null during the initial boot scan. If a codePath
9054                // for an app has changed during a boot scan, it's due to an app update that's
9055                // part of the system partition and marker changes must be applied to all users.
9056                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9057                final int[] userIds = resolveUserIds(userId);
9058                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9059            }
9060
9061            // Add the new setting to mSettings
9062            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9063            // Add the new setting to mPackages
9064            mPackages.put(pkg.applicationInfo.packageName, pkg);
9065            // Make sure we don't accidentally delete its data.
9066            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9067            while (iter.hasNext()) {
9068                PackageCleanItem item = iter.next();
9069                if (pkgName.equals(item.packageName)) {
9070                    iter.remove();
9071                }
9072            }
9073
9074            // Add the package's KeySets to the global KeySetManagerService
9075            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9076            ksms.addScannedPackageLPw(pkg);
9077
9078            int N = pkg.providers.size();
9079            StringBuilder r = null;
9080            int i;
9081            for (i=0; i<N; i++) {
9082                PackageParser.Provider p = pkg.providers.get(i);
9083                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9084                        p.info.processName);
9085                mProviders.addProvider(p);
9086                p.syncable = p.info.isSyncable;
9087                if (p.info.authority != null) {
9088                    String names[] = p.info.authority.split(";");
9089                    p.info.authority = null;
9090                    for (int j = 0; j < names.length; j++) {
9091                        if (j == 1 && p.syncable) {
9092                            // We only want the first authority for a provider to possibly be
9093                            // syncable, so if we already added this provider using a different
9094                            // authority clear the syncable flag. We copy the provider before
9095                            // changing it because the mProviders object contains a reference
9096                            // to a provider that we don't want to change.
9097                            // Only do this for the second authority since the resulting provider
9098                            // object can be the same for all future authorities for this provider.
9099                            p = new PackageParser.Provider(p);
9100                            p.syncable = false;
9101                        }
9102                        if (!mProvidersByAuthority.containsKey(names[j])) {
9103                            mProvidersByAuthority.put(names[j], p);
9104                            if (p.info.authority == null) {
9105                                p.info.authority = names[j];
9106                            } else {
9107                                p.info.authority = p.info.authority + ";" + names[j];
9108                            }
9109                            if (DEBUG_PACKAGE_SCANNING) {
9110                                if (chatty)
9111                                    Log.d(TAG, "Registered content provider: " + names[j]
9112                                            + ", className = " + p.info.name + ", isSyncable = "
9113                                            + p.info.isSyncable);
9114                            }
9115                        } else {
9116                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9117                            Slog.w(TAG, "Skipping provider name " + names[j] +
9118                                    " (in package " + pkg.applicationInfo.packageName +
9119                                    "): name already used by "
9120                                    + ((other != null && other.getComponentName() != null)
9121                                            ? other.getComponentName().getPackageName() : "?"));
9122                        }
9123                    }
9124                }
9125                if (chatty) {
9126                    if (r == null) {
9127                        r = new StringBuilder(256);
9128                    } else {
9129                        r.append(' ');
9130                    }
9131                    r.append(p.info.name);
9132                }
9133            }
9134            if (r != null) {
9135                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9136            }
9137
9138            N = pkg.services.size();
9139            r = null;
9140            for (i=0; i<N; i++) {
9141                PackageParser.Service s = pkg.services.get(i);
9142                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9143                        s.info.processName);
9144                mServices.addService(s);
9145                if (chatty) {
9146                    if (r == null) {
9147                        r = new StringBuilder(256);
9148                    } else {
9149                        r.append(' ');
9150                    }
9151                    r.append(s.info.name);
9152                }
9153            }
9154            if (r != null) {
9155                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9156            }
9157
9158            N = pkg.receivers.size();
9159            r = null;
9160            for (i=0; i<N; i++) {
9161                PackageParser.Activity a = pkg.receivers.get(i);
9162                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9163                        a.info.processName);
9164                mReceivers.addActivity(a, "receiver");
9165                if (chatty) {
9166                    if (r == null) {
9167                        r = new StringBuilder(256);
9168                    } else {
9169                        r.append(' ');
9170                    }
9171                    r.append(a.info.name);
9172                }
9173            }
9174            if (r != null) {
9175                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9176            }
9177
9178            N = pkg.activities.size();
9179            r = null;
9180            for (i=0; i<N; i++) {
9181                PackageParser.Activity a = pkg.activities.get(i);
9182                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9183                        a.info.processName);
9184                mActivities.addActivity(a, "activity");
9185                if (chatty) {
9186                    if (r == null) {
9187                        r = new StringBuilder(256);
9188                    } else {
9189                        r.append(' ');
9190                    }
9191                    r.append(a.info.name);
9192                }
9193            }
9194            if (r != null) {
9195                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9196            }
9197
9198            N = pkg.permissionGroups.size();
9199            r = null;
9200            for (i=0; i<N; i++) {
9201                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9202                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9203                final String curPackageName = cur == null ? null : cur.info.packageName;
9204                // Dont allow ephemeral apps to define new permission groups.
9205                if (pkg.applicationInfo.isEphemeralApp()) {
9206                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9207                            + pg.info.packageName
9208                            + " ignored: ephemeral apps cannot define new permission groups.");
9209                    continue;
9210                }
9211                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9212                if (cur == null || isPackageUpdate) {
9213                    mPermissionGroups.put(pg.info.name, pg);
9214                    if (chatty) {
9215                        if (r == null) {
9216                            r = new StringBuilder(256);
9217                        } else {
9218                            r.append(' ');
9219                        }
9220                        if (isPackageUpdate) {
9221                            r.append("UPD:");
9222                        }
9223                        r.append(pg.info.name);
9224                    }
9225                } else {
9226                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9227                            + pg.info.packageName + " ignored: original from "
9228                            + cur.info.packageName);
9229                    if (chatty) {
9230                        if (r == null) {
9231                            r = new StringBuilder(256);
9232                        } else {
9233                            r.append(' ');
9234                        }
9235                        r.append("DUP:");
9236                        r.append(pg.info.name);
9237                    }
9238                }
9239            }
9240            if (r != null) {
9241                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9242            }
9243
9244            N = pkg.permissions.size();
9245            r = null;
9246            for (i=0; i<N; i++) {
9247                PackageParser.Permission p = pkg.permissions.get(i);
9248
9249                // Dont allow ephemeral apps to define new permissions.
9250                if (pkg.applicationInfo.isEphemeralApp()) {
9251                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9252                            + p.info.packageName
9253                            + " ignored: ephemeral apps cannot define new permissions.");
9254                    continue;
9255                }
9256
9257                // Assume by default that we did not install this permission into the system.
9258                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9259
9260                // Now that permission groups have a special meaning, we ignore permission
9261                // groups for legacy apps to prevent unexpected behavior. In particular,
9262                // permissions for one app being granted to someone just becase they happen
9263                // to be in a group defined by another app (before this had no implications).
9264                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9265                    p.group = mPermissionGroups.get(p.info.group);
9266                    // Warn for a permission in an unknown group.
9267                    if (p.info.group != null && p.group == null) {
9268                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9269                                + p.info.packageName + " in an unknown group " + p.info.group);
9270                    }
9271                }
9272
9273                ArrayMap<String, BasePermission> permissionMap =
9274                        p.tree ? mSettings.mPermissionTrees
9275                                : mSettings.mPermissions;
9276                BasePermission bp = permissionMap.get(p.info.name);
9277
9278                // Allow system apps to redefine non-system permissions
9279                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9280                    final boolean currentOwnerIsSystem = (bp.perm != null
9281                            && isSystemApp(bp.perm.owner));
9282                    if (isSystemApp(p.owner)) {
9283                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9284                            // It's a built-in permission and no owner, take ownership now
9285                            bp.packageSetting = pkgSetting;
9286                            bp.perm = p;
9287                            bp.uid = pkg.applicationInfo.uid;
9288                            bp.sourcePackage = p.info.packageName;
9289                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9290                        } else if (!currentOwnerIsSystem) {
9291                            String msg = "New decl " + p.owner + " of permission  "
9292                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9293                            reportSettingsProblem(Log.WARN, msg);
9294                            bp = null;
9295                        }
9296                    }
9297                }
9298
9299                if (bp == null) {
9300                    bp = new BasePermission(p.info.name, p.info.packageName,
9301                            BasePermission.TYPE_NORMAL);
9302                    permissionMap.put(p.info.name, bp);
9303                }
9304
9305                if (bp.perm == null) {
9306                    if (bp.sourcePackage == null
9307                            || bp.sourcePackage.equals(p.info.packageName)) {
9308                        BasePermission tree = findPermissionTreeLP(p.info.name);
9309                        if (tree == null
9310                                || tree.sourcePackage.equals(p.info.packageName)) {
9311                            bp.packageSetting = pkgSetting;
9312                            bp.perm = p;
9313                            bp.uid = pkg.applicationInfo.uid;
9314                            bp.sourcePackage = p.info.packageName;
9315                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9316                            if (chatty) {
9317                                if (r == null) {
9318                                    r = new StringBuilder(256);
9319                                } else {
9320                                    r.append(' ');
9321                                }
9322                                r.append(p.info.name);
9323                            }
9324                        } else {
9325                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9326                                    + p.info.packageName + " ignored: base tree "
9327                                    + tree.name + " is from package "
9328                                    + tree.sourcePackage);
9329                        }
9330                    } else {
9331                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9332                                + p.info.packageName + " ignored: original from "
9333                                + bp.sourcePackage);
9334                    }
9335                } else if (chatty) {
9336                    if (r == null) {
9337                        r = new StringBuilder(256);
9338                    } else {
9339                        r.append(' ');
9340                    }
9341                    r.append("DUP:");
9342                    r.append(p.info.name);
9343                }
9344                if (bp.perm == p) {
9345                    bp.protectionLevel = p.info.protectionLevel;
9346                }
9347            }
9348
9349            if (r != null) {
9350                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9351            }
9352
9353            N = pkg.instrumentation.size();
9354            r = null;
9355            for (i=0; i<N; i++) {
9356                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9357                a.info.packageName = pkg.applicationInfo.packageName;
9358                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9359                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9360                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9361                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9362                a.info.dataDir = pkg.applicationInfo.dataDir;
9363                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9364                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9365                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9366                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9367                mInstrumentation.put(a.getComponentName(), a);
9368                if (chatty) {
9369                    if (r == null) {
9370                        r = new StringBuilder(256);
9371                    } else {
9372                        r.append(' ');
9373                    }
9374                    r.append(a.info.name);
9375                }
9376            }
9377            if (r != null) {
9378                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9379            }
9380
9381            if (pkg.protectedBroadcasts != null) {
9382                N = pkg.protectedBroadcasts.size();
9383                for (i=0; i<N; i++) {
9384                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9385                }
9386            }
9387
9388            // Create idmap files for pairs of (packages, overlay packages).
9389            // Note: "android", ie framework-res.apk, is handled by native layers.
9390            if (pkg.mOverlayTarget != null) {
9391                // This is an overlay package.
9392                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9393                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9394                        mOverlays.put(pkg.mOverlayTarget,
9395                                new ArrayMap<String, PackageParser.Package>());
9396                    }
9397                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9398                    map.put(pkg.packageName, pkg);
9399                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9400                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9401                        createIdmapFailed = true;
9402                    }
9403                }
9404            } else if (mOverlays.containsKey(pkg.packageName) &&
9405                    !pkg.packageName.equals("android")) {
9406                // This is a regular package, with one or more known overlay packages.
9407                createIdmapsForPackageLI(pkg);
9408            }
9409        }
9410
9411        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9412
9413        if (createIdmapFailed) {
9414            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9415                    "scanPackageLI failed to createIdmap");
9416        }
9417    }
9418
9419    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9420            PackageParser.Package update, int[] userIds) {
9421        if (existing.applicationInfo == null || update.applicationInfo == null) {
9422            // This isn't due to an app installation.
9423            return;
9424        }
9425
9426        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9427        final File newCodePath = new File(update.applicationInfo.getCodePath());
9428
9429        // The codePath hasn't changed, so there's nothing for us to do.
9430        if (Objects.equals(oldCodePath, newCodePath)) {
9431            return;
9432        }
9433
9434        File canonicalNewCodePath;
9435        try {
9436            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9437        } catch (IOException e) {
9438            Slog.w(TAG, "Failed to get canonical path.", e);
9439            return;
9440        }
9441
9442        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9443        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9444        // that the last component of the path (i.e, the name) doesn't need canonicalization
9445        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9446        // but may change in the future. Hopefully this function won't exist at that point.
9447        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9448                oldCodePath.getName());
9449
9450        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9451        // with "@".
9452        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9453        if (!oldMarkerPrefix.endsWith("@")) {
9454            oldMarkerPrefix += "@";
9455        }
9456        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9457        if (!newMarkerPrefix.endsWith("@")) {
9458            newMarkerPrefix += "@";
9459        }
9460
9461        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9462        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9463        for (String updatedPath : updatedPaths) {
9464            String updatedPathName = new File(updatedPath).getName();
9465            markerSuffixes.add(updatedPathName.replace('/', '@'));
9466        }
9467
9468        for (int userId : userIds) {
9469            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9470
9471            for (String markerSuffix : markerSuffixes) {
9472                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9473                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9474                if (oldForeignUseMark.exists()) {
9475                    try {
9476                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9477                                newForeignUseMark.getAbsolutePath());
9478                    } catch (ErrnoException e) {
9479                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9480                        oldForeignUseMark.delete();
9481                    }
9482                }
9483            }
9484        }
9485    }
9486
9487    /**
9488     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9489     * is derived purely on the basis of the contents of {@code scanFile} and
9490     * {@code cpuAbiOverride}.
9491     *
9492     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9493     */
9494    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9495                                 String cpuAbiOverride, boolean extractLibs,
9496                                 File appLib32InstallDir)
9497            throws PackageManagerException {
9498        // Give ourselves some initial paths; we'll come back for another
9499        // pass once we've determined ABI below.
9500        setNativeLibraryPaths(pkg, appLib32InstallDir);
9501
9502        // We would never need to extract libs for forward-locked and external packages,
9503        // since the container service will do it for us. We shouldn't attempt to
9504        // extract libs from system app when it was not updated.
9505        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9506                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9507            extractLibs = false;
9508        }
9509
9510        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9511        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9512
9513        NativeLibraryHelper.Handle handle = null;
9514        try {
9515            handle = NativeLibraryHelper.Handle.create(pkg);
9516            // TODO(multiArch): This can be null for apps that didn't go through the
9517            // usual installation process. We can calculate it again, like we
9518            // do during install time.
9519            //
9520            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9521            // unnecessary.
9522            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9523
9524            // Null out the abis so that they can be recalculated.
9525            pkg.applicationInfo.primaryCpuAbi = null;
9526            pkg.applicationInfo.secondaryCpuAbi = null;
9527            if (isMultiArch(pkg.applicationInfo)) {
9528                // Warn if we've set an abiOverride for multi-lib packages..
9529                // By definition, we need to copy both 32 and 64 bit libraries for
9530                // such packages.
9531                if (pkg.cpuAbiOverride != null
9532                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9533                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9534                }
9535
9536                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9537                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9538                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9539                    if (extractLibs) {
9540                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9541                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9542                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9543                                useIsaSpecificSubdirs);
9544                    } else {
9545                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9546                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9547                    }
9548                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9549                }
9550
9551                maybeThrowExceptionForMultiArchCopy(
9552                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9553
9554                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9555                    if (extractLibs) {
9556                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9557                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9558                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9559                                useIsaSpecificSubdirs);
9560                    } else {
9561                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9562                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9563                    }
9564                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9565                }
9566
9567                maybeThrowExceptionForMultiArchCopy(
9568                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9569
9570                if (abi64 >= 0) {
9571                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9572                }
9573
9574                if (abi32 >= 0) {
9575                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9576                    if (abi64 >= 0) {
9577                        if (pkg.use32bitAbi) {
9578                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9579                            pkg.applicationInfo.primaryCpuAbi = abi;
9580                        } else {
9581                            pkg.applicationInfo.secondaryCpuAbi = abi;
9582                        }
9583                    } else {
9584                        pkg.applicationInfo.primaryCpuAbi = abi;
9585                    }
9586                }
9587
9588            } else {
9589                String[] abiList = (cpuAbiOverride != null) ?
9590                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9591
9592                // Enable gross and lame hacks for apps that are built with old
9593                // SDK tools. We must scan their APKs for renderscript bitcode and
9594                // not launch them if it's present. Don't bother checking on devices
9595                // that don't have 64 bit support.
9596                boolean needsRenderScriptOverride = false;
9597                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9598                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9599                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9600                    needsRenderScriptOverride = true;
9601                }
9602
9603                final int copyRet;
9604                if (extractLibs) {
9605                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9606                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9607                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9608                } else {
9609                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9610                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9611                }
9612                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9613
9614                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9615                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9616                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9617                }
9618
9619                if (copyRet >= 0) {
9620                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9621                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9622                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9623                } else if (needsRenderScriptOverride) {
9624                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9625                }
9626            }
9627        } catch (IOException ioe) {
9628            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9629        } finally {
9630            IoUtils.closeQuietly(handle);
9631        }
9632
9633        // Now that we've calculated the ABIs and determined if it's an internal app,
9634        // we will go ahead and populate the nativeLibraryPath.
9635        setNativeLibraryPaths(pkg, appLib32InstallDir);
9636    }
9637
9638    /**
9639     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9640     * i.e, so that all packages can be run inside a single process if required.
9641     *
9642     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9643     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9644     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9645     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9646     * updating a package that belongs to a shared user.
9647     *
9648     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9649     * adds unnecessary complexity.
9650     */
9651    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9652            PackageParser.Package scannedPackage) {
9653        String requiredInstructionSet = null;
9654        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9655            requiredInstructionSet = VMRuntime.getInstructionSet(
9656                     scannedPackage.applicationInfo.primaryCpuAbi);
9657        }
9658
9659        PackageSetting requirer = null;
9660        for (PackageSetting ps : packagesForUser) {
9661            // If packagesForUser contains scannedPackage, we skip it. This will happen
9662            // when scannedPackage is an update of an existing package. Without this check,
9663            // we will never be able to change the ABI of any package belonging to a shared
9664            // user, even if it's compatible with other packages.
9665            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9666                if (ps.primaryCpuAbiString == null) {
9667                    continue;
9668                }
9669
9670                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9671                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9672                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9673                    // this but there's not much we can do.
9674                    String errorMessage = "Instruction set mismatch, "
9675                            + ((requirer == null) ? "[caller]" : requirer)
9676                            + " requires " + requiredInstructionSet + " whereas " + ps
9677                            + " requires " + instructionSet;
9678                    Slog.w(TAG, errorMessage);
9679                }
9680
9681                if (requiredInstructionSet == null) {
9682                    requiredInstructionSet = instructionSet;
9683                    requirer = ps;
9684                }
9685            }
9686        }
9687
9688        if (requiredInstructionSet != null) {
9689            String adjustedAbi;
9690            if (requirer != null) {
9691                // requirer != null implies that either scannedPackage was null or that scannedPackage
9692                // did not require an ABI, in which case we have to adjust scannedPackage to match
9693                // the ABI of the set (which is the same as requirer's ABI)
9694                adjustedAbi = requirer.primaryCpuAbiString;
9695                if (scannedPackage != null) {
9696                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9697                }
9698            } else {
9699                // requirer == null implies that we're updating all ABIs in the set to
9700                // match scannedPackage.
9701                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9702            }
9703
9704            for (PackageSetting ps : packagesForUser) {
9705                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9706                    if (ps.primaryCpuAbiString != null) {
9707                        continue;
9708                    }
9709
9710                    ps.primaryCpuAbiString = adjustedAbi;
9711                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9712                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9713                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9714                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9715                                + " (requirer="
9716                                + (requirer == null ? "null" : requirer.pkg.packageName)
9717                                + ", scannedPackage="
9718                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9719                                + ")");
9720                        try {
9721                            mInstaller.rmdex(ps.codePathString,
9722                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9723                        } catch (InstallerException ignored) {
9724                        }
9725                    }
9726                }
9727            }
9728        }
9729    }
9730
9731    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9732        synchronized (mPackages) {
9733            mResolverReplaced = true;
9734            // Set up information for custom user intent resolution activity.
9735            mResolveActivity.applicationInfo = pkg.applicationInfo;
9736            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9737            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9738            mResolveActivity.processName = pkg.applicationInfo.packageName;
9739            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9740            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9741                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9742            mResolveActivity.theme = 0;
9743            mResolveActivity.exported = true;
9744            mResolveActivity.enabled = true;
9745            mResolveInfo.activityInfo = mResolveActivity;
9746            mResolveInfo.priority = 0;
9747            mResolveInfo.preferredOrder = 0;
9748            mResolveInfo.match = 0;
9749            mResolveComponentName = mCustomResolverComponentName;
9750            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9751                    mResolveComponentName);
9752        }
9753    }
9754
9755    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9756        if (installerComponent == null) {
9757            if (DEBUG_EPHEMERAL) {
9758                Slog.d(TAG, "Clear ephemeral installer activity");
9759            }
9760            mEphemeralInstallerActivity.applicationInfo = null;
9761            return;
9762        }
9763
9764        if (DEBUG_EPHEMERAL) {
9765            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9766        }
9767        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9768        // Set up information for ephemeral installer activity
9769        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9770        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9771        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9772        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9773        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9774        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9775                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9776        mEphemeralInstallerActivity.theme = 0;
9777        mEphemeralInstallerActivity.exported = true;
9778        mEphemeralInstallerActivity.enabled = true;
9779        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9780        mEphemeralInstallerInfo.priority = 0;
9781        mEphemeralInstallerInfo.preferredOrder = 1;
9782        mEphemeralInstallerInfo.isDefault = true;
9783        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9784                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9785    }
9786
9787    private static String calculateBundledApkRoot(final String codePathString) {
9788        final File codePath = new File(codePathString);
9789        final File codeRoot;
9790        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9791            codeRoot = Environment.getRootDirectory();
9792        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9793            codeRoot = Environment.getOemDirectory();
9794        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9795            codeRoot = Environment.getVendorDirectory();
9796        } else {
9797            // Unrecognized code path; take its top real segment as the apk root:
9798            // e.g. /something/app/blah.apk => /something
9799            try {
9800                File f = codePath.getCanonicalFile();
9801                File parent = f.getParentFile();    // non-null because codePath is a file
9802                File tmp;
9803                while ((tmp = parent.getParentFile()) != null) {
9804                    f = parent;
9805                    parent = tmp;
9806                }
9807                codeRoot = f;
9808                Slog.w(TAG, "Unrecognized code path "
9809                        + codePath + " - using " + codeRoot);
9810            } catch (IOException e) {
9811                // Can't canonicalize the code path -- shenanigans?
9812                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9813                return Environment.getRootDirectory().getPath();
9814            }
9815        }
9816        return codeRoot.getPath();
9817    }
9818
9819    /**
9820     * Derive and set the location of native libraries for the given package,
9821     * which varies depending on where and how the package was installed.
9822     */
9823    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9824        final ApplicationInfo info = pkg.applicationInfo;
9825        final String codePath = pkg.codePath;
9826        final File codeFile = new File(codePath);
9827        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9828        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9829
9830        info.nativeLibraryRootDir = null;
9831        info.nativeLibraryRootRequiresIsa = false;
9832        info.nativeLibraryDir = null;
9833        info.secondaryNativeLibraryDir = null;
9834
9835        if (isApkFile(codeFile)) {
9836            // Monolithic install
9837            if (bundledApp) {
9838                // If "/system/lib64/apkname" exists, assume that is the per-package
9839                // native library directory to use; otherwise use "/system/lib/apkname".
9840                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9841                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9842                        getPrimaryInstructionSet(info));
9843
9844                // This is a bundled system app so choose the path based on the ABI.
9845                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9846                // is just the default path.
9847                final String apkName = deriveCodePathName(codePath);
9848                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9849                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9850                        apkName).getAbsolutePath();
9851
9852                if (info.secondaryCpuAbi != null) {
9853                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9854                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9855                            secondaryLibDir, apkName).getAbsolutePath();
9856                }
9857            } else if (asecApp) {
9858                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9859                        .getAbsolutePath();
9860            } else {
9861                final String apkName = deriveCodePathName(codePath);
9862                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9863                        .getAbsolutePath();
9864            }
9865
9866            info.nativeLibraryRootRequiresIsa = false;
9867            info.nativeLibraryDir = info.nativeLibraryRootDir;
9868        } else {
9869            // Cluster install
9870            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9871            info.nativeLibraryRootRequiresIsa = true;
9872
9873            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9874                    getPrimaryInstructionSet(info)).getAbsolutePath();
9875
9876            if (info.secondaryCpuAbi != null) {
9877                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9878                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9879            }
9880        }
9881    }
9882
9883    /**
9884     * Calculate the abis and roots for a bundled app. These can uniquely
9885     * be determined from the contents of the system partition, i.e whether
9886     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9887     * of this information, and instead assume that the system was built
9888     * sensibly.
9889     */
9890    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9891                                           PackageSetting pkgSetting) {
9892        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9893
9894        // If "/system/lib64/apkname" exists, assume that is the per-package
9895        // native library directory to use; otherwise use "/system/lib/apkname".
9896        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9897        setBundledAppAbi(pkg, apkRoot, apkName);
9898        // pkgSetting might be null during rescan following uninstall of updates
9899        // to a bundled app, so accommodate that possibility.  The settings in
9900        // that case will be established later from the parsed package.
9901        //
9902        // If the settings aren't null, sync them up with what we've just derived.
9903        // note that apkRoot isn't stored in the package settings.
9904        if (pkgSetting != null) {
9905            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9906            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9907        }
9908    }
9909
9910    /**
9911     * Deduces the ABI of a bundled app and sets the relevant fields on the
9912     * parsed pkg object.
9913     *
9914     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9915     *        under which system libraries are installed.
9916     * @param apkName the name of the installed package.
9917     */
9918    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9919        final File codeFile = new File(pkg.codePath);
9920
9921        final boolean has64BitLibs;
9922        final boolean has32BitLibs;
9923        if (isApkFile(codeFile)) {
9924            // Monolithic install
9925            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9926            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9927        } else {
9928            // Cluster install
9929            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9930            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9931                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9932                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9933                has64BitLibs = (new File(rootDir, isa)).exists();
9934            } else {
9935                has64BitLibs = false;
9936            }
9937            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9938                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9939                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9940                has32BitLibs = (new File(rootDir, isa)).exists();
9941            } else {
9942                has32BitLibs = false;
9943            }
9944        }
9945
9946        if (has64BitLibs && !has32BitLibs) {
9947            // The package has 64 bit libs, but not 32 bit libs. Its primary
9948            // ABI should be 64 bit. We can safely assume here that the bundled
9949            // native libraries correspond to the most preferred ABI in the list.
9950
9951            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9952            pkg.applicationInfo.secondaryCpuAbi = null;
9953        } else if (has32BitLibs && !has64BitLibs) {
9954            // The package has 32 bit libs but not 64 bit libs. Its primary
9955            // ABI should be 32 bit.
9956
9957            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9958            pkg.applicationInfo.secondaryCpuAbi = null;
9959        } else if (has32BitLibs && has64BitLibs) {
9960            // The application has both 64 and 32 bit bundled libraries. We check
9961            // here that the app declares multiArch support, and warn if it doesn't.
9962            //
9963            // We will be lenient here and record both ABIs. The primary will be the
9964            // ABI that's higher on the list, i.e, a device that's configured to prefer
9965            // 64 bit apps will see a 64 bit primary ABI,
9966
9967            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9968                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9969            }
9970
9971            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9972                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9973                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9974            } else {
9975                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9976                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9977            }
9978        } else {
9979            pkg.applicationInfo.primaryCpuAbi = null;
9980            pkg.applicationInfo.secondaryCpuAbi = null;
9981        }
9982    }
9983
9984    private void killApplication(String pkgName, int appId, String reason) {
9985        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9986    }
9987
9988    private void killApplication(String pkgName, int appId, int userId, String reason) {
9989        // Request the ActivityManager to kill the process(only for existing packages)
9990        // so that we do not end up in a confused state while the user is still using the older
9991        // version of the application while the new one gets installed.
9992        final long token = Binder.clearCallingIdentity();
9993        try {
9994            IActivityManager am = ActivityManager.getService();
9995            if (am != null) {
9996                try {
9997                    am.killApplication(pkgName, appId, userId, reason);
9998                } catch (RemoteException e) {
9999                }
10000            }
10001        } finally {
10002            Binder.restoreCallingIdentity(token);
10003        }
10004    }
10005
10006    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10007        // Remove the parent package setting
10008        PackageSetting ps = (PackageSetting) pkg.mExtras;
10009        if (ps != null) {
10010            removePackageLI(ps, chatty);
10011        }
10012        // Remove the child package setting
10013        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10014        for (int i = 0; i < childCount; i++) {
10015            PackageParser.Package childPkg = pkg.childPackages.get(i);
10016            ps = (PackageSetting) childPkg.mExtras;
10017            if (ps != null) {
10018                removePackageLI(ps, chatty);
10019            }
10020        }
10021    }
10022
10023    void removePackageLI(PackageSetting ps, boolean chatty) {
10024        if (DEBUG_INSTALL) {
10025            if (chatty)
10026                Log.d(TAG, "Removing package " + ps.name);
10027        }
10028
10029        // writer
10030        synchronized (mPackages) {
10031            mPackages.remove(ps.name);
10032            final PackageParser.Package pkg = ps.pkg;
10033            if (pkg != null) {
10034                cleanPackageDataStructuresLILPw(pkg, chatty);
10035            }
10036        }
10037    }
10038
10039    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10040        if (DEBUG_INSTALL) {
10041            if (chatty)
10042                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10043        }
10044
10045        // writer
10046        synchronized (mPackages) {
10047            // Remove the parent package
10048            mPackages.remove(pkg.applicationInfo.packageName);
10049            cleanPackageDataStructuresLILPw(pkg, chatty);
10050
10051            // Remove the child packages
10052            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10053            for (int i = 0; i < childCount; i++) {
10054                PackageParser.Package childPkg = pkg.childPackages.get(i);
10055                mPackages.remove(childPkg.applicationInfo.packageName);
10056                cleanPackageDataStructuresLILPw(childPkg, chatty);
10057            }
10058        }
10059    }
10060
10061    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10062        int N = pkg.providers.size();
10063        StringBuilder r = null;
10064        int i;
10065        for (i=0; i<N; i++) {
10066            PackageParser.Provider p = pkg.providers.get(i);
10067            mProviders.removeProvider(p);
10068            if (p.info.authority == null) {
10069
10070                /* There was another ContentProvider with this authority when
10071                 * this app was installed so this authority is null,
10072                 * Ignore it as we don't have to unregister the provider.
10073                 */
10074                continue;
10075            }
10076            String names[] = p.info.authority.split(";");
10077            for (int j = 0; j < names.length; j++) {
10078                if (mProvidersByAuthority.get(names[j]) == p) {
10079                    mProvidersByAuthority.remove(names[j]);
10080                    if (DEBUG_REMOVE) {
10081                        if (chatty)
10082                            Log.d(TAG, "Unregistered content provider: " + names[j]
10083                                    + ", className = " + p.info.name + ", isSyncable = "
10084                                    + p.info.isSyncable);
10085                    }
10086                }
10087            }
10088            if (DEBUG_REMOVE && chatty) {
10089                if (r == null) {
10090                    r = new StringBuilder(256);
10091                } else {
10092                    r.append(' ');
10093                }
10094                r.append(p.info.name);
10095            }
10096        }
10097        if (r != null) {
10098            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10099        }
10100
10101        N = pkg.services.size();
10102        r = null;
10103        for (i=0; i<N; i++) {
10104            PackageParser.Service s = pkg.services.get(i);
10105            mServices.removeService(s);
10106            if (chatty) {
10107                if (r == null) {
10108                    r = new StringBuilder(256);
10109                } else {
10110                    r.append(' ');
10111                }
10112                r.append(s.info.name);
10113            }
10114        }
10115        if (r != null) {
10116            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10117        }
10118
10119        N = pkg.receivers.size();
10120        r = null;
10121        for (i=0; i<N; i++) {
10122            PackageParser.Activity a = pkg.receivers.get(i);
10123            mReceivers.removeActivity(a, "receiver");
10124            if (DEBUG_REMOVE && chatty) {
10125                if (r == null) {
10126                    r = new StringBuilder(256);
10127                } else {
10128                    r.append(' ');
10129                }
10130                r.append(a.info.name);
10131            }
10132        }
10133        if (r != null) {
10134            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10135        }
10136
10137        N = pkg.activities.size();
10138        r = null;
10139        for (i=0; i<N; i++) {
10140            PackageParser.Activity a = pkg.activities.get(i);
10141            mActivities.removeActivity(a, "activity");
10142            if (DEBUG_REMOVE && chatty) {
10143                if (r == null) {
10144                    r = new StringBuilder(256);
10145                } else {
10146                    r.append(' ');
10147                }
10148                r.append(a.info.name);
10149            }
10150        }
10151        if (r != null) {
10152            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10153        }
10154
10155        N = pkg.permissions.size();
10156        r = null;
10157        for (i=0; i<N; i++) {
10158            PackageParser.Permission p = pkg.permissions.get(i);
10159            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10160            if (bp == null) {
10161                bp = mSettings.mPermissionTrees.get(p.info.name);
10162            }
10163            if (bp != null && bp.perm == p) {
10164                bp.perm = null;
10165                if (DEBUG_REMOVE && chatty) {
10166                    if (r == null) {
10167                        r = new StringBuilder(256);
10168                    } else {
10169                        r.append(' ');
10170                    }
10171                    r.append(p.info.name);
10172                }
10173            }
10174            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10175                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10176                if (appOpPkgs != null) {
10177                    appOpPkgs.remove(pkg.packageName);
10178                }
10179            }
10180        }
10181        if (r != null) {
10182            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10183        }
10184
10185        N = pkg.requestedPermissions.size();
10186        r = null;
10187        for (i=0; i<N; i++) {
10188            String perm = pkg.requestedPermissions.get(i);
10189            BasePermission bp = mSettings.mPermissions.get(perm);
10190            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10191                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10192                if (appOpPkgs != null) {
10193                    appOpPkgs.remove(pkg.packageName);
10194                    if (appOpPkgs.isEmpty()) {
10195                        mAppOpPermissionPackages.remove(perm);
10196                    }
10197                }
10198            }
10199        }
10200        if (r != null) {
10201            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10202        }
10203
10204        N = pkg.instrumentation.size();
10205        r = null;
10206        for (i=0; i<N; i++) {
10207            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10208            mInstrumentation.remove(a.getComponentName());
10209            if (DEBUG_REMOVE && chatty) {
10210                if (r == null) {
10211                    r = new StringBuilder(256);
10212                } else {
10213                    r.append(' ');
10214                }
10215                r.append(a.info.name);
10216            }
10217        }
10218        if (r != null) {
10219            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10220        }
10221
10222        r = null;
10223        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10224            // Only system apps can hold shared libraries.
10225            if (pkg.libraryNames != null) {
10226                for (i=0; i<pkg.libraryNames.size(); i++) {
10227                    String name = pkg.libraryNames.get(i);
10228                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10229                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10230                        mSharedLibraries.remove(name);
10231                        if (DEBUG_REMOVE && chatty) {
10232                            if (r == null) {
10233                                r = new StringBuilder(256);
10234                            } else {
10235                                r.append(' ');
10236                            }
10237                            r.append(name);
10238                        }
10239                    }
10240                }
10241            }
10242        }
10243        if (r != null) {
10244            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10245        }
10246    }
10247
10248    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10249        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10250            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10251                return true;
10252            }
10253        }
10254        return false;
10255    }
10256
10257    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10258    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10259    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10260
10261    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10262        // Update the parent permissions
10263        updatePermissionsLPw(pkg.packageName, pkg, flags);
10264        // Update the child permissions
10265        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10266        for (int i = 0; i < childCount; i++) {
10267            PackageParser.Package childPkg = pkg.childPackages.get(i);
10268            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10269        }
10270    }
10271
10272    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10273            int flags) {
10274        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10275        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10276    }
10277
10278    private void updatePermissionsLPw(String changingPkg,
10279            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10280        // Make sure there are no dangling permission trees.
10281        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10282        while (it.hasNext()) {
10283            final BasePermission bp = it.next();
10284            if (bp.packageSetting == null) {
10285                // We may not yet have parsed the package, so just see if
10286                // we still know about its settings.
10287                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10288            }
10289            if (bp.packageSetting == null) {
10290                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10291                        + " from package " + bp.sourcePackage);
10292                it.remove();
10293            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10294                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10295                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10296                            + " from package " + bp.sourcePackage);
10297                    flags |= UPDATE_PERMISSIONS_ALL;
10298                    it.remove();
10299                }
10300            }
10301        }
10302
10303        // Make sure all dynamic permissions have been assigned to a package,
10304        // and make sure there are no dangling permissions.
10305        it = mSettings.mPermissions.values().iterator();
10306        while (it.hasNext()) {
10307            final BasePermission bp = it.next();
10308            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10309                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10310                        + bp.name + " pkg=" + bp.sourcePackage
10311                        + " info=" + bp.pendingInfo);
10312                if (bp.packageSetting == null && bp.pendingInfo != null) {
10313                    final BasePermission tree = findPermissionTreeLP(bp.name);
10314                    if (tree != null && tree.perm != null) {
10315                        bp.packageSetting = tree.packageSetting;
10316                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10317                                new PermissionInfo(bp.pendingInfo));
10318                        bp.perm.info.packageName = tree.perm.info.packageName;
10319                        bp.perm.info.name = bp.name;
10320                        bp.uid = tree.uid;
10321                    }
10322                }
10323            }
10324            if (bp.packageSetting == null) {
10325                // We may not yet have parsed the package, so just see if
10326                // we still know about its settings.
10327                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10328            }
10329            if (bp.packageSetting == null) {
10330                Slog.w(TAG, "Removing dangling permission: " + bp.name
10331                        + " from package " + bp.sourcePackage);
10332                it.remove();
10333            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10334                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10335                    Slog.i(TAG, "Removing old permission: " + bp.name
10336                            + " from package " + bp.sourcePackage);
10337                    flags |= UPDATE_PERMISSIONS_ALL;
10338                    it.remove();
10339                }
10340            }
10341        }
10342
10343        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10344        // Now update the permissions for all packages, in particular
10345        // replace the granted permissions of the system packages.
10346        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10347            for (PackageParser.Package pkg : mPackages.values()) {
10348                if (pkg != pkgInfo) {
10349                    // Only replace for packages on requested volume
10350                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10351                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10352                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10353                    grantPermissionsLPw(pkg, replace, changingPkg);
10354                }
10355            }
10356        }
10357
10358        if (pkgInfo != null) {
10359            // Only replace for packages on requested volume
10360            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10361            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10362                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10363            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10364        }
10365        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10366    }
10367
10368    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10369            String packageOfInterest) {
10370        // IMPORTANT: There are two types of permissions: install and runtime.
10371        // Install time permissions are granted when the app is installed to
10372        // all device users and users added in the future. Runtime permissions
10373        // are granted at runtime explicitly to specific users. Normal and signature
10374        // protected permissions are install time permissions. Dangerous permissions
10375        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10376        // otherwise they are runtime permissions. This function does not manage
10377        // runtime permissions except for the case an app targeting Lollipop MR1
10378        // being upgraded to target a newer SDK, in which case dangerous permissions
10379        // are transformed from install time to runtime ones.
10380
10381        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10382        if (ps == null) {
10383            return;
10384        }
10385
10386        PermissionsState permissionsState = ps.getPermissionsState();
10387        PermissionsState origPermissions = permissionsState;
10388
10389        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10390
10391        boolean runtimePermissionsRevoked = false;
10392        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10393
10394        boolean changedInstallPermission = false;
10395
10396        if (replace) {
10397            ps.installPermissionsFixed = false;
10398            if (!ps.isSharedUser()) {
10399                origPermissions = new PermissionsState(permissionsState);
10400                permissionsState.reset();
10401            } else {
10402                // We need to know only about runtime permission changes since the
10403                // calling code always writes the install permissions state but
10404                // the runtime ones are written only if changed. The only cases of
10405                // changed runtime permissions here are promotion of an install to
10406                // runtime and revocation of a runtime from a shared user.
10407                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10408                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10409                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10410                    runtimePermissionsRevoked = true;
10411                }
10412            }
10413        }
10414
10415        permissionsState.setGlobalGids(mGlobalGids);
10416
10417        final int N = pkg.requestedPermissions.size();
10418        for (int i=0; i<N; i++) {
10419            final String name = pkg.requestedPermissions.get(i);
10420            final BasePermission bp = mSettings.mPermissions.get(name);
10421
10422            if (DEBUG_INSTALL) {
10423                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10424            }
10425
10426            if (bp == null || bp.packageSetting == null) {
10427                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10428                    Slog.w(TAG, "Unknown permission " + name
10429                            + " in package " + pkg.packageName);
10430                }
10431                continue;
10432            }
10433
10434
10435            // Limit ephemeral apps to ephemeral allowed permissions.
10436            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10437                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10438                        + pkg.packageName);
10439                continue;
10440            }
10441
10442            final String perm = bp.name;
10443            boolean allowedSig = false;
10444            int grant = GRANT_DENIED;
10445
10446            // Keep track of app op permissions.
10447            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10448                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10449                if (pkgs == null) {
10450                    pkgs = new ArraySet<>();
10451                    mAppOpPermissionPackages.put(bp.name, pkgs);
10452                }
10453                pkgs.add(pkg.packageName);
10454            }
10455
10456            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10457            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10458                    >= Build.VERSION_CODES.M;
10459            switch (level) {
10460                case PermissionInfo.PROTECTION_NORMAL: {
10461                    // For all apps normal permissions are install time ones.
10462                    grant = GRANT_INSTALL;
10463                } break;
10464
10465                case PermissionInfo.PROTECTION_DANGEROUS: {
10466                    // If a permission review is required for legacy apps we represent
10467                    // their permissions as always granted runtime ones since we need
10468                    // to keep the review required permission flag per user while an
10469                    // install permission's state is shared across all users.
10470                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10471                        // For legacy apps dangerous permissions are install time ones.
10472                        grant = GRANT_INSTALL;
10473                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10474                        // For legacy apps that became modern, install becomes runtime.
10475                        grant = GRANT_UPGRADE;
10476                    } else if (mPromoteSystemApps
10477                            && isSystemApp(ps)
10478                            && mExistingSystemPackages.contains(ps.name)) {
10479                        // For legacy system apps, install becomes runtime.
10480                        // We cannot check hasInstallPermission() for system apps since those
10481                        // permissions were granted implicitly and not persisted pre-M.
10482                        grant = GRANT_UPGRADE;
10483                    } else {
10484                        // For modern apps keep runtime permissions unchanged.
10485                        grant = GRANT_RUNTIME;
10486                    }
10487                } break;
10488
10489                case PermissionInfo.PROTECTION_SIGNATURE: {
10490                    // For all apps signature permissions are install time ones.
10491                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10492                    if (allowedSig) {
10493                        grant = GRANT_INSTALL;
10494                    }
10495                } break;
10496            }
10497
10498            if (DEBUG_INSTALL) {
10499                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10500            }
10501
10502            if (grant != GRANT_DENIED) {
10503                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10504                    // If this is an existing, non-system package, then
10505                    // we can't add any new permissions to it.
10506                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10507                        // Except...  if this is a permission that was added
10508                        // to the platform (note: need to only do this when
10509                        // updating the platform).
10510                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10511                            grant = GRANT_DENIED;
10512                        }
10513                    }
10514                }
10515
10516                switch (grant) {
10517                    case GRANT_INSTALL: {
10518                        // Revoke this as runtime permission to handle the case of
10519                        // a runtime permission being downgraded to an install one.
10520                        // Also in permission review mode we keep dangerous permissions
10521                        // for legacy apps
10522                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10523                            if (origPermissions.getRuntimePermissionState(
10524                                    bp.name, userId) != null) {
10525                                // Revoke the runtime permission and clear the flags.
10526                                origPermissions.revokeRuntimePermission(bp, userId);
10527                                origPermissions.updatePermissionFlags(bp, userId,
10528                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10529                                // If we revoked a permission permission, we have to write.
10530                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10531                                        changedRuntimePermissionUserIds, userId);
10532                            }
10533                        }
10534                        // Grant an install permission.
10535                        if (permissionsState.grantInstallPermission(bp) !=
10536                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10537                            changedInstallPermission = true;
10538                        }
10539                    } break;
10540
10541                    case GRANT_RUNTIME: {
10542                        // Grant previously granted runtime permissions.
10543                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10544                            PermissionState permissionState = origPermissions
10545                                    .getRuntimePermissionState(bp.name, userId);
10546                            int flags = permissionState != null
10547                                    ? permissionState.getFlags() : 0;
10548                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10549                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10550                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10551                                    // If we cannot put the permission as it was, we have to write.
10552                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10553                                            changedRuntimePermissionUserIds, userId);
10554                                }
10555                                // If the app supports runtime permissions no need for a review.
10556                                if (mPermissionReviewRequired
10557                                        && appSupportsRuntimePermissions
10558                                        && (flags & PackageManager
10559                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10560                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10561                                    // Since we changed the flags, we have to write.
10562                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10563                                            changedRuntimePermissionUserIds, userId);
10564                                }
10565                            } else if (mPermissionReviewRequired
10566                                    && !appSupportsRuntimePermissions) {
10567                                // For legacy apps that need a permission review, every new
10568                                // runtime permission is granted but it is pending a review.
10569                                // We also need to review only platform defined runtime
10570                                // permissions as these are the only ones the platform knows
10571                                // how to disable the API to simulate revocation as legacy
10572                                // apps don't expect to run with revoked permissions.
10573                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10574                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10575                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10576                                        // We changed the flags, hence have to write.
10577                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10578                                                changedRuntimePermissionUserIds, userId);
10579                                    }
10580                                }
10581                                if (permissionsState.grantRuntimePermission(bp, userId)
10582                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10583                                    // We changed the permission, hence have to write.
10584                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10585                                            changedRuntimePermissionUserIds, userId);
10586                                }
10587                            }
10588                            // Propagate the permission flags.
10589                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10590                        }
10591                    } break;
10592
10593                    case GRANT_UPGRADE: {
10594                        // Grant runtime permissions for a previously held install permission.
10595                        PermissionState permissionState = origPermissions
10596                                .getInstallPermissionState(bp.name);
10597                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10598
10599                        if (origPermissions.revokeInstallPermission(bp)
10600                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10601                            // We will be transferring the permission flags, so clear them.
10602                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10603                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10604                            changedInstallPermission = true;
10605                        }
10606
10607                        // If the permission is not to be promoted to runtime we ignore it and
10608                        // also its other flags as they are not applicable to install permissions.
10609                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10610                            for (int userId : currentUserIds) {
10611                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10612                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10613                                    // Transfer the permission flags.
10614                                    permissionsState.updatePermissionFlags(bp, userId,
10615                                            flags, flags);
10616                                    // If we granted the permission, we have to write.
10617                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10618                                            changedRuntimePermissionUserIds, userId);
10619                                }
10620                            }
10621                        }
10622                    } break;
10623
10624                    default: {
10625                        if (packageOfInterest == null
10626                                || packageOfInterest.equals(pkg.packageName)) {
10627                            Slog.w(TAG, "Not granting permission " + perm
10628                                    + " to package " + pkg.packageName
10629                                    + " because it was previously installed without");
10630                        }
10631                    } break;
10632                }
10633            } else {
10634                if (permissionsState.revokeInstallPermission(bp) !=
10635                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10636                    // Also drop the permission flags.
10637                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10638                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10639                    changedInstallPermission = true;
10640                    Slog.i(TAG, "Un-granting permission " + perm
10641                            + " from package " + pkg.packageName
10642                            + " (protectionLevel=" + bp.protectionLevel
10643                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10644                            + ")");
10645                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10646                    // Don't print warning for app op permissions, since it is fine for them
10647                    // not to be granted, there is a UI for the user to decide.
10648                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10649                        Slog.w(TAG, "Not granting permission " + perm
10650                                + " to package " + pkg.packageName
10651                                + " (protectionLevel=" + bp.protectionLevel
10652                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10653                                + ")");
10654                    }
10655                }
10656            }
10657        }
10658
10659        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10660                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10661            // This is the first that we have heard about this package, so the
10662            // permissions we have now selected are fixed until explicitly
10663            // changed.
10664            ps.installPermissionsFixed = true;
10665        }
10666
10667        // Persist the runtime permissions state for users with changes. If permissions
10668        // were revoked because no app in the shared user declares them we have to
10669        // write synchronously to avoid losing runtime permissions state.
10670        for (int userId : changedRuntimePermissionUserIds) {
10671            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10672        }
10673    }
10674
10675    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10676        boolean allowed = false;
10677        final int NP = PackageParser.NEW_PERMISSIONS.length;
10678        for (int ip=0; ip<NP; ip++) {
10679            final PackageParser.NewPermissionInfo npi
10680                    = PackageParser.NEW_PERMISSIONS[ip];
10681            if (npi.name.equals(perm)
10682                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10683                allowed = true;
10684                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10685                        + pkg.packageName);
10686                break;
10687            }
10688        }
10689        return allowed;
10690    }
10691
10692    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10693            BasePermission bp, PermissionsState origPermissions) {
10694        boolean privilegedPermission = (bp.protectionLevel
10695                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10696        boolean privappPermissionsDisable =
10697                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10698        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10699        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10700        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10701                && !platformPackage && platformPermission) {
10702            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10703                    .getPrivAppPermissions(pkg.packageName);
10704            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10705            if (!whitelisted) {
10706                Slog.w(TAG, "Privileged permission " + perm + " for package "
10707                        + pkg.packageName + " - not in privapp-permissions whitelist");
10708                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10709                    return false;
10710                }
10711            }
10712        }
10713        boolean allowed = (compareSignatures(
10714                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10715                        == PackageManager.SIGNATURE_MATCH)
10716                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10717                        == PackageManager.SIGNATURE_MATCH);
10718        if (!allowed && privilegedPermission) {
10719            if (isSystemApp(pkg)) {
10720                // For updated system applications, a system permission
10721                // is granted only if it had been defined by the original application.
10722                if (pkg.isUpdatedSystemApp()) {
10723                    final PackageSetting sysPs = mSettings
10724                            .getDisabledSystemPkgLPr(pkg.packageName);
10725                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10726                        // If the original was granted this permission, we take
10727                        // that grant decision as read and propagate it to the
10728                        // update.
10729                        if (sysPs.isPrivileged()) {
10730                            allowed = true;
10731                        }
10732                    } else {
10733                        // The system apk may have been updated with an older
10734                        // version of the one on the data partition, but which
10735                        // granted a new system permission that it didn't have
10736                        // before.  In this case we do want to allow the app to
10737                        // now get the new permission if the ancestral apk is
10738                        // privileged to get it.
10739                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10740                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10741                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10742                                    allowed = true;
10743                                    break;
10744                                }
10745                            }
10746                        }
10747                        // Also if a privileged parent package on the system image or any of
10748                        // its children requested a privileged permission, the updated child
10749                        // packages can also get the permission.
10750                        if (pkg.parentPackage != null) {
10751                            final PackageSetting disabledSysParentPs = mSettings
10752                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10753                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10754                                    && disabledSysParentPs.isPrivileged()) {
10755                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10756                                    allowed = true;
10757                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10758                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10759                                    for (int i = 0; i < count; i++) {
10760                                        PackageParser.Package disabledSysChildPkg =
10761                                                disabledSysParentPs.pkg.childPackages.get(i);
10762                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10763                                                perm)) {
10764                                            allowed = true;
10765                                            break;
10766                                        }
10767                                    }
10768                                }
10769                            }
10770                        }
10771                    }
10772                } else {
10773                    allowed = isPrivilegedApp(pkg);
10774                }
10775            }
10776        }
10777        if (!allowed) {
10778            if (!allowed && (bp.protectionLevel
10779                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10780                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10781                // If this was a previously normal/dangerous permission that got moved
10782                // to a system permission as part of the runtime permission redesign, then
10783                // we still want to blindly grant it to old apps.
10784                allowed = true;
10785            }
10786            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10787                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10788                // If this permission is to be granted to the system installer and
10789                // this app is an installer, then it gets the permission.
10790                allowed = true;
10791            }
10792            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10793                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10794                // If this permission is to be granted to the system verifier and
10795                // this app is a verifier, then it gets the permission.
10796                allowed = true;
10797            }
10798            if (!allowed && (bp.protectionLevel
10799                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10800                    && isSystemApp(pkg)) {
10801                // Any pre-installed system app is allowed to get this permission.
10802                allowed = true;
10803            }
10804            if (!allowed && (bp.protectionLevel
10805                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10806                // For development permissions, a development permission
10807                // is granted only if it was already granted.
10808                allowed = origPermissions.hasInstallPermission(perm);
10809            }
10810            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10811                    && pkg.packageName.equals(mSetupWizardPackage)) {
10812                // If this permission is to be granted to the system setup wizard and
10813                // this app is a setup wizard, then it gets the permission.
10814                allowed = true;
10815            }
10816        }
10817        return allowed;
10818    }
10819
10820    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10821        final int permCount = pkg.requestedPermissions.size();
10822        for (int j = 0; j < permCount; j++) {
10823            String requestedPermission = pkg.requestedPermissions.get(j);
10824            if (permission.equals(requestedPermission)) {
10825                return true;
10826            }
10827        }
10828        return false;
10829    }
10830
10831    final class ActivityIntentResolver
10832            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10833        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10834                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10835            if (!sUserManager.exists(userId)) return null;
10836            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10837                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10838                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10839            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10840                    isEphemeral, userId);
10841        }
10842
10843        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10844                int userId) {
10845            if (!sUserManager.exists(userId)) return null;
10846            mFlags = flags;
10847            return super.queryIntent(intent, resolvedType,
10848                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10849                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10850                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10851        }
10852
10853        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10854                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10855            if (!sUserManager.exists(userId)) return null;
10856            if (packageActivities == null) {
10857                return null;
10858            }
10859            mFlags = flags;
10860            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10861            final boolean vislbleToEphemeral =
10862                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10863            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10864            final int N = packageActivities.size();
10865            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10866                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10867
10868            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10869            for (int i = 0; i < N; ++i) {
10870                intentFilters = packageActivities.get(i).intents;
10871                if (intentFilters != null && intentFilters.size() > 0) {
10872                    PackageParser.ActivityIntentInfo[] array =
10873                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10874                    intentFilters.toArray(array);
10875                    listCut.add(array);
10876                }
10877            }
10878            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10879                    vislbleToEphemeral, isEphemeral, listCut, userId);
10880        }
10881
10882        /**
10883         * Finds a privileged activity that matches the specified activity names.
10884         */
10885        private PackageParser.Activity findMatchingActivity(
10886                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10887            for (PackageParser.Activity sysActivity : activityList) {
10888                if (sysActivity.info.name.equals(activityInfo.name)) {
10889                    return sysActivity;
10890                }
10891                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10892                    return sysActivity;
10893                }
10894                if (sysActivity.info.targetActivity != null) {
10895                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10896                        return sysActivity;
10897                    }
10898                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10899                        return sysActivity;
10900                    }
10901                }
10902            }
10903            return null;
10904        }
10905
10906        public class IterGenerator<E> {
10907            public Iterator<E> generate(ActivityIntentInfo info) {
10908                return null;
10909            }
10910        }
10911
10912        public class ActionIterGenerator extends IterGenerator<String> {
10913            @Override
10914            public Iterator<String> generate(ActivityIntentInfo info) {
10915                return info.actionsIterator();
10916            }
10917        }
10918
10919        public class CategoriesIterGenerator extends IterGenerator<String> {
10920            @Override
10921            public Iterator<String> generate(ActivityIntentInfo info) {
10922                return info.categoriesIterator();
10923            }
10924        }
10925
10926        public class SchemesIterGenerator extends IterGenerator<String> {
10927            @Override
10928            public Iterator<String> generate(ActivityIntentInfo info) {
10929                return info.schemesIterator();
10930            }
10931        }
10932
10933        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10934            @Override
10935            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10936                return info.authoritiesIterator();
10937            }
10938        }
10939
10940        /**
10941         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10942         * MODIFIED. Do not pass in a list that should not be changed.
10943         */
10944        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10945                IterGenerator<T> generator, Iterator<T> searchIterator) {
10946            // loop through the set of actions; every one must be found in the intent filter
10947            while (searchIterator.hasNext()) {
10948                // we must have at least one filter in the list to consider a match
10949                if (intentList.size() == 0) {
10950                    break;
10951                }
10952
10953                final T searchAction = searchIterator.next();
10954
10955                // loop through the set of intent filters
10956                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10957                while (intentIter.hasNext()) {
10958                    final ActivityIntentInfo intentInfo = intentIter.next();
10959                    boolean selectionFound = false;
10960
10961                    // loop through the intent filter's selection criteria; at least one
10962                    // of them must match the searched criteria
10963                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10964                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10965                        final T intentSelection = intentSelectionIter.next();
10966                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10967                            selectionFound = true;
10968                            break;
10969                        }
10970                    }
10971
10972                    // the selection criteria wasn't found in this filter's set; this filter
10973                    // is not a potential match
10974                    if (!selectionFound) {
10975                        intentIter.remove();
10976                    }
10977                }
10978            }
10979        }
10980
10981        private boolean isProtectedAction(ActivityIntentInfo filter) {
10982            final Iterator<String> actionsIter = filter.actionsIterator();
10983            while (actionsIter != null && actionsIter.hasNext()) {
10984                final String filterAction = actionsIter.next();
10985                if (PROTECTED_ACTIONS.contains(filterAction)) {
10986                    return true;
10987                }
10988            }
10989            return false;
10990        }
10991
10992        /**
10993         * Adjusts the priority of the given intent filter according to policy.
10994         * <p>
10995         * <ul>
10996         * <li>The priority for non privileged applications is capped to '0'</li>
10997         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10998         * <li>The priority for unbundled updates to privileged applications is capped to the
10999         *      priority defined on the system partition</li>
11000         * </ul>
11001         * <p>
11002         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11003         * allowed to obtain any priority on any action.
11004         */
11005        private void adjustPriority(
11006                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11007            // nothing to do; priority is fine as-is
11008            if (intent.getPriority() <= 0) {
11009                return;
11010            }
11011
11012            final ActivityInfo activityInfo = intent.activity.info;
11013            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11014
11015            final boolean privilegedApp =
11016                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11017            if (!privilegedApp) {
11018                // non-privileged applications can never define a priority >0
11019                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11020                        + " package: " + applicationInfo.packageName
11021                        + " activity: " + intent.activity.className
11022                        + " origPrio: " + intent.getPriority());
11023                intent.setPriority(0);
11024                return;
11025            }
11026
11027            if (systemActivities == null) {
11028                // the system package is not disabled; we're parsing the system partition
11029                if (isProtectedAction(intent)) {
11030                    if (mDeferProtectedFilters) {
11031                        // We can't deal with these just yet. No component should ever obtain a
11032                        // >0 priority for a protected actions, with ONE exception -- the setup
11033                        // wizard. The setup wizard, however, cannot be known until we're able to
11034                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11035                        // until all intent filters have been processed. Chicken, meet egg.
11036                        // Let the filter temporarily have a high priority and rectify the
11037                        // priorities after all system packages have been scanned.
11038                        mProtectedFilters.add(intent);
11039                        if (DEBUG_FILTERS) {
11040                            Slog.i(TAG, "Protected action; save for later;"
11041                                    + " package: " + applicationInfo.packageName
11042                                    + " activity: " + intent.activity.className
11043                                    + " origPrio: " + intent.getPriority());
11044                        }
11045                        return;
11046                    } else {
11047                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11048                            Slog.i(TAG, "No setup wizard;"
11049                                + " All protected intents capped to priority 0");
11050                        }
11051                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11052                            if (DEBUG_FILTERS) {
11053                                Slog.i(TAG, "Found setup wizard;"
11054                                    + " allow priority " + intent.getPriority() + ";"
11055                                    + " package: " + intent.activity.info.packageName
11056                                    + " activity: " + intent.activity.className
11057                                    + " priority: " + intent.getPriority());
11058                            }
11059                            // setup wizard gets whatever it wants
11060                            return;
11061                        }
11062                        Slog.w(TAG, "Protected action; cap priority to 0;"
11063                                + " package: " + intent.activity.info.packageName
11064                                + " activity: " + intent.activity.className
11065                                + " origPrio: " + intent.getPriority());
11066                        intent.setPriority(0);
11067                        return;
11068                    }
11069                }
11070                // privileged apps on the system image get whatever priority they request
11071                return;
11072            }
11073
11074            // privileged app unbundled update ... try to find the same activity
11075            final PackageParser.Activity foundActivity =
11076                    findMatchingActivity(systemActivities, activityInfo);
11077            if (foundActivity == null) {
11078                // this is a new activity; it cannot obtain >0 priority
11079                if (DEBUG_FILTERS) {
11080                    Slog.i(TAG, "New activity; cap priority to 0;"
11081                            + " package: " + applicationInfo.packageName
11082                            + " activity: " + intent.activity.className
11083                            + " origPrio: " + intent.getPriority());
11084                }
11085                intent.setPriority(0);
11086                return;
11087            }
11088
11089            // found activity, now check for filter equivalence
11090
11091            // a shallow copy is enough; we modify the list, not its contents
11092            final List<ActivityIntentInfo> intentListCopy =
11093                    new ArrayList<>(foundActivity.intents);
11094            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11095
11096            // find matching action subsets
11097            final Iterator<String> actionsIterator = intent.actionsIterator();
11098            if (actionsIterator != null) {
11099                getIntentListSubset(
11100                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11101                if (intentListCopy.size() == 0) {
11102                    // no more intents to match; we're not equivalent
11103                    if (DEBUG_FILTERS) {
11104                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11105                                + " package: " + applicationInfo.packageName
11106                                + " activity: " + intent.activity.className
11107                                + " origPrio: " + intent.getPriority());
11108                    }
11109                    intent.setPriority(0);
11110                    return;
11111                }
11112            }
11113
11114            // find matching category subsets
11115            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11116            if (categoriesIterator != null) {
11117                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11118                        categoriesIterator);
11119                if (intentListCopy.size() == 0) {
11120                    // no more intents to match; we're not equivalent
11121                    if (DEBUG_FILTERS) {
11122                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11123                                + " package: " + applicationInfo.packageName
11124                                + " activity: " + intent.activity.className
11125                                + " origPrio: " + intent.getPriority());
11126                    }
11127                    intent.setPriority(0);
11128                    return;
11129                }
11130            }
11131
11132            // find matching schemes subsets
11133            final Iterator<String> schemesIterator = intent.schemesIterator();
11134            if (schemesIterator != null) {
11135                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11136                        schemesIterator);
11137                if (intentListCopy.size() == 0) {
11138                    // no more intents to match; we're not equivalent
11139                    if (DEBUG_FILTERS) {
11140                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11141                                + " package: " + applicationInfo.packageName
11142                                + " activity: " + intent.activity.className
11143                                + " origPrio: " + intent.getPriority());
11144                    }
11145                    intent.setPriority(0);
11146                    return;
11147                }
11148            }
11149
11150            // find matching authorities subsets
11151            final Iterator<IntentFilter.AuthorityEntry>
11152                    authoritiesIterator = intent.authoritiesIterator();
11153            if (authoritiesIterator != null) {
11154                getIntentListSubset(intentListCopy,
11155                        new AuthoritiesIterGenerator(),
11156                        authoritiesIterator);
11157                if (intentListCopy.size() == 0) {
11158                    // no more intents to match; we're not equivalent
11159                    if (DEBUG_FILTERS) {
11160                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11161                                + " package: " + applicationInfo.packageName
11162                                + " activity: " + intent.activity.className
11163                                + " origPrio: " + intent.getPriority());
11164                    }
11165                    intent.setPriority(0);
11166                    return;
11167                }
11168            }
11169
11170            // we found matching filter(s); app gets the max priority of all intents
11171            int cappedPriority = 0;
11172            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11173                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11174            }
11175            if (intent.getPriority() > cappedPriority) {
11176                if (DEBUG_FILTERS) {
11177                    Slog.i(TAG, "Found matching filter(s);"
11178                            + " cap priority to " + cappedPriority + ";"
11179                            + " package: " + applicationInfo.packageName
11180                            + " activity: " + intent.activity.className
11181                            + " origPrio: " + intent.getPriority());
11182                }
11183                intent.setPriority(cappedPriority);
11184                return;
11185            }
11186            // all this for nothing; the requested priority was <= what was on the system
11187        }
11188
11189        public final void addActivity(PackageParser.Activity a, String type) {
11190            mActivities.put(a.getComponentName(), a);
11191            if (DEBUG_SHOW_INFO)
11192                Log.v(
11193                TAG, "  " + type + " " +
11194                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11195            if (DEBUG_SHOW_INFO)
11196                Log.v(TAG, "    Class=" + a.info.name);
11197            final int NI = a.intents.size();
11198            for (int j=0; j<NI; j++) {
11199                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11200                if ("activity".equals(type)) {
11201                    final PackageSetting ps =
11202                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11203                    final List<PackageParser.Activity> systemActivities =
11204                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11205                    adjustPriority(systemActivities, intent);
11206                }
11207                if (DEBUG_SHOW_INFO) {
11208                    Log.v(TAG, "    IntentFilter:");
11209                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11210                }
11211                if (!intent.debugCheck()) {
11212                    Log.w(TAG, "==> For Activity " + a.info.name);
11213                }
11214                addFilter(intent);
11215            }
11216        }
11217
11218        public final void removeActivity(PackageParser.Activity a, String type) {
11219            mActivities.remove(a.getComponentName());
11220            if (DEBUG_SHOW_INFO) {
11221                Log.v(TAG, "  " + type + " "
11222                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11223                                : a.info.name) + ":");
11224                Log.v(TAG, "    Class=" + a.info.name);
11225            }
11226            final int NI = a.intents.size();
11227            for (int j=0; j<NI; j++) {
11228                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11229                if (DEBUG_SHOW_INFO) {
11230                    Log.v(TAG, "    IntentFilter:");
11231                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11232                }
11233                removeFilter(intent);
11234            }
11235        }
11236
11237        @Override
11238        protected boolean allowFilterResult(
11239                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11240            ActivityInfo filterAi = filter.activity.info;
11241            for (int i=dest.size()-1; i>=0; i--) {
11242                ActivityInfo destAi = dest.get(i).activityInfo;
11243                if (destAi.name == filterAi.name
11244                        && destAi.packageName == filterAi.packageName) {
11245                    return false;
11246                }
11247            }
11248            return true;
11249        }
11250
11251        @Override
11252        protected ActivityIntentInfo[] newArray(int size) {
11253            return new ActivityIntentInfo[size];
11254        }
11255
11256        @Override
11257        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11258            if (!sUserManager.exists(userId)) return true;
11259            PackageParser.Package p = filter.activity.owner;
11260            if (p != null) {
11261                PackageSetting ps = (PackageSetting)p.mExtras;
11262                if (ps != null) {
11263                    // System apps are never considered stopped for purposes of
11264                    // filtering, because there may be no way for the user to
11265                    // actually re-launch them.
11266                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11267                            && ps.getStopped(userId);
11268                }
11269            }
11270            return false;
11271        }
11272
11273        @Override
11274        protected boolean isPackageForFilter(String packageName,
11275                PackageParser.ActivityIntentInfo info) {
11276            return packageName.equals(info.activity.owner.packageName);
11277        }
11278
11279        @Override
11280        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11281                int match, int userId) {
11282            if (!sUserManager.exists(userId)) return null;
11283            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11284                return null;
11285            }
11286            final PackageParser.Activity activity = info.activity;
11287            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11288            if (ps == null) {
11289                return null;
11290            }
11291            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11292                    ps.readUserState(userId), userId);
11293            if (ai == null) {
11294                return null;
11295            }
11296            final ResolveInfo res = new ResolveInfo();
11297            res.activityInfo = ai;
11298            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11299                res.filter = info;
11300            }
11301            if (info != null) {
11302                res.handleAllWebDataURI = info.handleAllWebDataURI();
11303            }
11304            res.priority = info.getPriority();
11305            res.preferredOrder = activity.owner.mPreferredOrder;
11306            //System.out.println("Result: " + res.activityInfo.className +
11307            //                   " = " + res.priority);
11308            res.match = match;
11309            res.isDefault = info.hasDefault;
11310            res.labelRes = info.labelRes;
11311            res.nonLocalizedLabel = info.nonLocalizedLabel;
11312            if (userNeedsBadging(userId)) {
11313                res.noResourceId = true;
11314            } else {
11315                res.icon = info.icon;
11316            }
11317            res.iconResourceId = info.icon;
11318            res.system = res.activityInfo.applicationInfo.isSystemApp();
11319            return res;
11320        }
11321
11322        @Override
11323        protected void sortResults(List<ResolveInfo> results) {
11324            Collections.sort(results, mResolvePrioritySorter);
11325        }
11326
11327        @Override
11328        protected void dumpFilter(PrintWriter out, String prefix,
11329                PackageParser.ActivityIntentInfo filter) {
11330            out.print(prefix); out.print(
11331                    Integer.toHexString(System.identityHashCode(filter.activity)));
11332                    out.print(' ');
11333                    filter.activity.printComponentShortName(out);
11334                    out.print(" filter ");
11335                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11336        }
11337
11338        @Override
11339        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11340            return filter.activity;
11341        }
11342
11343        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11344            PackageParser.Activity activity = (PackageParser.Activity)label;
11345            out.print(prefix); out.print(
11346                    Integer.toHexString(System.identityHashCode(activity)));
11347                    out.print(' ');
11348                    activity.printComponentShortName(out);
11349            if (count > 1) {
11350                out.print(" ("); out.print(count); out.print(" filters)");
11351            }
11352            out.println();
11353        }
11354
11355        // Keys are String (activity class name), values are Activity.
11356        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11357                = new ArrayMap<ComponentName, PackageParser.Activity>();
11358        private int mFlags;
11359    }
11360
11361    private final class ServiceIntentResolver
11362            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11363        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11364                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11365            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11366            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11367                    isEphemeral, userId);
11368        }
11369
11370        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11371                int userId) {
11372            if (!sUserManager.exists(userId)) return null;
11373            mFlags = flags;
11374            return super.queryIntent(intent, resolvedType,
11375                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11376                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11377                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11378        }
11379
11380        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11381                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11382            if (!sUserManager.exists(userId)) return null;
11383            if (packageServices == null) {
11384                return null;
11385            }
11386            mFlags = flags;
11387            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11388            final boolean vislbleToEphemeral =
11389                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11390            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11391            final int N = packageServices.size();
11392            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11393                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11394
11395            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11396            for (int i = 0; i < N; ++i) {
11397                intentFilters = packageServices.get(i).intents;
11398                if (intentFilters != null && intentFilters.size() > 0) {
11399                    PackageParser.ServiceIntentInfo[] array =
11400                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11401                    intentFilters.toArray(array);
11402                    listCut.add(array);
11403                }
11404            }
11405            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11406                    vislbleToEphemeral, isEphemeral, listCut, userId);
11407        }
11408
11409        public final void addService(PackageParser.Service s) {
11410            mServices.put(s.getComponentName(), s);
11411            if (DEBUG_SHOW_INFO) {
11412                Log.v(TAG, "  "
11413                        + (s.info.nonLocalizedLabel != null
11414                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11415                Log.v(TAG, "    Class=" + s.info.name);
11416            }
11417            final int NI = s.intents.size();
11418            int j;
11419            for (j=0; j<NI; j++) {
11420                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11421                if (DEBUG_SHOW_INFO) {
11422                    Log.v(TAG, "    IntentFilter:");
11423                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11424                }
11425                if (!intent.debugCheck()) {
11426                    Log.w(TAG, "==> For Service " + s.info.name);
11427                }
11428                addFilter(intent);
11429            }
11430        }
11431
11432        public final void removeService(PackageParser.Service s) {
11433            mServices.remove(s.getComponentName());
11434            if (DEBUG_SHOW_INFO) {
11435                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11436                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11437                Log.v(TAG, "    Class=" + s.info.name);
11438            }
11439            final int NI = s.intents.size();
11440            int j;
11441            for (j=0; j<NI; j++) {
11442                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11443                if (DEBUG_SHOW_INFO) {
11444                    Log.v(TAG, "    IntentFilter:");
11445                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11446                }
11447                removeFilter(intent);
11448            }
11449        }
11450
11451        @Override
11452        protected boolean allowFilterResult(
11453                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11454            ServiceInfo filterSi = filter.service.info;
11455            for (int i=dest.size()-1; i>=0; i--) {
11456                ServiceInfo destAi = dest.get(i).serviceInfo;
11457                if (destAi.name == filterSi.name
11458                        && destAi.packageName == filterSi.packageName) {
11459                    return false;
11460                }
11461            }
11462            return true;
11463        }
11464
11465        @Override
11466        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11467            return new PackageParser.ServiceIntentInfo[size];
11468        }
11469
11470        @Override
11471        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11472            if (!sUserManager.exists(userId)) return true;
11473            PackageParser.Package p = filter.service.owner;
11474            if (p != null) {
11475                PackageSetting ps = (PackageSetting)p.mExtras;
11476                if (ps != null) {
11477                    // System apps are never considered stopped for purposes of
11478                    // filtering, because there may be no way for the user to
11479                    // actually re-launch them.
11480                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11481                            && ps.getStopped(userId);
11482                }
11483            }
11484            return false;
11485        }
11486
11487        @Override
11488        protected boolean isPackageForFilter(String packageName,
11489                PackageParser.ServiceIntentInfo info) {
11490            return packageName.equals(info.service.owner.packageName);
11491        }
11492
11493        @Override
11494        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11495                int match, int userId) {
11496            if (!sUserManager.exists(userId)) return null;
11497            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11498            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11499                return null;
11500            }
11501            final PackageParser.Service service = info.service;
11502            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11503            if (ps == null) {
11504                return null;
11505            }
11506            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11507                    ps.readUserState(userId), userId);
11508            if (si == null) {
11509                return null;
11510            }
11511            final ResolveInfo res = new ResolveInfo();
11512            res.serviceInfo = si;
11513            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11514                res.filter = filter;
11515            }
11516            res.priority = info.getPriority();
11517            res.preferredOrder = service.owner.mPreferredOrder;
11518            res.match = match;
11519            res.isDefault = info.hasDefault;
11520            res.labelRes = info.labelRes;
11521            res.nonLocalizedLabel = info.nonLocalizedLabel;
11522            res.icon = info.icon;
11523            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11524            return res;
11525        }
11526
11527        @Override
11528        protected void sortResults(List<ResolveInfo> results) {
11529            Collections.sort(results, mResolvePrioritySorter);
11530        }
11531
11532        @Override
11533        protected void dumpFilter(PrintWriter out, String prefix,
11534                PackageParser.ServiceIntentInfo filter) {
11535            out.print(prefix); out.print(
11536                    Integer.toHexString(System.identityHashCode(filter.service)));
11537                    out.print(' ');
11538                    filter.service.printComponentShortName(out);
11539                    out.print(" filter ");
11540                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11541        }
11542
11543        @Override
11544        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11545            return filter.service;
11546        }
11547
11548        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11549            PackageParser.Service service = (PackageParser.Service)label;
11550            out.print(prefix); out.print(
11551                    Integer.toHexString(System.identityHashCode(service)));
11552                    out.print(' ');
11553                    service.printComponentShortName(out);
11554            if (count > 1) {
11555                out.print(" ("); out.print(count); out.print(" filters)");
11556            }
11557            out.println();
11558        }
11559
11560//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11561//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11562//            final List<ResolveInfo> retList = Lists.newArrayList();
11563//            while (i.hasNext()) {
11564//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11565//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11566//                    retList.add(resolveInfo);
11567//                }
11568//            }
11569//            return retList;
11570//        }
11571
11572        // Keys are String (activity class name), values are Activity.
11573        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11574                = new ArrayMap<ComponentName, PackageParser.Service>();
11575        private int mFlags;
11576    }
11577
11578    private final class ProviderIntentResolver
11579            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11580        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11581                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11582            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11583            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11584                    isEphemeral, userId);
11585        }
11586
11587        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11588                int userId) {
11589            if (!sUserManager.exists(userId))
11590                return null;
11591            mFlags = flags;
11592            return super.queryIntent(intent, resolvedType,
11593                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11594                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11595                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11596        }
11597
11598        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11599                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11600            if (!sUserManager.exists(userId))
11601                return null;
11602            if (packageProviders == null) {
11603                return null;
11604            }
11605            mFlags = flags;
11606            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11607            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11608            final boolean vislbleToEphemeral =
11609                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11610            final int N = packageProviders.size();
11611            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11612                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11613
11614            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11615            for (int i = 0; i < N; ++i) {
11616                intentFilters = packageProviders.get(i).intents;
11617                if (intentFilters != null && intentFilters.size() > 0) {
11618                    PackageParser.ProviderIntentInfo[] array =
11619                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11620                    intentFilters.toArray(array);
11621                    listCut.add(array);
11622                }
11623            }
11624            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11625                    vislbleToEphemeral, isEphemeral, listCut, userId);
11626        }
11627
11628        public final void addProvider(PackageParser.Provider p) {
11629            if (mProviders.containsKey(p.getComponentName())) {
11630                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11631                return;
11632            }
11633
11634            mProviders.put(p.getComponentName(), p);
11635            if (DEBUG_SHOW_INFO) {
11636                Log.v(TAG, "  "
11637                        + (p.info.nonLocalizedLabel != null
11638                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11639                Log.v(TAG, "    Class=" + p.info.name);
11640            }
11641            final int NI = p.intents.size();
11642            int j;
11643            for (j = 0; j < NI; j++) {
11644                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11645                if (DEBUG_SHOW_INFO) {
11646                    Log.v(TAG, "    IntentFilter:");
11647                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11648                }
11649                if (!intent.debugCheck()) {
11650                    Log.w(TAG, "==> For Provider " + p.info.name);
11651                }
11652                addFilter(intent);
11653            }
11654        }
11655
11656        public final void removeProvider(PackageParser.Provider p) {
11657            mProviders.remove(p.getComponentName());
11658            if (DEBUG_SHOW_INFO) {
11659                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11660                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11661                Log.v(TAG, "    Class=" + p.info.name);
11662            }
11663            final int NI = p.intents.size();
11664            int j;
11665            for (j = 0; j < NI; j++) {
11666                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11667                if (DEBUG_SHOW_INFO) {
11668                    Log.v(TAG, "    IntentFilter:");
11669                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11670                }
11671                removeFilter(intent);
11672            }
11673        }
11674
11675        @Override
11676        protected boolean allowFilterResult(
11677                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11678            ProviderInfo filterPi = filter.provider.info;
11679            for (int i = dest.size() - 1; i >= 0; i--) {
11680                ProviderInfo destPi = dest.get(i).providerInfo;
11681                if (destPi.name == filterPi.name
11682                        && destPi.packageName == filterPi.packageName) {
11683                    return false;
11684                }
11685            }
11686            return true;
11687        }
11688
11689        @Override
11690        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11691            return new PackageParser.ProviderIntentInfo[size];
11692        }
11693
11694        @Override
11695        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11696            if (!sUserManager.exists(userId))
11697                return true;
11698            PackageParser.Package p = filter.provider.owner;
11699            if (p != null) {
11700                PackageSetting ps = (PackageSetting) p.mExtras;
11701                if (ps != null) {
11702                    // System apps are never considered stopped for purposes of
11703                    // filtering, because there may be no way for the user to
11704                    // actually re-launch them.
11705                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11706                            && ps.getStopped(userId);
11707                }
11708            }
11709            return false;
11710        }
11711
11712        @Override
11713        protected boolean isPackageForFilter(String packageName,
11714                PackageParser.ProviderIntentInfo info) {
11715            return packageName.equals(info.provider.owner.packageName);
11716        }
11717
11718        @Override
11719        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11720                int match, int userId) {
11721            if (!sUserManager.exists(userId))
11722                return null;
11723            final PackageParser.ProviderIntentInfo info = filter;
11724            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11725                return null;
11726            }
11727            final PackageParser.Provider provider = info.provider;
11728            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11729            if (ps == null) {
11730                return null;
11731            }
11732            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11733                    ps.readUserState(userId), userId);
11734            if (pi == null) {
11735                return null;
11736            }
11737            final ResolveInfo res = new ResolveInfo();
11738            res.providerInfo = pi;
11739            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11740                res.filter = filter;
11741            }
11742            res.priority = info.getPriority();
11743            res.preferredOrder = provider.owner.mPreferredOrder;
11744            res.match = match;
11745            res.isDefault = info.hasDefault;
11746            res.labelRes = info.labelRes;
11747            res.nonLocalizedLabel = info.nonLocalizedLabel;
11748            res.icon = info.icon;
11749            res.system = res.providerInfo.applicationInfo.isSystemApp();
11750            return res;
11751        }
11752
11753        @Override
11754        protected void sortResults(List<ResolveInfo> results) {
11755            Collections.sort(results, mResolvePrioritySorter);
11756        }
11757
11758        @Override
11759        protected void dumpFilter(PrintWriter out, String prefix,
11760                PackageParser.ProviderIntentInfo filter) {
11761            out.print(prefix);
11762            out.print(
11763                    Integer.toHexString(System.identityHashCode(filter.provider)));
11764            out.print(' ');
11765            filter.provider.printComponentShortName(out);
11766            out.print(" filter ");
11767            out.println(Integer.toHexString(System.identityHashCode(filter)));
11768        }
11769
11770        @Override
11771        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11772            return filter.provider;
11773        }
11774
11775        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11776            PackageParser.Provider provider = (PackageParser.Provider)label;
11777            out.print(prefix); out.print(
11778                    Integer.toHexString(System.identityHashCode(provider)));
11779                    out.print(' ');
11780                    provider.printComponentShortName(out);
11781            if (count > 1) {
11782                out.print(" ("); out.print(count); out.print(" filters)");
11783            }
11784            out.println();
11785        }
11786
11787        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11788                = new ArrayMap<ComponentName, PackageParser.Provider>();
11789        private int mFlags;
11790    }
11791
11792    static final class EphemeralIntentResolver
11793            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11794        /**
11795         * The result that has the highest defined order. Ordering applies on a
11796         * per-package basis. Mapping is from package name to Pair of order and
11797         * EphemeralResolveInfo.
11798         * <p>
11799         * NOTE: This is implemented as a field variable for convenience and efficiency.
11800         * By having a field variable, we're able to track filter ordering as soon as
11801         * a non-zero order is defined. Otherwise, multiple loops across the result set
11802         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11803         * this needs to be contained entirely within {@link #filterResults()}.
11804         */
11805        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11806
11807        @Override
11808        protected EphemeralResponse[] newArray(int size) {
11809            return new EphemeralResponse[size];
11810        }
11811
11812        @Override
11813        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11814            return true;
11815        }
11816
11817        @Override
11818        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11819                int userId) {
11820            if (!sUserManager.exists(userId)) {
11821                return null;
11822            }
11823            final String packageName = responseObj.resolveInfo.getPackageName();
11824            final Integer order = responseObj.getOrder();
11825            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11826                    mOrderResult.get(packageName);
11827            // ordering is enabled and this item's order isn't high enough
11828            if (lastOrderResult != null && lastOrderResult.first >= order) {
11829                return null;
11830            }
11831            final EphemeralResolveInfo res = responseObj.resolveInfo;
11832            if (order > 0) {
11833                // non-zero order, enable ordering
11834                mOrderResult.put(packageName, new Pair<>(order, res));
11835            }
11836            return responseObj;
11837        }
11838
11839        @Override
11840        protected void filterResults(List<EphemeralResponse> results) {
11841            // only do work if ordering is enabled [most of the time it won't be]
11842            if (mOrderResult.size() == 0) {
11843                return;
11844            }
11845            int resultSize = results.size();
11846            for (int i = 0; i < resultSize; i++) {
11847                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11848                final String packageName = info.getPackageName();
11849                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11850                if (savedInfo == null) {
11851                    // package doesn't having ordering
11852                    continue;
11853                }
11854                if (savedInfo.second == info) {
11855                    // circled back to the highest ordered item; remove from order list
11856                    mOrderResult.remove(savedInfo);
11857                    if (mOrderResult.size() == 0) {
11858                        // no more ordered items
11859                        break;
11860                    }
11861                    continue;
11862                }
11863                // item has a worse order, remove it from the result list
11864                results.remove(i);
11865                resultSize--;
11866                i--;
11867            }
11868        }
11869    }
11870
11871    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11872            new Comparator<ResolveInfo>() {
11873        public int compare(ResolveInfo r1, ResolveInfo r2) {
11874            int v1 = r1.priority;
11875            int v2 = r2.priority;
11876            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11877            if (v1 != v2) {
11878                return (v1 > v2) ? -1 : 1;
11879            }
11880            v1 = r1.preferredOrder;
11881            v2 = r2.preferredOrder;
11882            if (v1 != v2) {
11883                return (v1 > v2) ? -1 : 1;
11884            }
11885            if (r1.isDefault != r2.isDefault) {
11886                return r1.isDefault ? -1 : 1;
11887            }
11888            v1 = r1.match;
11889            v2 = r2.match;
11890            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11891            if (v1 != v2) {
11892                return (v1 > v2) ? -1 : 1;
11893            }
11894            if (r1.system != r2.system) {
11895                return r1.system ? -1 : 1;
11896            }
11897            if (r1.activityInfo != null) {
11898                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11899            }
11900            if (r1.serviceInfo != null) {
11901                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11902            }
11903            if (r1.providerInfo != null) {
11904                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11905            }
11906            return 0;
11907        }
11908    };
11909
11910    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11911            new Comparator<ProviderInfo>() {
11912        public int compare(ProviderInfo p1, ProviderInfo p2) {
11913            final int v1 = p1.initOrder;
11914            final int v2 = p2.initOrder;
11915            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11916        }
11917    };
11918
11919    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11920            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11921            final int[] userIds) {
11922        mHandler.post(new Runnable() {
11923            @Override
11924            public void run() {
11925                try {
11926                    final IActivityManager am = ActivityManager.getService();
11927                    if (am == null) return;
11928                    final int[] resolvedUserIds;
11929                    if (userIds == null) {
11930                        resolvedUserIds = am.getRunningUserIds();
11931                    } else {
11932                        resolvedUserIds = userIds;
11933                    }
11934                    for (int id : resolvedUserIds) {
11935                        final Intent intent = new Intent(action,
11936                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11937                        if (extras != null) {
11938                            intent.putExtras(extras);
11939                        }
11940                        if (targetPkg != null) {
11941                            intent.setPackage(targetPkg);
11942                        }
11943                        // Modify the UID when posting to other users
11944                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11945                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11946                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11947                            intent.putExtra(Intent.EXTRA_UID, uid);
11948                        }
11949                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11950                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11951                        if (DEBUG_BROADCASTS) {
11952                            RuntimeException here = new RuntimeException("here");
11953                            here.fillInStackTrace();
11954                            Slog.d(TAG, "Sending to user " + id + ": "
11955                                    + intent.toShortString(false, true, false, false)
11956                                    + " " + intent.getExtras(), here);
11957                        }
11958                        am.broadcastIntent(null, intent, null, finishedReceiver,
11959                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11960                                null, finishedReceiver != null, false, id);
11961                    }
11962                } catch (RemoteException ex) {
11963                }
11964            }
11965        });
11966    }
11967
11968    /**
11969     * Check if the external storage media is available. This is true if there
11970     * is a mounted external storage medium or if the external storage is
11971     * emulated.
11972     */
11973    private boolean isExternalMediaAvailable() {
11974        return mMediaMounted || Environment.isExternalStorageEmulated();
11975    }
11976
11977    @Override
11978    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11979        // writer
11980        synchronized (mPackages) {
11981            if (!isExternalMediaAvailable()) {
11982                // If the external storage is no longer mounted at this point,
11983                // the caller may not have been able to delete all of this
11984                // packages files and can not delete any more.  Bail.
11985                return null;
11986            }
11987            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11988            if (lastPackage != null) {
11989                pkgs.remove(lastPackage);
11990            }
11991            if (pkgs.size() > 0) {
11992                return pkgs.get(0);
11993            }
11994        }
11995        return null;
11996    }
11997
11998    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11999        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12000                userId, andCode ? 1 : 0, packageName);
12001        if (mSystemReady) {
12002            msg.sendToTarget();
12003        } else {
12004            if (mPostSystemReadyMessages == null) {
12005                mPostSystemReadyMessages = new ArrayList<>();
12006            }
12007            mPostSystemReadyMessages.add(msg);
12008        }
12009    }
12010
12011    void startCleaningPackages() {
12012        // reader
12013        if (!isExternalMediaAvailable()) {
12014            return;
12015        }
12016        synchronized (mPackages) {
12017            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12018                return;
12019            }
12020        }
12021        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12022        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12023        IActivityManager am = ActivityManager.getService();
12024        if (am != null) {
12025            try {
12026                am.startService(null, intent, null, mContext.getOpPackageName(),
12027                        UserHandle.USER_SYSTEM);
12028            } catch (RemoteException e) {
12029            }
12030        }
12031    }
12032
12033    @Override
12034    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12035            int installFlags, String installerPackageName, int userId) {
12036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12037
12038        final int callingUid = Binder.getCallingUid();
12039        enforceCrossUserPermission(callingUid, userId,
12040                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12041
12042        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12043            try {
12044                if (observer != null) {
12045                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12046                }
12047            } catch (RemoteException re) {
12048            }
12049            return;
12050        }
12051
12052        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12053            installFlags |= PackageManager.INSTALL_FROM_ADB;
12054
12055        } else {
12056            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12057            // about installerPackageName.
12058
12059            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12060            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12061        }
12062
12063        UserHandle user;
12064        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12065            user = UserHandle.ALL;
12066        } else {
12067            user = new UserHandle(userId);
12068        }
12069
12070        // Only system components can circumvent runtime permissions when installing.
12071        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12072                && mContext.checkCallingOrSelfPermission(Manifest.permission
12073                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12074            throw new SecurityException("You need the "
12075                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12076                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12077        }
12078
12079        final File originFile = new File(originPath);
12080        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12081
12082        final Message msg = mHandler.obtainMessage(INIT_COPY);
12083        final VerificationInfo verificationInfo = new VerificationInfo(
12084                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12085        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12086                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12087                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12088                null /*certificates*/);
12089        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12090        msg.obj = params;
12091
12092        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12093                System.identityHashCode(msg.obj));
12094        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12095                System.identityHashCode(msg.obj));
12096
12097        mHandler.sendMessage(msg);
12098    }
12099
12100    void installStage(String packageName, File stagedDir, String stagedCid,
12101            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12102            String installerPackageName, int installerUid, UserHandle user,
12103            Certificate[][] certificates) {
12104        if (DEBUG_EPHEMERAL) {
12105            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12106                Slog.d(TAG, "Ephemeral install of " + packageName);
12107            }
12108        }
12109        final VerificationInfo verificationInfo = new VerificationInfo(
12110                sessionParams.originatingUri, sessionParams.referrerUri,
12111                sessionParams.originatingUid, installerUid);
12112
12113        final OriginInfo origin;
12114        if (stagedDir != null) {
12115            origin = OriginInfo.fromStagedFile(stagedDir);
12116        } else {
12117            origin = OriginInfo.fromStagedContainer(stagedCid);
12118        }
12119
12120        final Message msg = mHandler.obtainMessage(INIT_COPY);
12121        final InstallParams params = new InstallParams(origin, null, observer,
12122                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12123                verificationInfo, user, sessionParams.abiOverride,
12124                sessionParams.grantedRuntimePermissions, certificates);
12125        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12126        msg.obj = params;
12127
12128        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12129                System.identityHashCode(msg.obj));
12130        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12131                System.identityHashCode(msg.obj));
12132
12133        mHandler.sendMessage(msg);
12134    }
12135
12136    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12137            int userId) {
12138        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12139        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12140    }
12141
12142    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12143            int appId, int... userIds) {
12144        if (ArrayUtils.isEmpty(userIds)) {
12145            return;
12146        }
12147        Bundle extras = new Bundle(1);
12148        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12149        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12150
12151        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12152                packageName, extras, 0, null, null, userIds);
12153        if (isSystem) {
12154            mHandler.post(() -> {
12155                        for (int userId : userIds) {
12156                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12157                        }
12158                    }
12159            );
12160        }
12161    }
12162
12163    /**
12164     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12165     * automatically without needing an explicit launch.
12166     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12167     */
12168    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12169        // If user is not running, the app didn't miss any broadcast
12170        if (!mUserManagerInternal.isUserRunning(userId)) {
12171            return;
12172        }
12173        final IActivityManager am = ActivityManager.getService();
12174        try {
12175            // Deliver LOCKED_BOOT_COMPLETED first
12176            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12177                    .setPackage(packageName);
12178            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12179            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12180                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12181
12182            // Deliver BOOT_COMPLETED only if user is unlocked
12183            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12184                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12185                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12186                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12187            }
12188        } catch (RemoteException e) {
12189            throw e.rethrowFromSystemServer();
12190        }
12191    }
12192
12193    @Override
12194    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12195            int userId) {
12196        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12197        PackageSetting pkgSetting;
12198        final int uid = Binder.getCallingUid();
12199        enforceCrossUserPermission(uid, userId,
12200                true /* requireFullPermission */, true /* checkShell */,
12201                "setApplicationHiddenSetting for user " + userId);
12202
12203        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12204            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12205            return false;
12206        }
12207
12208        long callingId = Binder.clearCallingIdentity();
12209        try {
12210            boolean sendAdded = false;
12211            boolean sendRemoved = false;
12212            // writer
12213            synchronized (mPackages) {
12214                pkgSetting = mSettings.mPackages.get(packageName);
12215                if (pkgSetting == null) {
12216                    return false;
12217                }
12218                // Do not allow "android" is being disabled
12219                if ("android".equals(packageName)) {
12220                    Slog.w(TAG, "Cannot hide package: android");
12221                    return false;
12222                }
12223                // Only allow protected packages to hide themselves.
12224                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12225                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12226                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12227                    return false;
12228                }
12229
12230                if (pkgSetting.getHidden(userId) != hidden) {
12231                    pkgSetting.setHidden(hidden, userId);
12232                    mSettings.writePackageRestrictionsLPr(userId);
12233                    if (hidden) {
12234                        sendRemoved = true;
12235                    } else {
12236                        sendAdded = true;
12237                    }
12238                }
12239            }
12240            if (sendAdded) {
12241                sendPackageAddedForUser(packageName, pkgSetting, userId);
12242                return true;
12243            }
12244            if (sendRemoved) {
12245                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12246                        "hiding pkg");
12247                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12248                return true;
12249            }
12250        } finally {
12251            Binder.restoreCallingIdentity(callingId);
12252        }
12253        return false;
12254    }
12255
12256    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12257            int userId) {
12258        final PackageRemovedInfo info = new PackageRemovedInfo();
12259        info.removedPackage = packageName;
12260        info.removedUsers = new int[] {userId};
12261        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12262        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12263    }
12264
12265    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12266        if (pkgList.length > 0) {
12267            Bundle extras = new Bundle(1);
12268            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12269
12270            sendPackageBroadcast(
12271                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12272                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12273                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12274                    new int[] {userId});
12275        }
12276    }
12277
12278    /**
12279     * Returns true if application is not found or there was an error. Otherwise it returns
12280     * the hidden state of the package for the given user.
12281     */
12282    @Override
12283    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12284        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12286                true /* requireFullPermission */, false /* checkShell */,
12287                "getApplicationHidden for user " + userId);
12288        PackageSetting pkgSetting;
12289        long callingId = Binder.clearCallingIdentity();
12290        try {
12291            // writer
12292            synchronized (mPackages) {
12293                pkgSetting = mSettings.mPackages.get(packageName);
12294                if (pkgSetting == null) {
12295                    return true;
12296                }
12297                return pkgSetting.getHidden(userId);
12298            }
12299        } finally {
12300            Binder.restoreCallingIdentity(callingId);
12301        }
12302    }
12303
12304    /**
12305     * @hide
12306     */
12307    @Override
12308    public int installExistingPackageAsUser(String packageName, int userId) {
12309        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12310                null);
12311        PackageSetting pkgSetting;
12312        final int uid = Binder.getCallingUid();
12313        enforceCrossUserPermission(uid, userId,
12314                true /* requireFullPermission */, true /* checkShell */,
12315                "installExistingPackage for user " + userId);
12316        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12317            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12318        }
12319
12320        long callingId = Binder.clearCallingIdentity();
12321        try {
12322            boolean installed = false;
12323
12324            // writer
12325            synchronized (mPackages) {
12326                pkgSetting = mSettings.mPackages.get(packageName);
12327                if (pkgSetting == null) {
12328                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12329                }
12330                if (!pkgSetting.getInstalled(userId)) {
12331                    pkgSetting.setInstalled(true, userId);
12332                    pkgSetting.setHidden(false, userId);
12333                    mSettings.writePackageRestrictionsLPr(userId);
12334                    installed = true;
12335                }
12336            }
12337
12338            if (installed) {
12339                if (pkgSetting.pkg != null) {
12340                    synchronized (mInstallLock) {
12341                        // We don't need to freeze for a brand new install
12342                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12343                    }
12344                }
12345                sendPackageAddedForUser(packageName, pkgSetting, userId);
12346            }
12347        } finally {
12348            Binder.restoreCallingIdentity(callingId);
12349        }
12350
12351        return PackageManager.INSTALL_SUCCEEDED;
12352    }
12353
12354    boolean isUserRestricted(int userId, String restrictionKey) {
12355        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12356        if (restrictions.getBoolean(restrictionKey, false)) {
12357            Log.w(TAG, "User is restricted: " + restrictionKey);
12358            return true;
12359        }
12360        return false;
12361    }
12362
12363    @Override
12364    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12365            int userId) {
12366        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12367        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12368                true /* requireFullPermission */, true /* checkShell */,
12369                "setPackagesSuspended for user " + userId);
12370
12371        if (ArrayUtils.isEmpty(packageNames)) {
12372            return packageNames;
12373        }
12374
12375        // List of package names for whom the suspended state has changed.
12376        List<String> changedPackages = new ArrayList<>(packageNames.length);
12377        // List of package names for whom the suspended state is not set as requested in this
12378        // method.
12379        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12380        long callingId = Binder.clearCallingIdentity();
12381        try {
12382            for (int i = 0; i < packageNames.length; i++) {
12383                String packageName = packageNames[i];
12384                boolean changed = false;
12385                final int appId;
12386                synchronized (mPackages) {
12387                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12388                    if (pkgSetting == null) {
12389                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12390                                + "\". Skipping suspending/un-suspending.");
12391                        unactionedPackages.add(packageName);
12392                        continue;
12393                    }
12394                    appId = pkgSetting.appId;
12395                    if (pkgSetting.getSuspended(userId) != suspended) {
12396                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12397                            unactionedPackages.add(packageName);
12398                            continue;
12399                        }
12400                        pkgSetting.setSuspended(suspended, userId);
12401                        mSettings.writePackageRestrictionsLPr(userId);
12402                        changed = true;
12403                        changedPackages.add(packageName);
12404                    }
12405                }
12406
12407                if (changed && suspended) {
12408                    killApplication(packageName, UserHandle.getUid(userId, appId),
12409                            "suspending package");
12410                }
12411            }
12412        } finally {
12413            Binder.restoreCallingIdentity(callingId);
12414        }
12415
12416        if (!changedPackages.isEmpty()) {
12417            sendPackagesSuspendedForUser(changedPackages.toArray(
12418                    new String[changedPackages.size()]), userId, suspended);
12419        }
12420
12421        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12422    }
12423
12424    @Override
12425    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12426        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12427                true /* requireFullPermission */, false /* checkShell */,
12428                "isPackageSuspendedForUser for user " + userId);
12429        synchronized (mPackages) {
12430            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12431            if (pkgSetting == null) {
12432                throw new IllegalArgumentException("Unknown target package: " + packageName);
12433            }
12434            return pkgSetting.getSuspended(userId);
12435        }
12436    }
12437
12438    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12439        if (isPackageDeviceAdmin(packageName, userId)) {
12440            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12441                    + "\": has an active device admin");
12442            return false;
12443        }
12444
12445        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12446        if (packageName.equals(activeLauncherPackageName)) {
12447            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12448                    + "\": contains the active launcher");
12449            return false;
12450        }
12451
12452        if (packageName.equals(mRequiredInstallerPackage)) {
12453            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12454                    + "\": required for package installation");
12455            return false;
12456        }
12457
12458        if (packageName.equals(mRequiredUninstallerPackage)) {
12459            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12460                    + "\": required for package uninstallation");
12461            return false;
12462        }
12463
12464        if (packageName.equals(mRequiredVerifierPackage)) {
12465            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12466                    + "\": required for package verification");
12467            return false;
12468        }
12469
12470        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12471            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12472                    + "\": is the default dialer");
12473            return false;
12474        }
12475
12476        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12477            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12478                    + "\": protected package");
12479            return false;
12480        }
12481
12482        return true;
12483    }
12484
12485    private String getActiveLauncherPackageName(int userId) {
12486        Intent intent = new Intent(Intent.ACTION_MAIN);
12487        intent.addCategory(Intent.CATEGORY_HOME);
12488        ResolveInfo resolveInfo = resolveIntent(
12489                intent,
12490                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12491                PackageManager.MATCH_DEFAULT_ONLY,
12492                userId);
12493
12494        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12495    }
12496
12497    private String getDefaultDialerPackageName(int userId) {
12498        synchronized (mPackages) {
12499            return mSettings.getDefaultDialerPackageNameLPw(userId);
12500        }
12501    }
12502
12503    @Override
12504    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12505        mContext.enforceCallingOrSelfPermission(
12506                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12507                "Only package verification agents can verify applications");
12508
12509        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12510        final PackageVerificationResponse response = new PackageVerificationResponse(
12511                verificationCode, Binder.getCallingUid());
12512        msg.arg1 = id;
12513        msg.obj = response;
12514        mHandler.sendMessage(msg);
12515    }
12516
12517    @Override
12518    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12519            long millisecondsToDelay) {
12520        mContext.enforceCallingOrSelfPermission(
12521                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12522                "Only package verification agents can extend verification timeouts");
12523
12524        final PackageVerificationState state = mPendingVerification.get(id);
12525        final PackageVerificationResponse response = new PackageVerificationResponse(
12526                verificationCodeAtTimeout, Binder.getCallingUid());
12527
12528        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12529            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12530        }
12531        if (millisecondsToDelay < 0) {
12532            millisecondsToDelay = 0;
12533        }
12534        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12535                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12536            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12537        }
12538
12539        if ((state != null) && !state.timeoutExtended()) {
12540            state.extendTimeout();
12541
12542            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12543            msg.arg1 = id;
12544            msg.obj = response;
12545            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12546        }
12547    }
12548
12549    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12550            int verificationCode, UserHandle user) {
12551        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12552        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12553        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12554        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12555        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12556
12557        mContext.sendBroadcastAsUser(intent, user,
12558                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12559    }
12560
12561    private ComponentName matchComponentForVerifier(String packageName,
12562            List<ResolveInfo> receivers) {
12563        ActivityInfo targetReceiver = null;
12564
12565        final int NR = receivers.size();
12566        for (int i = 0; i < NR; i++) {
12567            final ResolveInfo info = receivers.get(i);
12568            if (info.activityInfo == null) {
12569                continue;
12570            }
12571
12572            if (packageName.equals(info.activityInfo.packageName)) {
12573                targetReceiver = info.activityInfo;
12574                break;
12575            }
12576        }
12577
12578        if (targetReceiver == null) {
12579            return null;
12580        }
12581
12582        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12583    }
12584
12585    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12586            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12587        if (pkgInfo.verifiers.length == 0) {
12588            return null;
12589        }
12590
12591        final int N = pkgInfo.verifiers.length;
12592        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12593        for (int i = 0; i < N; i++) {
12594            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12595
12596            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12597                    receivers);
12598            if (comp == null) {
12599                continue;
12600            }
12601
12602            final int verifierUid = getUidForVerifier(verifierInfo);
12603            if (verifierUid == -1) {
12604                continue;
12605            }
12606
12607            if (DEBUG_VERIFY) {
12608                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12609                        + " with the correct signature");
12610            }
12611            sufficientVerifiers.add(comp);
12612            verificationState.addSufficientVerifier(verifierUid);
12613        }
12614
12615        return sufficientVerifiers;
12616    }
12617
12618    private int getUidForVerifier(VerifierInfo verifierInfo) {
12619        synchronized (mPackages) {
12620            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12621            if (pkg == null) {
12622                return -1;
12623            } else if (pkg.mSignatures.length != 1) {
12624                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12625                        + " has more than one signature; ignoring");
12626                return -1;
12627            }
12628
12629            /*
12630             * If the public key of the package's signature does not match
12631             * our expected public key, then this is a different package and
12632             * we should skip.
12633             */
12634
12635            final byte[] expectedPublicKey;
12636            try {
12637                final Signature verifierSig = pkg.mSignatures[0];
12638                final PublicKey publicKey = verifierSig.getPublicKey();
12639                expectedPublicKey = publicKey.getEncoded();
12640            } catch (CertificateException e) {
12641                return -1;
12642            }
12643
12644            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12645
12646            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12647                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12648                        + " does not have the expected public key; ignoring");
12649                return -1;
12650            }
12651
12652            return pkg.applicationInfo.uid;
12653        }
12654    }
12655
12656    @Override
12657    public void finishPackageInstall(int token, boolean didLaunch) {
12658        enforceSystemOrRoot("Only the system is allowed to finish installs");
12659
12660        if (DEBUG_INSTALL) {
12661            Slog.v(TAG, "BM finishing package install for " + token);
12662        }
12663        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12664
12665        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12666        mHandler.sendMessage(msg);
12667    }
12668
12669    /**
12670     * Get the verification agent timeout.
12671     *
12672     * @return verification timeout in milliseconds
12673     */
12674    private long getVerificationTimeout() {
12675        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12676                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12677                DEFAULT_VERIFICATION_TIMEOUT);
12678    }
12679
12680    /**
12681     * Get the default verification agent response code.
12682     *
12683     * @return default verification response code
12684     */
12685    private int getDefaultVerificationResponse() {
12686        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12687                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12688                DEFAULT_VERIFICATION_RESPONSE);
12689    }
12690
12691    /**
12692     * Check whether or not package verification has been enabled.
12693     *
12694     * @return true if verification should be performed
12695     */
12696    private boolean isVerificationEnabled(int userId, int installFlags) {
12697        if (!DEFAULT_VERIFY_ENABLE) {
12698            return false;
12699        }
12700        // Ephemeral apps don't get the full verification treatment
12701        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12702            if (DEBUG_EPHEMERAL) {
12703                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12704            }
12705            return false;
12706        }
12707
12708        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12709
12710        // Check if installing from ADB
12711        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12712            // Do not run verification in a test harness environment
12713            if (ActivityManager.isRunningInTestHarness()) {
12714                return false;
12715            }
12716            if (ensureVerifyAppsEnabled) {
12717                return true;
12718            }
12719            // Check if the developer does not want package verification for ADB installs
12720            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12721                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12722                return false;
12723            }
12724        }
12725
12726        if (ensureVerifyAppsEnabled) {
12727            return true;
12728        }
12729
12730        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12731                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12732    }
12733
12734    @Override
12735    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12736            throws RemoteException {
12737        mContext.enforceCallingOrSelfPermission(
12738                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12739                "Only intentfilter verification agents can verify applications");
12740
12741        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12742        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12743                Binder.getCallingUid(), verificationCode, failedDomains);
12744        msg.arg1 = id;
12745        msg.obj = response;
12746        mHandler.sendMessage(msg);
12747    }
12748
12749    @Override
12750    public int getIntentVerificationStatus(String packageName, int userId) {
12751        synchronized (mPackages) {
12752            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12753        }
12754    }
12755
12756    @Override
12757    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12758        mContext.enforceCallingOrSelfPermission(
12759                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12760
12761        boolean result = false;
12762        synchronized (mPackages) {
12763            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12764        }
12765        if (result) {
12766            scheduleWritePackageRestrictionsLocked(userId);
12767        }
12768        return result;
12769    }
12770
12771    @Override
12772    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12773            String packageName) {
12774        synchronized (mPackages) {
12775            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12776        }
12777    }
12778
12779    @Override
12780    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12781        if (TextUtils.isEmpty(packageName)) {
12782            return ParceledListSlice.emptyList();
12783        }
12784        synchronized (mPackages) {
12785            PackageParser.Package pkg = mPackages.get(packageName);
12786            if (pkg == null || pkg.activities == null) {
12787                return ParceledListSlice.emptyList();
12788            }
12789            final int count = pkg.activities.size();
12790            ArrayList<IntentFilter> result = new ArrayList<>();
12791            for (int n=0; n<count; n++) {
12792                PackageParser.Activity activity = pkg.activities.get(n);
12793                if (activity.intents != null && activity.intents.size() > 0) {
12794                    result.addAll(activity.intents);
12795                }
12796            }
12797            return new ParceledListSlice<>(result);
12798        }
12799    }
12800
12801    @Override
12802    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12803        mContext.enforceCallingOrSelfPermission(
12804                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12805
12806        synchronized (mPackages) {
12807            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12808            if (packageName != null) {
12809                result |= updateIntentVerificationStatus(packageName,
12810                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12811                        userId);
12812                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12813                        packageName, userId);
12814            }
12815            return result;
12816        }
12817    }
12818
12819    @Override
12820    public String getDefaultBrowserPackageName(int userId) {
12821        synchronized (mPackages) {
12822            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12823        }
12824    }
12825
12826    /**
12827     * Get the "allow unknown sources" setting.
12828     *
12829     * @return the current "allow unknown sources" setting
12830     */
12831    private int getUnknownSourcesSettings() {
12832        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12833                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12834                -1);
12835    }
12836
12837    @Override
12838    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12839        final int uid = Binder.getCallingUid();
12840        // writer
12841        synchronized (mPackages) {
12842            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12843            if (targetPackageSetting == null) {
12844                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12845            }
12846
12847            PackageSetting installerPackageSetting;
12848            if (installerPackageName != null) {
12849                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12850                if (installerPackageSetting == null) {
12851                    throw new IllegalArgumentException("Unknown installer package: "
12852                            + installerPackageName);
12853                }
12854            } else {
12855                installerPackageSetting = null;
12856            }
12857
12858            Signature[] callerSignature;
12859            Object obj = mSettings.getUserIdLPr(uid);
12860            if (obj != null) {
12861                if (obj instanceof SharedUserSetting) {
12862                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12863                } else if (obj instanceof PackageSetting) {
12864                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12865                } else {
12866                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12867                }
12868            } else {
12869                throw new SecurityException("Unknown calling UID: " + uid);
12870            }
12871
12872            // Verify: can't set installerPackageName to a package that is
12873            // not signed with the same cert as the caller.
12874            if (installerPackageSetting != null) {
12875                if (compareSignatures(callerSignature,
12876                        installerPackageSetting.signatures.mSignatures)
12877                        != PackageManager.SIGNATURE_MATCH) {
12878                    throw new SecurityException(
12879                            "Caller does not have same cert as new installer package "
12880                            + installerPackageName);
12881                }
12882            }
12883
12884            // Verify: if target already has an installer package, it must
12885            // be signed with the same cert as the caller.
12886            if (targetPackageSetting.installerPackageName != null) {
12887                PackageSetting setting = mSettings.mPackages.get(
12888                        targetPackageSetting.installerPackageName);
12889                // If the currently set package isn't valid, then it's always
12890                // okay to change it.
12891                if (setting != null) {
12892                    if (compareSignatures(callerSignature,
12893                            setting.signatures.mSignatures)
12894                            != PackageManager.SIGNATURE_MATCH) {
12895                        throw new SecurityException(
12896                                "Caller does not have same cert as old installer package "
12897                                + targetPackageSetting.installerPackageName);
12898                    }
12899                }
12900            }
12901
12902            // Okay!
12903            targetPackageSetting.installerPackageName = installerPackageName;
12904            if (installerPackageName != null) {
12905                mSettings.mInstallerPackages.add(installerPackageName);
12906            }
12907            scheduleWriteSettingsLocked();
12908        }
12909    }
12910
12911    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12912        // Queue up an async operation since the package installation may take a little while.
12913        mHandler.post(new Runnable() {
12914            public void run() {
12915                mHandler.removeCallbacks(this);
12916                 // Result object to be returned
12917                PackageInstalledInfo res = new PackageInstalledInfo();
12918                res.setReturnCode(currentStatus);
12919                res.uid = -1;
12920                res.pkg = null;
12921                res.removedInfo = null;
12922                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12923                    args.doPreInstall(res.returnCode);
12924                    synchronized (mInstallLock) {
12925                        installPackageTracedLI(args, res);
12926                    }
12927                    args.doPostInstall(res.returnCode, res.uid);
12928                }
12929
12930                // A restore should be performed at this point if (a) the install
12931                // succeeded, (b) the operation is not an update, and (c) the new
12932                // package has not opted out of backup participation.
12933                final boolean update = res.removedInfo != null
12934                        && res.removedInfo.removedPackage != null;
12935                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12936                boolean doRestore = !update
12937                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12938
12939                // Set up the post-install work request bookkeeping.  This will be used
12940                // and cleaned up by the post-install event handling regardless of whether
12941                // there's a restore pass performed.  Token values are >= 1.
12942                int token;
12943                if (mNextInstallToken < 0) mNextInstallToken = 1;
12944                token = mNextInstallToken++;
12945
12946                PostInstallData data = new PostInstallData(args, res);
12947                mRunningInstalls.put(token, data);
12948                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12949
12950                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12951                    // Pass responsibility to the Backup Manager.  It will perform a
12952                    // restore if appropriate, then pass responsibility back to the
12953                    // Package Manager to run the post-install observer callbacks
12954                    // and broadcasts.
12955                    IBackupManager bm = IBackupManager.Stub.asInterface(
12956                            ServiceManager.getService(Context.BACKUP_SERVICE));
12957                    if (bm != null) {
12958                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12959                                + " to BM for possible restore");
12960                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12961                        try {
12962                            // TODO: http://b/22388012
12963                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12964                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12965                            } else {
12966                                doRestore = false;
12967                            }
12968                        } catch (RemoteException e) {
12969                            // can't happen; the backup manager is local
12970                        } catch (Exception e) {
12971                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12972                            doRestore = false;
12973                        }
12974                    } else {
12975                        Slog.e(TAG, "Backup Manager not found!");
12976                        doRestore = false;
12977                    }
12978                }
12979
12980                if (!doRestore) {
12981                    // No restore possible, or the Backup Manager was mysteriously not
12982                    // available -- just fire the post-install work request directly.
12983                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12984
12985                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12986
12987                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12988                    mHandler.sendMessage(msg);
12989                }
12990            }
12991        });
12992    }
12993
12994    /**
12995     * Callback from PackageSettings whenever an app is first transitioned out of the
12996     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12997     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12998     * here whether the app is the target of an ongoing install, and only send the
12999     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13000     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13001     * handling.
13002     */
13003    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13004        // Serialize this with the rest of the install-process message chain.  In the
13005        // restore-at-install case, this Runnable will necessarily run before the
13006        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13007        // are coherent.  In the non-restore case, the app has already completed install
13008        // and been launched through some other means, so it is not in a problematic
13009        // state for observers to see the FIRST_LAUNCH signal.
13010        mHandler.post(new Runnable() {
13011            @Override
13012            public void run() {
13013                for (int i = 0; i < mRunningInstalls.size(); i++) {
13014                    final PostInstallData data = mRunningInstalls.valueAt(i);
13015                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13016                        continue;
13017                    }
13018                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13019                        // right package; but is it for the right user?
13020                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13021                            if (userId == data.res.newUsers[uIndex]) {
13022                                if (DEBUG_BACKUP) {
13023                                    Slog.i(TAG, "Package " + pkgName
13024                                            + " being restored so deferring FIRST_LAUNCH");
13025                                }
13026                                return;
13027                            }
13028                        }
13029                    }
13030                }
13031                // didn't find it, so not being restored
13032                if (DEBUG_BACKUP) {
13033                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13034                }
13035                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13036            }
13037        });
13038    }
13039
13040    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13041        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13042                installerPkg, null, userIds);
13043    }
13044
13045    private abstract class HandlerParams {
13046        private static final int MAX_RETRIES = 4;
13047
13048        /**
13049         * Number of times startCopy() has been attempted and had a non-fatal
13050         * error.
13051         */
13052        private int mRetries = 0;
13053
13054        /** User handle for the user requesting the information or installation. */
13055        private final UserHandle mUser;
13056        String traceMethod;
13057        int traceCookie;
13058
13059        HandlerParams(UserHandle user) {
13060            mUser = user;
13061        }
13062
13063        UserHandle getUser() {
13064            return mUser;
13065        }
13066
13067        HandlerParams setTraceMethod(String traceMethod) {
13068            this.traceMethod = traceMethod;
13069            return this;
13070        }
13071
13072        HandlerParams setTraceCookie(int traceCookie) {
13073            this.traceCookie = traceCookie;
13074            return this;
13075        }
13076
13077        final boolean startCopy() {
13078            boolean res;
13079            try {
13080                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13081
13082                if (++mRetries > MAX_RETRIES) {
13083                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13084                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13085                    handleServiceError();
13086                    return false;
13087                } else {
13088                    handleStartCopy();
13089                    res = true;
13090                }
13091            } catch (RemoteException e) {
13092                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13093                mHandler.sendEmptyMessage(MCS_RECONNECT);
13094                res = false;
13095            }
13096            handleReturnCode();
13097            return res;
13098        }
13099
13100        final void serviceError() {
13101            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13102            handleServiceError();
13103            handleReturnCode();
13104        }
13105
13106        abstract void handleStartCopy() throws RemoteException;
13107        abstract void handleServiceError();
13108        abstract void handleReturnCode();
13109    }
13110
13111    class MeasureParams extends HandlerParams {
13112        private final PackageStats mStats;
13113        private boolean mSuccess;
13114
13115        private final IPackageStatsObserver mObserver;
13116
13117        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13118            super(new UserHandle(stats.userHandle));
13119            mObserver = observer;
13120            mStats = stats;
13121        }
13122
13123        @Override
13124        public String toString() {
13125            return "MeasureParams{"
13126                + Integer.toHexString(System.identityHashCode(this))
13127                + " " + mStats.packageName + "}";
13128        }
13129
13130        @Override
13131        void handleStartCopy() throws RemoteException {
13132            synchronized (mInstallLock) {
13133                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13134            }
13135
13136            if (mSuccess) {
13137                boolean mounted = false;
13138                try {
13139                    final String status = Environment.getExternalStorageState();
13140                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13141                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13142                } catch (Exception e) {
13143                }
13144
13145                if (mounted) {
13146                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13147
13148                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13149                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13150
13151                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13152                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13153
13154                    // Always subtract cache size, since it's a subdirectory
13155                    mStats.externalDataSize -= mStats.externalCacheSize;
13156
13157                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13158                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13159
13160                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13161                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13162                }
13163            }
13164        }
13165
13166        @Override
13167        void handleReturnCode() {
13168            if (mObserver != null) {
13169                try {
13170                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13171                } catch (RemoteException e) {
13172                    Slog.i(TAG, "Observer no longer exists.");
13173                }
13174            }
13175        }
13176
13177        @Override
13178        void handleServiceError() {
13179            Slog.e(TAG, "Could not measure application " + mStats.packageName
13180                            + " external storage");
13181        }
13182    }
13183
13184    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13185            throws RemoteException {
13186        long result = 0;
13187        for (File path : paths) {
13188            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13189        }
13190        return result;
13191    }
13192
13193    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13194        for (File path : paths) {
13195            try {
13196                mcs.clearDirectory(path.getAbsolutePath());
13197            } catch (RemoteException e) {
13198            }
13199        }
13200    }
13201
13202    static class OriginInfo {
13203        /**
13204         * Location where install is coming from, before it has been
13205         * copied/renamed into place. This could be a single monolithic APK
13206         * file, or a cluster directory. This location may be untrusted.
13207         */
13208        final File file;
13209        final String cid;
13210
13211        /**
13212         * Flag indicating that {@link #file} or {@link #cid} has already been
13213         * staged, meaning downstream users don't need to defensively copy the
13214         * contents.
13215         */
13216        final boolean staged;
13217
13218        /**
13219         * Flag indicating that {@link #file} or {@link #cid} is an already
13220         * installed app that is being moved.
13221         */
13222        final boolean existing;
13223
13224        final String resolvedPath;
13225        final File resolvedFile;
13226
13227        static OriginInfo fromNothing() {
13228            return new OriginInfo(null, null, false, false);
13229        }
13230
13231        static OriginInfo fromUntrustedFile(File file) {
13232            return new OriginInfo(file, null, false, false);
13233        }
13234
13235        static OriginInfo fromExistingFile(File file) {
13236            return new OriginInfo(file, null, false, true);
13237        }
13238
13239        static OriginInfo fromStagedFile(File file) {
13240            return new OriginInfo(file, null, true, false);
13241        }
13242
13243        static OriginInfo fromStagedContainer(String cid) {
13244            return new OriginInfo(null, cid, true, false);
13245        }
13246
13247        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13248            this.file = file;
13249            this.cid = cid;
13250            this.staged = staged;
13251            this.existing = existing;
13252
13253            if (cid != null) {
13254                resolvedPath = PackageHelper.getSdDir(cid);
13255                resolvedFile = new File(resolvedPath);
13256            } else if (file != null) {
13257                resolvedPath = file.getAbsolutePath();
13258                resolvedFile = file;
13259            } else {
13260                resolvedPath = null;
13261                resolvedFile = null;
13262            }
13263        }
13264    }
13265
13266    static class MoveInfo {
13267        final int moveId;
13268        final String fromUuid;
13269        final String toUuid;
13270        final String packageName;
13271        final String dataAppName;
13272        final int appId;
13273        final String seinfo;
13274        final int targetSdkVersion;
13275
13276        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13277                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13278            this.moveId = moveId;
13279            this.fromUuid = fromUuid;
13280            this.toUuid = toUuid;
13281            this.packageName = packageName;
13282            this.dataAppName = dataAppName;
13283            this.appId = appId;
13284            this.seinfo = seinfo;
13285            this.targetSdkVersion = targetSdkVersion;
13286        }
13287    }
13288
13289    static class VerificationInfo {
13290        /** A constant used to indicate that a uid value is not present. */
13291        public static final int NO_UID = -1;
13292
13293        /** URI referencing where the package was downloaded from. */
13294        final Uri originatingUri;
13295
13296        /** HTTP referrer URI associated with the originatingURI. */
13297        final Uri referrer;
13298
13299        /** UID of the application that the install request originated from. */
13300        final int originatingUid;
13301
13302        /** UID of application requesting the install */
13303        final int installerUid;
13304
13305        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13306            this.originatingUri = originatingUri;
13307            this.referrer = referrer;
13308            this.originatingUid = originatingUid;
13309            this.installerUid = installerUid;
13310        }
13311    }
13312
13313    class InstallParams extends HandlerParams {
13314        final OriginInfo origin;
13315        final MoveInfo move;
13316        final IPackageInstallObserver2 observer;
13317        int installFlags;
13318        final String installerPackageName;
13319        final String volumeUuid;
13320        private InstallArgs mArgs;
13321        private int mRet;
13322        final String packageAbiOverride;
13323        final String[] grantedRuntimePermissions;
13324        final VerificationInfo verificationInfo;
13325        final Certificate[][] certificates;
13326
13327        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13328                int installFlags, String installerPackageName, String volumeUuid,
13329                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13330                String[] grantedPermissions, Certificate[][] certificates) {
13331            super(user);
13332            this.origin = origin;
13333            this.move = move;
13334            this.observer = observer;
13335            this.installFlags = installFlags;
13336            this.installerPackageName = installerPackageName;
13337            this.volumeUuid = volumeUuid;
13338            this.verificationInfo = verificationInfo;
13339            this.packageAbiOverride = packageAbiOverride;
13340            this.grantedRuntimePermissions = grantedPermissions;
13341            this.certificates = certificates;
13342        }
13343
13344        @Override
13345        public String toString() {
13346            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13347                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13348        }
13349
13350        private int installLocationPolicy(PackageInfoLite pkgLite) {
13351            String packageName = pkgLite.packageName;
13352            int installLocation = pkgLite.installLocation;
13353            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13354            // reader
13355            synchronized (mPackages) {
13356                // Currently installed package which the new package is attempting to replace or
13357                // null if no such package is installed.
13358                PackageParser.Package installedPkg = mPackages.get(packageName);
13359                // Package which currently owns the data which the new package will own if installed.
13360                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13361                // will be null whereas dataOwnerPkg will contain information about the package
13362                // which was uninstalled while keeping its data.
13363                PackageParser.Package dataOwnerPkg = installedPkg;
13364                if (dataOwnerPkg  == null) {
13365                    PackageSetting ps = mSettings.mPackages.get(packageName);
13366                    if (ps != null) {
13367                        dataOwnerPkg = ps.pkg;
13368                    }
13369                }
13370
13371                if (dataOwnerPkg != null) {
13372                    // If installed, the package will get access to data left on the device by its
13373                    // predecessor. As a security measure, this is permited only if this is not a
13374                    // version downgrade or if the predecessor package is marked as debuggable and
13375                    // a downgrade is explicitly requested.
13376                    //
13377                    // On debuggable platform builds, downgrades are permitted even for
13378                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13379                    // not offer security guarantees and thus it's OK to disable some security
13380                    // mechanisms to make debugging/testing easier on those builds. However, even on
13381                    // debuggable builds downgrades of packages are permitted only if requested via
13382                    // installFlags. This is because we aim to keep the behavior of debuggable
13383                    // platform builds as close as possible to the behavior of non-debuggable
13384                    // platform builds.
13385                    final boolean downgradeRequested =
13386                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13387                    final boolean packageDebuggable =
13388                                (dataOwnerPkg.applicationInfo.flags
13389                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13390                    final boolean downgradePermitted =
13391                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13392                    if (!downgradePermitted) {
13393                        try {
13394                            checkDowngrade(dataOwnerPkg, pkgLite);
13395                        } catch (PackageManagerException e) {
13396                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13397                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13398                        }
13399                    }
13400                }
13401
13402                if (installedPkg != null) {
13403                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13404                        // Check for updated system application.
13405                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13406                            if (onSd) {
13407                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13408                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13409                            }
13410                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13411                        } else {
13412                            if (onSd) {
13413                                // Install flag overrides everything.
13414                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13415                            }
13416                            // If current upgrade specifies particular preference
13417                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13418                                // Application explicitly specified internal.
13419                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13420                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13421                                // App explictly prefers external. Let policy decide
13422                            } else {
13423                                // Prefer previous location
13424                                if (isExternal(installedPkg)) {
13425                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13426                                }
13427                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13428                            }
13429                        }
13430                    } else {
13431                        // Invalid install. Return error code
13432                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13433                    }
13434                }
13435            }
13436            // All the special cases have been taken care of.
13437            // Return result based on recommended install location.
13438            if (onSd) {
13439                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13440            }
13441            return pkgLite.recommendedInstallLocation;
13442        }
13443
13444        /*
13445         * Invoke remote method to get package information and install
13446         * location values. Override install location based on default
13447         * policy if needed and then create install arguments based
13448         * on the install location.
13449         */
13450        public void handleStartCopy() throws RemoteException {
13451            int ret = PackageManager.INSTALL_SUCCEEDED;
13452
13453            // If we're already staged, we've firmly committed to an install location
13454            if (origin.staged) {
13455                if (origin.file != null) {
13456                    installFlags |= PackageManager.INSTALL_INTERNAL;
13457                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13458                } else if (origin.cid != null) {
13459                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13460                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13461                } else {
13462                    throw new IllegalStateException("Invalid stage location");
13463                }
13464            }
13465
13466            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13467            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13468            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13469            PackageInfoLite pkgLite = null;
13470
13471            if (onInt && onSd) {
13472                // Check if both bits are set.
13473                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13474                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13475            } else if (onSd && ephemeral) {
13476                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13477                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13478            } else {
13479                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13480                        packageAbiOverride);
13481
13482                if (DEBUG_EPHEMERAL && ephemeral) {
13483                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13484                }
13485
13486                /*
13487                 * If we have too little free space, try to free cache
13488                 * before giving up.
13489                 */
13490                if (!origin.staged && pkgLite.recommendedInstallLocation
13491                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13492                    // TODO: focus freeing disk space on the target device
13493                    final StorageManager storage = StorageManager.from(mContext);
13494                    final long lowThreshold = storage.getStorageLowBytes(
13495                            Environment.getDataDirectory());
13496
13497                    final long sizeBytes = mContainerService.calculateInstalledSize(
13498                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13499
13500                    try {
13501                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13502                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13503                                installFlags, packageAbiOverride);
13504                    } catch (InstallerException e) {
13505                        Slog.w(TAG, "Failed to free cache", e);
13506                    }
13507
13508                    /*
13509                     * The cache free must have deleted the file we
13510                     * downloaded to install.
13511                     *
13512                     * TODO: fix the "freeCache" call to not delete
13513                     *       the file we care about.
13514                     */
13515                    if (pkgLite.recommendedInstallLocation
13516                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13517                        pkgLite.recommendedInstallLocation
13518                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13519                    }
13520                }
13521            }
13522
13523            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13524                int loc = pkgLite.recommendedInstallLocation;
13525                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13526                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13527                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13528                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13529                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13530                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13531                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13532                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13533                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13534                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13535                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13536                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13537                } else {
13538                    // Override with defaults if needed.
13539                    loc = installLocationPolicy(pkgLite);
13540                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13541                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13542                    } else if (!onSd && !onInt) {
13543                        // Override install location with flags
13544                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13545                            // Set the flag to install on external media.
13546                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13547                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13548                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13549                            if (DEBUG_EPHEMERAL) {
13550                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13551                            }
13552                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13553                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13554                                    |PackageManager.INSTALL_INTERNAL);
13555                        } else {
13556                            // Make sure the flag for installing on external
13557                            // media is unset
13558                            installFlags |= PackageManager.INSTALL_INTERNAL;
13559                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13560                        }
13561                    }
13562                }
13563            }
13564
13565            final InstallArgs args = createInstallArgs(this);
13566            mArgs = args;
13567
13568            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13569                // TODO: http://b/22976637
13570                // Apps installed for "all" users use the device owner to verify the app
13571                UserHandle verifierUser = getUser();
13572                if (verifierUser == UserHandle.ALL) {
13573                    verifierUser = UserHandle.SYSTEM;
13574                }
13575
13576                /*
13577                 * Determine if we have any installed package verifiers. If we
13578                 * do, then we'll defer to them to verify the packages.
13579                 */
13580                final int requiredUid = mRequiredVerifierPackage == null ? -1
13581                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13582                                verifierUser.getIdentifier());
13583                if (!origin.existing && requiredUid != -1
13584                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13585                    final Intent verification = new Intent(
13586                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13587                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13588                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13589                            PACKAGE_MIME_TYPE);
13590                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13591
13592                    // Query all live verifiers based on current user state
13593                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13594                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13595
13596                    if (DEBUG_VERIFY) {
13597                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13598                                + verification.toString() + " with " + pkgLite.verifiers.length
13599                                + " optional verifiers");
13600                    }
13601
13602                    final int verificationId = mPendingVerificationToken++;
13603
13604                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13605
13606                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13607                            installerPackageName);
13608
13609                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13610                            installFlags);
13611
13612                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13613                            pkgLite.packageName);
13614
13615                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13616                            pkgLite.versionCode);
13617
13618                    if (verificationInfo != null) {
13619                        if (verificationInfo.originatingUri != null) {
13620                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13621                                    verificationInfo.originatingUri);
13622                        }
13623                        if (verificationInfo.referrer != null) {
13624                            verification.putExtra(Intent.EXTRA_REFERRER,
13625                                    verificationInfo.referrer);
13626                        }
13627                        if (verificationInfo.originatingUid >= 0) {
13628                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13629                                    verificationInfo.originatingUid);
13630                        }
13631                        if (verificationInfo.installerUid >= 0) {
13632                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13633                                    verificationInfo.installerUid);
13634                        }
13635                    }
13636
13637                    final PackageVerificationState verificationState = new PackageVerificationState(
13638                            requiredUid, args);
13639
13640                    mPendingVerification.append(verificationId, verificationState);
13641
13642                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13643                            receivers, verificationState);
13644
13645                    /*
13646                     * If any sufficient verifiers were listed in the package
13647                     * manifest, attempt to ask them.
13648                     */
13649                    if (sufficientVerifiers != null) {
13650                        final int N = sufficientVerifiers.size();
13651                        if (N == 0) {
13652                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13653                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13654                        } else {
13655                            for (int i = 0; i < N; i++) {
13656                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13657
13658                                final Intent sufficientIntent = new Intent(verification);
13659                                sufficientIntent.setComponent(verifierComponent);
13660                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13661                            }
13662                        }
13663                    }
13664
13665                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13666                            mRequiredVerifierPackage, receivers);
13667                    if (ret == PackageManager.INSTALL_SUCCEEDED
13668                            && mRequiredVerifierPackage != null) {
13669                        Trace.asyncTraceBegin(
13670                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13671                        /*
13672                         * Send the intent to the required verification agent,
13673                         * but only start the verification timeout after the
13674                         * target BroadcastReceivers have run.
13675                         */
13676                        verification.setComponent(requiredVerifierComponent);
13677                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13678                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13679                                new BroadcastReceiver() {
13680                                    @Override
13681                                    public void onReceive(Context context, Intent intent) {
13682                                        final Message msg = mHandler
13683                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13684                                        msg.arg1 = verificationId;
13685                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13686                                    }
13687                                }, null, 0, null, null);
13688
13689                        /*
13690                         * We don't want the copy to proceed until verification
13691                         * succeeds, so null out this field.
13692                         */
13693                        mArgs = null;
13694                    }
13695                } else {
13696                    /*
13697                     * No package verification is enabled, so immediately start
13698                     * the remote call to initiate copy using temporary file.
13699                     */
13700                    ret = args.copyApk(mContainerService, true);
13701                }
13702            }
13703
13704            mRet = ret;
13705        }
13706
13707        @Override
13708        void handleReturnCode() {
13709            // If mArgs is null, then MCS couldn't be reached. When it
13710            // reconnects, it will try again to install. At that point, this
13711            // will succeed.
13712            if (mArgs != null) {
13713                processPendingInstall(mArgs, mRet);
13714            }
13715        }
13716
13717        @Override
13718        void handleServiceError() {
13719            mArgs = createInstallArgs(this);
13720            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13721        }
13722
13723        public boolean isForwardLocked() {
13724            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13725        }
13726    }
13727
13728    /**
13729     * Used during creation of InstallArgs
13730     *
13731     * @param installFlags package installation flags
13732     * @return true if should be installed on external storage
13733     */
13734    private static boolean installOnExternalAsec(int installFlags) {
13735        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13736            return false;
13737        }
13738        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13739            return true;
13740        }
13741        return false;
13742    }
13743
13744    /**
13745     * Used during creation of InstallArgs
13746     *
13747     * @param installFlags package installation flags
13748     * @return true if should be installed as forward locked
13749     */
13750    private static boolean installForwardLocked(int installFlags) {
13751        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13752    }
13753
13754    private InstallArgs createInstallArgs(InstallParams params) {
13755        if (params.move != null) {
13756            return new MoveInstallArgs(params);
13757        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13758            return new AsecInstallArgs(params);
13759        } else {
13760            return new FileInstallArgs(params);
13761        }
13762    }
13763
13764    /**
13765     * Create args that describe an existing installed package. Typically used
13766     * when cleaning up old installs, or used as a move source.
13767     */
13768    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13769            String resourcePath, String[] instructionSets) {
13770        final boolean isInAsec;
13771        if (installOnExternalAsec(installFlags)) {
13772            /* Apps on SD card are always in ASEC containers. */
13773            isInAsec = true;
13774        } else if (installForwardLocked(installFlags)
13775                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13776            /*
13777             * Forward-locked apps are only in ASEC containers if they're the
13778             * new style
13779             */
13780            isInAsec = true;
13781        } else {
13782            isInAsec = false;
13783        }
13784
13785        if (isInAsec) {
13786            return new AsecInstallArgs(codePath, instructionSets,
13787                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13788        } else {
13789            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13790        }
13791    }
13792
13793    static abstract class InstallArgs {
13794        /** @see InstallParams#origin */
13795        final OriginInfo origin;
13796        /** @see InstallParams#move */
13797        final MoveInfo move;
13798
13799        final IPackageInstallObserver2 observer;
13800        // Always refers to PackageManager flags only
13801        final int installFlags;
13802        final String installerPackageName;
13803        final String volumeUuid;
13804        final UserHandle user;
13805        final String abiOverride;
13806        final String[] installGrantPermissions;
13807        /** If non-null, drop an async trace when the install completes */
13808        final String traceMethod;
13809        final int traceCookie;
13810        final Certificate[][] certificates;
13811
13812        // The list of instruction sets supported by this app. This is currently
13813        // only used during the rmdex() phase to clean up resources. We can get rid of this
13814        // if we move dex files under the common app path.
13815        /* nullable */ String[] instructionSets;
13816
13817        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13818                int installFlags, String installerPackageName, String volumeUuid,
13819                UserHandle user, String[] instructionSets,
13820                String abiOverride, String[] installGrantPermissions,
13821                String traceMethod, int traceCookie, Certificate[][] certificates) {
13822            this.origin = origin;
13823            this.move = move;
13824            this.installFlags = installFlags;
13825            this.observer = observer;
13826            this.installerPackageName = installerPackageName;
13827            this.volumeUuid = volumeUuid;
13828            this.user = user;
13829            this.instructionSets = instructionSets;
13830            this.abiOverride = abiOverride;
13831            this.installGrantPermissions = installGrantPermissions;
13832            this.traceMethod = traceMethod;
13833            this.traceCookie = traceCookie;
13834            this.certificates = certificates;
13835        }
13836
13837        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13838        abstract int doPreInstall(int status);
13839
13840        /**
13841         * Rename package into final resting place. All paths on the given
13842         * scanned package should be updated to reflect the rename.
13843         */
13844        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13845        abstract int doPostInstall(int status, int uid);
13846
13847        /** @see PackageSettingBase#codePathString */
13848        abstract String getCodePath();
13849        /** @see PackageSettingBase#resourcePathString */
13850        abstract String getResourcePath();
13851
13852        // Need installer lock especially for dex file removal.
13853        abstract void cleanUpResourcesLI();
13854        abstract boolean doPostDeleteLI(boolean delete);
13855
13856        /**
13857         * Called before the source arguments are copied. This is used mostly
13858         * for MoveParams when it needs to read the source file to put it in the
13859         * destination.
13860         */
13861        int doPreCopy() {
13862            return PackageManager.INSTALL_SUCCEEDED;
13863        }
13864
13865        /**
13866         * Called after the source arguments are copied. This is used mostly for
13867         * MoveParams when it needs to read the source file to put it in the
13868         * destination.
13869         */
13870        int doPostCopy(int uid) {
13871            return PackageManager.INSTALL_SUCCEEDED;
13872        }
13873
13874        protected boolean isFwdLocked() {
13875            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13876        }
13877
13878        protected boolean isExternalAsec() {
13879            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13880        }
13881
13882        protected boolean isEphemeral() {
13883            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13884        }
13885
13886        UserHandle getUser() {
13887            return user;
13888        }
13889    }
13890
13891    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13892        if (!allCodePaths.isEmpty()) {
13893            if (instructionSets == null) {
13894                throw new IllegalStateException("instructionSet == null");
13895            }
13896            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13897            for (String codePath : allCodePaths) {
13898                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13899                    try {
13900                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13901                    } catch (InstallerException ignored) {
13902                    }
13903                }
13904            }
13905        }
13906    }
13907
13908    /**
13909     * Logic to handle installation of non-ASEC applications, including copying
13910     * and renaming logic.
13911     */
13912    class FileInstallArgs extends InstallArgs {
13913        private File codeFile;
13914        private File resourceFile;
13915
13916        // Example topology:
13917        // /data/app/com.example/base.apk
13918        // /data/app/com.example/split_foo.apk
13919        // /data/app/com.example/lib/arm/libfoo.so
13920        // /data/app/com.example/lib/arm64/libfoo.so
13921        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13922
13923        /** New install */
13924        FileInstallArgs(InstallParams params) {
13925            super(params.origin, params.move, params.observer, params.installFlags,
13926                    params.installerPackageName, params.volumeUuid,
13927                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13928                    params.grantedRuntimePermissions,
13929                    params.traceMethod, params.traceCookie, params.certificates);
13930            if (isFwdLocked()) {
13931                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13932            }
13933        }
13934
13935        /** Existing install */
13936        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13937            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13938                    null, null, null, 0, null /*certificates*/);
13939            this.codeFile = (codePath != null) ? new File(codePath) : null;
13940            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13941        }
13942
13943        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13944            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13945            try {
13946                return doCopyApk(imcs, temp);
13947            } finally {
13948                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13949            }
13950        }
13951
13952        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13953            if (origin.staged) {
13954                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13955                codeFile = origin.file;
13956                resourceFile = origin.file;
13957                return PackageManager.INSTALL_SUCCEEDED;
13958            }
13959
13960            try {
13961                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13962                final File tempDir =
13963                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13964                codeFile = tempDir;
13965                resourceFile = tempDir;
13966            } catch (IOException e) {
13967                Slog.w(TAG, "Failed to create copy file: " + e);
13968                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13969            }
13970
13971            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13972                @Override
13973                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13974                    if (!FileUtils.isValidExtFilename(name)) {
13975                        throw new IllegalArgumentException("Invalid filename: " + name);
13976                    }
13977                    try {
13978                        final File file = new File(codeFile, name);
13979                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13980                                O_RDWR | O_CREAT, 0644);
13981                        Os.chmod(file.getAbsolutePath(), 0644);
13982                        return new ParcelFileDescriptor(fd);
13983                    } catch (ErrnoException e) {
13984                        throw new RemoteException("Failed to open: " + e.getMessage());
13985                    }
13986                }
13987            };
13988
13989            int ret = PackageManager.INSTALL_SUCCEEDED;
13990            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13991            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13992                Slog.e(TAG, "Failed to copy package");
13993                return ret;
13994            }
13995
13996            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13997            NativeLibraryHelper.Handle handle = null;
13998            try {
13999                handle = NativeLibraryHelper.Handle.create(codeFile);
14000                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14001                        abiOverride);
14002            } catch (IOException e) {
14003                Slog.e(TAG, "Copying native libraries failed", e);
14004                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14005            } finally {
14006                IoUtils.closeQuietly(handle);
14007            }
14008
14009            return ret;
14010        }
14011
14012        int doPreInstall(int status) {
14013            if (status != PackageManager.INSTALL_SUCCEEDED) {
14014                cleanUp();
14015            }
14016            return status;
14017        }
14018
14019        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14020            if (status != PackageManager.INSTALL_SUCCEEDED) {
14021                cleanUp();
14022                return false;
14023            }
14024
14025            final File targetDir = codeFile.getParentFile();
14026            final File beforeCodeFile = codeFile;
14027            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14028
14029            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14030            try {
14031                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14032            } catch (ErrnoException e) {
14033                Slog.w(TAG, "Failed to rename", e);
14034                return false;
14035            }
14036
14037            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14038                Slog.w(TAG, "Failed to restorecon");
14039                return false;
14040            }
14041
14042            // Reflect the rename internally
14043            codeFile = afterCodeFile;
14044            resourceFile = afterCodeFile;
14045
14046            // Reflect the rename in scanned details
14047            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14048            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14049                    afterCodeFile, pkg.baseCodePath));
14050            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14051                    afterCodeFile, pkg.splitCodePaths));
14052
14053            // Reflect the rename in app info
14054            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14055            pkg.setApplicationInfoCodePath(pkg.codePath);
14056            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14057            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14058            pkg.setApplicationInfoResourcePath(pkg.codePath);
14059            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14060            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14061
14062            return true;
14063        }
14064
14065        int doPostInstall(int status, int uid) {
14066            if (status != PackageManager.INSTALL_SUCCEEDED) {
14067                cleanUp();
14068            }
14069            return status;
14070        }
14071
14072        @Override
14073        String getCodePath() {
14074            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14075        }
14076
14077        @Override
14078        String getResourcePath() {
14079            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14080        }
14081
14082        private boolean cleanUp() {
14083            if (codeFile == null || !codeFile.exists()) {
14084                return false;
14085            }
14086
14087            removeCodePathLI(codeFile);
14088
14089            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14090                resourceFile.delete();
14091            }
14092
14093            return true;
14094        }
14095
14096        void cleanUpResourcesLI() {
14097            // Try enumerating all code paths before deleting
14098            List<String> allCodePaths = Collections.EMPTY_LIST;
14099            if (codeFile != null && codeFile.exists()) {
14100                try {
14101                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14102                    allCodePaths = pkg.getAllCodePaths();
14103                } catch (PackageParserException e) {
14104                    // Ignored; we tried our best
14105                }
14106            }
14107
14108            cleanUp();
14109            removeDexFiles(allCodePaths, instructionSets);
14110        }
14111
14112        boolean doPostDeleteLI(boolean delete) {
14113            // XXX err, shouldn't we respect the delete flag?
14114            cleanUpResourcesLI();
14115            return true;
14116        }
14117    }
14118
14119    private boolean isAsecExternal(String cid) {
14120        final String asecPath = PackageHelper.getSdFilesystem(cid);
14121        return !asecPath.startsWith(mAsecInternalPath);
14122    }
14123
14124    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14125            PackageManagerException {
14126        if (copyRet < 0) {
14127            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14128                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14129                throw new PackageManagerException(copyRet, message);
14130            }
14131        }
14132    }
14133
14134    /**
14135     * Extract the StorageManagerService "container ID" from the full code path of an
14136     * .apk.
14137     */
14138    static String cidFromCodePath(String fullCodePath) {
14139        int eidx = fullCodePath.lastIndexOf("/");
14140        String subStr1 = fullCodePath.substring(0, eidx);
14141        int sidx = subStr1.lastIndexOf("/");
14142        return subStr1.substring(sidx+1, eidx);
14143    }
14144
14145    /**
14146     * Logic to handle installation of ASEC applications, including copying and
14147     * renaming logic.
14148     */
14149    class AsecInstallArgs extends InstallArgs {
14150        static final String RES_FILE_NAME = "pkg.apk";
14151        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14152
14153        String cid;
14154        String packagePath;
14155        String resourcePath;
14156
14157        /** New install */
14158        AsecInstallArgs(InstallParams params) {
14159            super(params.origin, params.move, params.observer, params.installFlags,
14160                    params.installerPackageName, params.volumeUuid,
14161                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14162                    params.grantedRuntimePermissions,
14163                    params.traceMethod, params.traceCookie, params.certificates);
14164        }
14165
14166        /** Existing install */
14167        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14168                        boolean isExternal, boolean isForwardLocked) {
14169            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14170              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14171                    instructionSets, null, null, null, 0, null /*certificates*/);
14172            // Hackily pretend we're still looking at a full code path
14173            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14174                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14175            }
14176
14177            // Extract cid from fullCodePath
14178            int eidx = fullCodePath.lastIndexOf("/");
14179            String subStr1 = fullCodePath.substring(0, eidx);
14180            int sidx = subStr1.lastIndexOf("/");
14181            cid = subStr1.substring(sidx+1, eidx);
14182            setMountPath(subStr1);
14183        }
14184
14185        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14186            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14187              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14188                    instructionSets, null, null, null, 0, null /*certificates*/);
14189            this.cid = cid;
14190            setMountPath(PackageHelper.getSdDir(cid));
14191        }
14192
14193        void createCopyFile() {
14194            cid = mInstallerService.allocateExternalStageCidLegacy();
14195        }
14196
14197        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14198            if (origin.staged && origin.cid != null) {
14199                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14200                cid = origin.cid;
14201                setMountPath(PackageHelper.getSdDir(cid));
14202                return PackageManager.INSTALL_SUCCEEDED;
14203            }
14204
14205            if (temp) {
14206                createCopyFile();
14207            } else {
14208                /*
14209                 * Pre-emptively destroy the container since it's destroyed if
14210                 * copying fails due to it existing anyway.
14211                 */
14212                PackageHelper.destroySdDir(cid);
14213            }
14214
14215            final String newMountPath = imcs.copyPackageToContainer(
14216                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14217                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14218
14219            if (newMountPath != null) {
14220                setMountPath(newMountPath);
14221                return PackageManager.INSTALL_SUCCEEDED;
14222            } else {
14223                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14224            }
14225        }
14226
14227        @Override
14228        String getCodePath() {
14229            return packagePath;
14230        }
14231
14232        @Override
14233        String getResourcePath() {
14234            return resourcePath;
14235        }
14236
14237        int doPreInstall(int status) {
14238            if (status != PackageManager.INSTALL_SUCCEEDED) {
14239                // Destroy container
14240                PackageHelper.destroySdDir(cid);
14241            } else {
14242                boolean mounted = PackageHelper.isContainerMounted(cid);
14243                if (!mounted) {
14244                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14245                            Process.SYSTEM_UID);
14246                    if (newMountPath != null) {
14247                        setMountPath(newMountPath);
14248                    } else {
14249                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14250                    }
14251                }
14252            }
14253            return status;
14254        }
14255
14256        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14257            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14258            String newMountPath = null;
14259            if (PackageHelper.isContainerMounted(cid)) {
14260                // Unmount the container
14261                if (!PackageHelper.unMountSdDir(cid)) {
14262                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14263                    return false;
14264                }
14265            }
14266            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14267                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14268                        " which might be stale. Will try to clean up.");
14269                // Clean up the stale container and proceed to recreate.
14270                if (!PackageHelper.destroySdDir(newCacheId)) {
14271                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14272                    return false;
14273                }
14274                // Successfully cleaned up stale container. Try to rename again.
14275                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14276                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14277                            + " inspite of cleaning it up.");
14278                    return false;
14279                }
14280            }
14281            if (!PackageHelper.isContainerMounted(newCacheId)) {
14282                Slog.w(TAG, "Mounting container " + newCacheId);
14283                newMountPath = PackageHelper.mountSdDir(newCacheId,
14284                        getEncryptKey(), Process.SYSTEM_UID);
14285            } else {
14286                newMountPath = PackageHelper.getSdDir(newCacheId);
14287            }
14288            if (newMountPath == null) {
14289                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14290                return false;
14291            }
14292            Log.i(TAG, "Succesfully renamed " + cid +
14293                    " to " + newCacheId +
14294                    " at new path: " + newMountPath);
14295            cid = newCacheId;
14296
14297            final File beforeCodeFile = new File(packagePath);
14298            setMountPath(newMountPath);
14299            final File afterCodeFile = new File(packagePath);
14300
14301            // Reflect the rename in scanned details
14302            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14303            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14304                    afterCodeFile, pkg.baseCodePath));
14305            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14306                    afterCodeFile, pkg.splitCodePaths));
14307
14308            // Reflect the rename in app info
14309            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14310            pkg.setApplicationInfoCodePath(pkg.codePath);
14311            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14312            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14313            pkg.setApplicationInfoResourcePath(pkg.codePath);
14314            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14315            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14316
14317            return true;
14318        }
14319
14320        private void setMountPath(String mountPath) {
14321            final File mountFile = new File(mountPath);
14322
14323            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14324            if (monolithicFile.exists()) {
14325                packagePath = monolithicFile.getAbsolutePath();
14326                if (isFwdLocked()) {
14327                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14328                } else {
14329                    resourcePath = packagePath;
14330                }
14331            } else {
14332                packagePath = mountFile.getAbsolutePath();
14333                resourcePath = packagePath;
14334            }
14335        }
14336
14337        int doPostInstall(int status, int uid) {
14338            if (status != PackageManager.INSTALL_SUCCEEDED) {
14339                cleanUp();
14340            } else {
14341                final int groupOwner;
14342                final String protectedFile;
14343                if (isFwdLocked()) {
14344                    groupOwner = UserHandle.getSharedAppGid(uid);
14345                    protectedFile = RES_FILE_NAME;
14346                } else {
14347                    groupOwner = -1;
14348                    protectedFile = null;
14349                }
14350
14351                if (uid < Process.FIRST_APPLICATION_UID
14352                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14353                    Slog.e(TAG, "Failed to finalize " + cid);
14354                    PackageHelper.destroySdDir(cid);
14355                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14356                }
14357
14358                boolean mounted = PackageHelper.isContainerMounted(cid);
14359                if (!mounted) {
14360                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14361                }
14362            }
14363            return status;
14364        }
14365
14366        private void cleanUp() {
14367            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14368
14369            // Destroy secure container
14370            PackageHelper.destroySdDir(cid);
14371        }
14372
14373        private List<String> getAllCodePaths() {
14374            final File codeFile = new File(getCodePath());
14375            if (codeFile != null && codeFile.exists()) {
14376                try {
14377                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14378                    return pkg.getAllCodePaths();
14379                } catch (PackageParserException e) {
14380                    // Ignored; we tried our best
14381                }
14382            }
14383            return Collections.EMPTY_LIST;
14384        }
14385
14386        void cleanUpResourcesLI() {
14387            // Enumerate all code paths before deleting
14388            cleanUpResourcesLI(getAllCodePaths());
14389        }
14390
14391        private void cleanUpResourcesLI(List<String> allCodePaths) {
14392            cleanUp();
14393            removeDexFiles(allCodePaths, instructionSets);
14394        }
14395
14396        String getPackageName() {
14397            return getAsecPackageName(cid);
14398        }
14399
14400        boolean doPostDeleteLI(boolean delete) {
14401            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14402            final List<String> allCodePaths = getAllCodePaths();
14403            boolean mounted = PackageHelper.isContainerMounted(cid);
14404            if (mounted) {
14405                // Unmount first
14406                if (PackageHelper.unMountSdDir(cid)) {
14407                    mounted = false;
14408                }
14409            }
14410            if (!mounted && delete) {
14411                cleanUpResourcesLI(allCodePaths);
14412            }
14413            return !mounted;
14414        }
14415
14416        @Override
14417        int doPreCopy() {
14418            if (isFwdLocked()) {
14419                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14420                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14421                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14422                }
14423            }
14424
14425            return PackageManager.INSTALL_SUCCEEDED;
14426        }
14427
14428        @Override
14429        int doPostCopy(int uid) {
14430            if (isFwdLocked()) {
14431                if (uid < Process.FIRST_APPLICATION_UID
14432                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14433                                RES_FILE_NAME)) {
14434                    Slog.e(TAG, "Failed to finalize " + cid);
14435                    PackageHelper.destroySdDir(cid);
14436                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14437                }
14438            }
14439
14440            return PackageManager.INSTALL_SUCCEEDED;
14441        }
14442    }
14443
14444    /**
14445     * Logic to handle movement of existing installed applications.
14446     */
14447    class MoveInstallArgs extends InstallArgs {
14448        private File codeFile;
14449        private File resourceFile;
14450
14451        /** New install */
14452        MoveInstallArgs(InstallParams params) {
14453            super(params.origin, params.move, params.observer, params.installFlags,
14454                    params.installerPackageName, params.volumeUuid,
14455                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14456                    params.grantedRuntimePermissions,
14457                    params.traceMethod, params.traceCookie, params.certificates);
14458        }
14459
14460        int copyApk(IMediaContainerService imcs, boolean temp) {
14461            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14462                    + move.fromUuid + " to " + move.toUuid);
14463            synchronized (mInstaller) {
14464                try {
14465                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14466                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14467                } catch (InstallerException e) {
14468                    Slog.w(TAG, "Failed to move app", e);
14469                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14470                }
14471            }
14472
14473            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14474            resourceFile = codeFile;
14475            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14476
14477            return PackageManager.INSTALL_SUCCEEDED;
14478        }
14479
14480        int doPreInstall(int status) {
14481            if (status != PackageManager.INSTALL_SUCCEEDED) {
14482                cleanUp(move.toUuid);
14483            }
14484            return status;
14485        }
14486
14487        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14488            if (status != PackageManager.INSTALL_SUCCEEDED) {
14489                cleanUp(move.toUuid);
14490                return false;
14491            }
14492
14493            // Reflect the move in app info
14494            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14495            pkg.setApplicationInfoCodePath(pkg.codePath);
14496            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14497            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14498            pkg.setApplicationInfoResourcePath(pkg.codePath);
14499            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14500            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14501
14502            return true;
14503        }
14504
14505        int doPostInstall(int status, int uid) {
14506            if (status == PackageManager.INSTALL_SUCCEEDED) {
14507                cleanUp(move.fromUuid);
14508            } else {
14509                cleanUp(move.toUuid);
14510            }
14511            return status;
14512        }
14513
14514        @Override
14515        String getCodePath() {
14516            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14517        }
14518
14519        @Override
14520        String getResourcePath() {
14521            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14522        }
14523
14524        private boolean cleanUp(String volumeUuid) {
14525            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14526                    move.dataAppName);
14527            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14528            final int[] userIds = sUserManager.getUserIds();
14529            synchronized (mInstallLock) {
14530                // Clean up both app data and code
14531                // All package moves are frozen until finished
14532                for (int userId : userIds) {
14533                    try {
14534                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14535                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14536                    } catch (InstallerException e) {
14537                        Slog.w(TAG, String.valueOf(e));
14538                    }
14539                }
14540                removeCodePathLI(codeFile);
14541            }
14542            return true;
14543        }
14544
14545        void cleanUpResourcesLI() {
14546            throw new UnsupportedOperationException();
14547        }
14548
14549        boolean doPostDeleteLI(boolean delete) {
14550            throw new UnsupportedOperationException();
14551        }
14552    }
14553
14554    static String getAsecPackageName(String packageCid) {
14555        int idx = packageCid.lastIndexOf("-");
14556        if (idx == -1) {
14557            return packageCid;
14558        }
14559        return packageCid.substring(0, idx);
14560    }
14561
14562    // Utility method used to create code paths based on package name and available index.
14563    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14564        String idxStr = "";
14565        int idx = 1;
14566        // Fall back to default value of idx=1 if prefix is not
14567        // part of oldCodePath
14568        if (oldCodePath != null) {
14569            String subStr = oldCodePath;
14570            // Drop the suffix right away
14571            if (suffix != null && subStr.endsWith(suffix)) {
14572                subStr = subStr.substring(0, subStr.length() - suffix.length());
14573            }
14574            // If oldCodePath already contains prefix find out the
14575            // ending index to either increment or decrement.
14576            int sidx = subStr.lastIndexOf(prefix);
14577            if (sidx != -1) {
14578                subStr = subStr.substring(sidx + prefix.length());
14579                if (subStr != null) {
14580                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14581                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14582                    }
14583                    try {
14584                        idx = Integer.parseInt(subStr);
14585                        if (idx <= 1) {
14586                            idx++;
14587                        } else {
14588                            idx--;
14589                        }
14590                    } catch(NumberFormatException e) {
14591                    }
14592                }
14593            }
14594        }
14595        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14596        return prefix + idxStr;
14597    }
14598
14599    private File getNextCodePath(File targetDir, String packageName) {
14600        File result;
14601        SecureRandom random = new SecureRandom();
14602        byte[] bytes = new byte[16];
14603        do {
14604            random.nextBytes(bytes);
14605            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14606            result = new File(targetDir, packageName + "-" + suffix);
14607        } while (result.exists());
14608        return result;
14609    }
14610
14611    // Utility method that returns the relative package path with respect
14612    // to the installation directory. Like say for /data/data/com.test-1.apk
14613    // string com.test-1 is returned.
14614    static String deriveCodePathName(String codePath) {
14615        if (codePath == null) {
14616            return null;
14617        }
14618        final File codeFile = new File(codePath);
14619        final String name = codeFile.getName();
14620        if (codeFile.isDirectory()) {
14621            return name;
14622        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14623            final int lastDot = name.lastIndexOf('.');
14624            return name.substring(0, lastDot);
14625        } else {
14626            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14627            return null;
14628        }
14629    }
14630
14631    static class PackageInstalledInfo {
14632        String name;
14633        int uid;
14634        // The set of users that originally had this package installed.
14635        int[] origUsers;
14636        // The set of users that now have this package installed.
14637        int[] newUsers;
14638        PackageParser.Package pkg;
14639        int returnCode;
14640        String returnMsg;
14641        PackageRemovedInfo removedInfo;
14642        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14643
14644        public void setError(int code, String msg) {
14645            setReturnCode(code);
14646            setReturnMessage(msg);
14647            Slog.w(TAG, msg);
14648        }
14649
14650        public void setError(String msg, PackageParserException e) {
14651            setReturnCode(e.error);
14652            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14653            Slog.w(TAG, msg, e);
14654        }
14655
14656        public void setError(String msg, PackageManagerException e) {
14657            returnCode = e.error;
14658            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14659            Slog.w(TAG, msg, e);
14660        }
14661
14662        public void setReturnCode(int returnCode) {
14663            this.returnCode = returnCode;
14664            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14665            for (int i = 0; i < childCount; i++) {
14666                addedChildPackages.valueAt(i).returnCode = returnCode;
14667            }
14668        }
14669
14670        private void setReturnMessage(String returnMsg) {
14671            this.returnMsg = returnMsg;
14672            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14673            for (int i = 0; i < childCount; i++) {
14674                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14675            }
14676        }
14677
14678        // In some error cases we want to convey more info back to the observer
14679        String origPackage;
14680        String origPermission;
14681    }
14682
14683    /*
14684     * Install a non-existing package.
14685     */
14686    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14687            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14688            PackageInstalledInfo res) {
14689        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14690
14691        // Remember this for later, in case we need to rollback this install
14692        String pkgName = pkg.packageName;
14693
14694        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14695
14696        synchronized(mPackages) {
14697            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14698            if (renamedPackage != null) {
14699                // A package with the same name is already installed, though
14700                // it has been renamed to an older name.  The package we
14701                // are trying to install should be installed as an update to
14702                // the existing one, but that has not been requested, so bail.
14703                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14704                        + " without first uninstalling package running as "
14705                        + renamedPackage);
14706                return;
14707            }
14708            if (mPackages.containsKey(pkgName)) {
14709                // Don't allow installation over an existing package with the same name.
14710                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14711                        + " without first uninstalling.");
14712                return;
14713            }
14714        }
14715
14716        try {
14717            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14718                    System.currentTimeMillis(), user);
14719
14720            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14721
14722            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14723                prepareAppDataAfterInstallLIF(newPackage);
14724
14725            } else {
14726                // Remove package from internal structures, but keep around any
14727                // data that might have already existed
14728                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14729                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14730            }
14731        } catch (PackageManagerException e) {
14732            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14733        }
14734
14735        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14736    }
14737
14738    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14739        // Can't rotate keys during boot or if sharedUser.
14740        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14741                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14742            return false;
14743        }
14744        // app is using upgradeKeySets; make sure all are valid
14745        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14746        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14747        for (int i = 0; i < upgradeKeySets.length; i++) {
14748            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14749                Slog.wtf(TAG, "Package "
14750                         + (oldPs.name != null ? oldPs.name : "<null>")
14751                         + " contains upgrade-key-set reference to unknown key-set: "
14752                         + upgradeKeySets[i]
14753                         + " reverting to signatures check.");
14754                return false;
14755            }
14756        }
14757        return true;
14758    }
14759
14760    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14761        // Upgrade keysets are being used.  Determine if new package has a superset of the
14762        // required keys.
14763        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14764        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14765        for (int i = 0; i < upgradeKeySets.length; i++) {
14766            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14767            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14768                return true;
14769            }
14770        }
14771        return false;
14772    }
14773
14774    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14775        try (DigestInputStream digestStream =
14776                new DigestInputStream(new FileInputStream(file), digest)) {
14777            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14778        }
14779    }
14780
14781    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14782            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14783        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14784
14785        final PackageParser.Package oldPackage;
14786        final String pkgName = pkg.packageName;
14787        final int[] allUsers;
14788        final int[] installedUsers;
14789
14790        synchronized(mPackages) {
14791            oldPackage = mPackages.get(pkgName);
14792            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14793
14794            // don't allow upgrade to target a release SDK from a pre-release SDK
14795            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14796                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14797            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14798                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14799            if (oldTargetsPreRelease
14800                    && !newTargetsPreRelease
14801                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14802                Slog.w(TAG, "Can't install package targeting released sdk");
14803                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14804                return;
14805            }
14806
14807            // don't allow an upgrade from full to ephemeral
14808            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14809            if (isEphemeral && !oldIsEphemeral) {
14810                // can't downgrade from full to ephemeral
14811                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14812                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14813                return;
14814            }
14815
14816            // verify signatures are valid
14817            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14818            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14819                if (!checkUpgradeKeySetLP(ps, pkg)) {
14820                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14821                            "New package not signed by keys specified by upgrade-keysets: "
14822                                    + pkgName);
14823                    return;
14824                }
14825            } else {
14826                // default to original signature matching
14827                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14828                        != PackageManager.SIGNATURE_MATCH) {
14829                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14830                            "New package has a different signature: " + pkgName);
14831                    return;
14832                }
14833            }
14834
14835            // don't allow a system upgrade unless the upgrade hash matches
14836            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14837                byte[] digestBytes = null;
14838                try {
14839                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14840                    updateDigest(digest, new File(pkg.baseCodePath));
14841                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14842                        for (String path : pkg.splitCodePaths) {
14843                            updateDigest(digest, new File(path));
14844                        }
14845                    }
14846                    digestBytes = digest.digest();
14847                } catch (NoSuchAlgorithmException | IOException e) {
14848                    res.setError(INSTALL_FAILED_INVALID_APK,
14849                            "Could not compute hash: " + pkgName);
14850                    return;
14851                }
14852                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14853                    res.setError(INSTALL_FAILED_INVALID_APK,
14854                            "New package fails restrict-update check: " + pkgName);
14855                    return;
14856                }
14857                // retain upgrade restriction
14858                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14859            }
14860
14861            // Check for shared user id changes
14862            String invalidPackageName =
14863                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14864            if (invalidPackageName != null) {
14865                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14866                        "Package " + invalidPackageName + " tried to change user "
14867                                + oldPackage.mSharedUserId);
14868                return;
14869            }
14870
14871            // In case of rollback, remember per-user/profile install state
14872            allUsers = sUserManager.getUserIds();
14873            installedUsers = ps.queryInstalledUsers(allUsers, true);
14874        }
14875
14876        // Update what is removed
14877        res.removedInfo = new PackageRemovedInfo();
14878        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14879        res.removedInfo.removedPackage = oldPackage.packageName;
14880        res.removedInfo.isUpdate = true;
14881        res.removedInfo.origUsers = installedUsers;
14882        final int childCount = (oldPackage.childPackages != null)
14883                ? oldPackage.childPackages.size() : 0;
14884        for (int i = 0; i < childCount; i++) {
14885            boolean childPackageUpdated = false;
14886            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14887            if (res.addedChildPackages != null) {
14888                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14889                if (childRes != null) {
14890                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14891                    childRes.removedInfo.removedPackage = childPkg.packageName;
14892                    childRes.removedInfo.isUpdate = true;
14893                    childPackageUpdated = true;
14894                }
14895            }
14896            if (!childPackageUpdated) {
14897                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14898                childRemovedRes.removedPackage = childPkg.packageName;
14899                childRemovedRes.isUpdate = false;
14900                childRemovedRes.dataRemoved = true;
14901                synchronized (mPackages) {
14902                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14903                    if (childPs != null) {
14904                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14905                    }
14906                }
14907                if (res.removedInfo.removedChildPackages == null) {
14908                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14909                }
14910                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14911            }
14912        }
14913
14914        boolean sysPkg = (isSystemApp(oldPackage));
14915        if (sysPkg) {
14916            // Set the system/privileged flags as needed
14917            final boolean privileged =
14918                    (oldPackage.applicationInfo.privateFlags
14919                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14920            final int systemPolicyFlags = policyFlags
14921                    | PackageParser.PARSE_IS_SYSTEM
14922                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14923
14924            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14925                    user, allUsers, installerPackageName, res);
14926        } else {
14927            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14928                    user, allUsers, installerPackageName, res);
14929        }
14930    }
14931
14932    public List<String> getPreviousCodePaths(String packageName) {
14933        final PackageSetting ps = mSettings.mPackages.get(packageName);
14934        final List<String> result = new ArrayList<String>();
14935        if (ps != null && ps.oldCodePaths != null) {
14936            result.addAll(ps.oldCodePaths);
14937        }
14938        return result;
14939    }
14940
14941    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14942            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14943            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14944        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14945                + deletedPackage);
14946
14947        String pkgName = deletedPackage.packageName;
14948        boolean deletedPkg = true;
14949        boolean addedPkg = false;
14950        boolean updatedSettings = false;
14951        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14952        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14953                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14954
14955        final long origUpdateTime = (pkg.mExtras != null)
14956                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14957
14958        // First delete the existing package while retaining the data directory
14959        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14960                res.removedInfo, true, pkg)) {
14961            // If the existing package wasn't successfully deleted
14962            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14963            deletedPkg = false;
14964        } else {
14965            // Successfully deleted the old package; proceed with replace.
14966
14967            // If deleted package lived in a container, give users a chance to
14968            // relinquish resources before killing.
14969            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14970                if (DEBUG_INSTALL) {
14971                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14972                }
14973                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14974                final ArrayList<String> pkgList = new ArrayList<String>(1);
14975                pkgList.add(deletedPackage.applicationInfo.packageName);
14976                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14977            }
14978
14979            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14980                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14981            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14982
14983            try {
14984                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14985                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14986                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14987
14988                // Update the in-memory copy of the previous code paths.
14989                PackageSetting ps = mSettings.mPackages.get(pkgName);
14990                if (!killApp) {
14991                    if (ps.oldCodePaths == null) {
14992                        ps.oldCodePaths = new ArraySet<>();
14993                    }
14994                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14995                    if (deletedPackage.splitCodePaths != null) {
14996                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14997                    }
14998                } else {
14999                    ps.oldCodePaths = null;
15000                }
15001                if (ps.childPackageNames != null) {
15002                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15003                        final String childPkgName = ps.childPackageNames.get(i);
15004                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15005                        childPs.oldCodePaths = ps.oldCodePaths;
15006                    }
15007                }
15008                prepareAppDataAfterInstallLIF(newPackage);
15009                addedPkg = true;
15010            } catch (PackageManagerException e) {
15011                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15012            }
15013        }
15014
15015        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15016            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15017
15018            // Revert all internal state mutations and added folders for the failed install
15019            if (addedPkg) {
15020                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15021                        res.removedInfo, true, null);
15022            }
15023
15024            // Restore the old package
15025            if (deletedPkg) {
15026                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15027                File restoreFile = new File(deletedPackage.codePath);
15028                // Parse old package
15029                boolean oldExternal = isExternal(deletedPackage);
15030                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15031                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15032                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15033                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15034                try {
15035                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15036                            null);
15037                } catch (PackageManagerException e) {
15038                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15039                            + e.getMessage());
15040                    return;
15041                }
15042
15043                synchronized (mPackages) {
15044                    // Ensure the installer package name up to date
15045                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15046
15047                    // Update permissions for restored package
15048                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15049
15050                    mSettings.writeLPr();
15051                }
15052
15053                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15054            }
15055        } else {
15056            synchronized (mPackages) {
15057                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15058                if (ps != null) {
15059                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15060                    if (res.removedInfo.removedChildPackages != null) {
15061                        final int childCount = res.removedInfo.removedChildPackages.size();
15062                        // Iterate in reverse as we may modify the collection
15063                        for (int i = childCount - 1; i >= 0; i--) {
15064                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15065                            if (res.addedChildPackages.containsKey(childPackageName)) {
15066                                res.removedInfo.removedChildPackages.removeAt(i);
15067                            } else {
15068                                PackageRemovedInfo childInfo = res.removedInfo
15069                                        .removedChildPackages.valueAt(i);
15070                                childInfo.removedForAllUsers = mPackages.get(
15071                                        childInfo.removedPackage) == null;
15072                            }
15073                        }
15074                    }
15075                }
15076            }
15077        }
15078    }
15079
15080    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15081            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15082            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
15083        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15084                + ", old=" + deletedPackage);
15085
15086        final boolean disabledSystem;
15087
15088        // Remove existing system package
15089        removePackageLI(deletedPackage, true);
15090
15091        synchronized (mPackages) {
15092            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15093        }
15094        if (!disabledSystem) {
15095            // We didn't need to disable the .apk as a current system package,
15096            // which means we are replacing another update that is already
15097            // installed.  We need to make sure to delete the older one's .apk.
15098            res.removedInfo.args = createInstallArgsForExisting(0,
15099                    deletedPackage.applicationInfo.getCodePath(),
15100                    deletedPackage.applicationInfo.getResourcePath(),
15101                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15102        } else {
15103            res.removedInfo.args = null;
15104        }
15105
15106        // Successfully disabled the old package. Now proceed with re-installation
15107        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15108                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15109        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15110
15111        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15112        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15113                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15114
15115        PackageParser.Package newPackage = null;
15116        try {
15117            // Add the package to the internal data structures
15118            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15119
15120            // Set the update and install times
15121            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15122            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15123                    System.currentTimeMillis());
15124
15125            // Update the package dynamic state if succeeded
15126            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15127                // Now that the install succeeded make sure we remove data
15128                // directories for any child package the update removed.
15129                final int deletedChildCount = (deletedPackage.childPackages != null)
15130                        ? deletedPackage.childPackages.size() : 0;
15131                final int newChildCount = (newPackage.childPackages != null)
15132                        ? newPackage.childPackages.size() : 0;
15133                for (int i = 0; i < deletedChildCount; i++) {
15134                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15135                    boolean childPackageDeleted = true;
15136                    for (int j = 0; j < newChildCount; j++) {
15137                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15138                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15139                            childPackageDeleted = false;
15140                            break;
15141                        }
15142                    }
15143                    if (childPackageDeleted) {
15144                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15145                                deletedChildPkg.packageName);
15146                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15147                            PackageRemovedInfo removedChildRes = res.removedInfo
15148                                    .removedChildPackages.get(deletedChildPkg.packageName);
15149                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15150                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15151                        }
15152                    }
15153                }
15154
15155                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
15156                prepareAppDataAfterInstallLIF(newPackage);
15157            }
15158        } catch (PackageManagerException e) {
15159            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15160            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15161        }
15162
15163        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15164            // Re installation failed. Restore old information
15165            // Remove new pkg information
15166            if (newPackage != null) {
15167                removeInstalledPackageLI(newPackage, true);
15168            }
15169            // Add back the old system package
15170            try {
15171                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15172            } catch (PackageManagerException e) {
15173                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15174            }
15175
15176            synchronized (mPackages) {
15177                if (disabledSystem) {
15178                    enableSystemPackageLPw(deletedPackage);
15179                }
15180
15181                // Ensure the installer package name up to date
15182                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15183
15184                // Update permissions for restored package
15185                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15186
15187                mSettings.writeLPr();
15188            }
15189
15190            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15191                    + " after failed upgrade");
15192        }
15193    }
15194
15195    /**
15196     * Checks whether the parent or any of the child packages have a change shared
15197     * user. For a package to be a valid update the shred users of the parent and
15198     * the children should match. We may later support changing child shared users.
15199     * @param oldPkg The updated package.
15200     * @param newPkg The update package.
15201     * @return The shared user that change between the versions.
15202     */
15203    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15204            PackageParser.Package newPkg) {
15205        // Check parent shared user
15206        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15207            return newPkg.packageName;
15208        }
15209        // Check child shared users
15210        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15211        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15212        for (int i = 0; i < newChildCount; i++) {
15213            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15214            // If this child was present, did it have the same shared user?
15215            for (int j = 0; j < oldChildCount; j++) {
15216                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15217                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15218                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15219                    return newChildPkg.packageName;
15220                }
15221            }
15222        }
15223        return null;
15224    }
15225
15226    private void removeNativeBinariesLI(PackageSetting ps) {
15227        // Remove the lib path for the parent package
15228        if (ps != null) {
15229            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15230            // Remove the lib path for the child packages
15231            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15232            for (int i = 0; i < childCount; i++) {
15233                PackageSetting childPs = null;
15234                synchronized (mPackages) {
15235                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15236                }
15237                if (childPs != null) {
15238                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15239                            .legacyNativeLibraryPathString);
15240                }
15241            }
15242        }
15243    }
15244
15245    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15246        // Enable the parent package
15247        mSettings.enableSystemPackageLPw(pkg.packageName);
15248        // Enable the child packages
15249        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15250        for (int i = 0; i < childCount; i++) {
15251            PackageParser.Package childPkg = pkg.childPackages.get(i);
15252            mSettings.enableSystemPackageLPw(childPkg.packageName);
15253        }
15254    }
15255
15256    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15257            PackageParser.Package newPkg) {
15258        // Disable the parent package (parent always replaced)
15259        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15260        // Disable the child packages
15261        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15262        for (int i = 0; i < childCount; i++) {
15263            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15264            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15265            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15266        }
15267        return disabled;
15268    }
15269
15270    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15271            String installerPackageName) {
15272        // Enable the parent package
15273        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15274        // Enable the child packages
15275        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15276        for (int i = 0; i < childCount; i++) {
15277            PackageParser.Package childPkg = pkg.childPackages.get(i);
15278            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15279        }
15280    }
15281
15282    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15283        // Collect all used permissions in the UID
15284        ArraySet<String> usedPermissions = new ArraySet<>();
15285        final int packageCount = su.packages.size();
15286        for (int i = 0; i < packageCount; i++) {
15287            PackageSetting ps = su.packages.valueAt(i);
15288            if (ps.pkg == null) {
15289                continue;
15290            }
15291            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15292            for (int j = 0; j < requestedPermCount; j++) {
15293                String permission = ps.pkg.requestedPermissions.get(j);
15294                BasePermission bp = mSettings.mPermissions.get(permission);
15295                if (bp != null) {
15296                    usedPermissions.add(permission);
15297                }
15298            }
15299        }
15300
15301        PermissionsState permissionsState = su.getPermissionsState();
15302        // Prune install permissions
15303        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15304        final int installPermCount = installPermStates.size();
15305        for (int i = installPermCount - 1; i >= 0;  i--) {
15306            PermissionState permissionState = installPermStates.get(i);
15307            if (!usedPermissions.contains(permissionState.getName())) {
15308                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15309                if (bp != null) {
15310                    permissionsState.revokeInstallPermission(bp);
15311                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15312                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15313                }
15314            }
15315        }
15316
15317        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15318
15319        // Prune runtime permissions
15320        for (int userId : allUserIds) {
15321            List<PermissionState> runtimePermStates = permissionsState
15322                    .getRuntimePermissionStates(userId);
15323            final int runtimePermCount = runtimePermStates.size();
15324            for (int i = runtimePermCount - 1; i >= 0; i--) {
15325                PermissionState permissionState = runtimePermStates.get(i);
15326                if (!usedPermissions.contains(permissionState.getName())) {
15327                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15328                    if (bp != null) {
15329                        permissionsState.revokeRuntimePermission(bp, userId);
15330                        permissionsState.updatePermissionFlags(bp, userId,
15331                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15332                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15333                                runtimePermissionChangedUserIds, userId);
15334                    }
15335                }
15336            }
15337        }
15338
15339        return runtimePermissionChangedUserIds;
15340    }
15341
15342    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15343            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15344        // Update the parent package setting
15345        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15346                res, user);
15347        // Update the child packages setting
15348        final int childCount = (newPackage.childPackages != null)
15349                ? newPackage.childPackages.size() : 0;
15350        for (int i = 0; i < childCount; i++) {
15351            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15352            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15353            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15354                    childRes.origUsers, childRes, user);
15355        }
15356    }
15357
15358    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15359            String installerPackageName, int[] allUsers, int[] installedForUsers,
15360            PackageInstalledInfo res, UserHandle user) {
15361        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15362
15363        String pkgName = newPackage.packageName;
15364        synchronized (mPackages) {
15365            //write settings. the installStatus will be incomplete at this stage.
15366            //note that the new package setting would have already been
15367            //added to mPackages. It hasn't been persisted yet.
15368            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15369            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15370            mSettings.writeLPr();
15371            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15372        }
15373
15374        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15375        synchronized (mPackages) {
15376            updatePermissionsLPw(newPackage.packageName, newPackage,
15377                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15378                            ? UPDATE_PERMISSIONS_ALL : 0));
15379            // For system-bundled packages, we assume that installing an upgraded version
15380            // of the package implies that the user actually wants to run that new code,
15381            // so we enable the package.
15382            PackageSetting ps = mSettings.mPackages.get(pkgName);
15383            final int userId = user.getIdentifier();
15384            if (ps != null) {
15385                if (isSystemApp(newPackage)) {
15386                    if (DEBUG_INSTALL) {
15387                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15388                    }
15389                    // Enable system package for requested users
15390                    if (res.origUsers != null) {
15391                        for (int origUserId : res.origUsers) {
15392                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15393                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15394                                        origUserId, installerPackageName);
15395                            }
15396                        }
15397                    }
15398                    // Also convey the prior install/uninstall state
15399                    if (allUsers != null && installedForUsers != null) {
15400                        for (int currentUserId : allUsers) {
15401                            final boolean installed = ArrayUtils.contains(
15402                                    installedForUsers, currentUserId);
15403                            if (DEBUG_INSTALL) {
15404                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15405                            }
15406                            ps.setInstalled(installed, currentUserId);
15407                        }
15408                        // these install state changes will be persisted in the
15409                        // upcoming call to mSettings.writeLPr().
15410                    }
15411                }
15412                // It's implied that when a user requests installation, they want the app to be
15413                // installed and enabled.
15414                if (userId != UserHandle.USER_ALL) {
15415                    ps.setInstalled(true, userId);
15416                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15417                }
15418            }
15419            res.name = pkgName;
15420            res.uid = newPackage.applicationInfo.uid;
15421            res.pkg = newPackage;
15422            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15423            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15424            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15425            //to update install status
15426            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15427            mSettings.writeLPr();
15428            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15429        }
15430
15431        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15432    }
15433
15434    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15435        try {
15436            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15437            installPackageLI(args, res);
15438        } finally {
15439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15440        }
15441    }
15442
15443    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15444        final int installFlags = args.installFlags;
15445        final String installerPackageName = args.installerPackageName;
15446        final String volumeUuid = args.volumeUuid;
15447        final File tmpPackageFile = new File(args.getCodePath());
15448        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15449        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15450                || (args.volumeUuid != null));
15451        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15452        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15453        boolean replace = false;
15454        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15455        if (args.move != null) {
15456            // moving a complete application; perform an initial scan on the new install location
15457            scanFlags |= SCAN_INITIAL;
15458        }
15459        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15460            scanFlags |= SCAN_DONT_KILL_APP;
15461        }
15462
15463        // Result object to be returned
15464        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15465
15466        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15467
15468        // Sanity check
15469        if (ephemeral && (forwardLocked || onExternal)) {
15470            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15471                    + " external=" + onExternal);
15472            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15473            return;
15474        }
15475
15476        // Retrieve PackageSettings and parse package
15477        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15478                | PackageParser.PARSE_ENFORCE_CODE
15479                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15480                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15481                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15482                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15483        PackageParser pp = new PackageParser();
15484        pp.setSeparateProcesses(mSeparateProcesses);
15485        pp.setDisplayMetrics(mMetrics);
15486
15487        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15488        final PackageParser.Package pkg;
15489        try {
15490            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15491        } catch (PackageParserException e) {
15492            res.setError("Failed parse during installPackageLI", e);
15493            return;
15494        } finally {
15495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15496        }
15497
15498        // If we are installing a clustered package add results for the children
15499        if (pkg.childPackages != null) {
15500            synchronized (mPackages) {
15501                final int childCount = pkg.childPackages.size();
15502                for (int i = 0; i < childCount; i++) {
15503                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15504                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15505                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15506                    childRes.pkg = childPkg;
15507                    childRes.name = childPkg.packageName;
15508                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15509                    if (childPs != null) {
15510                        childRes.origUsers = childPs.queryInstalledUsers(
15511                                sUserManager.getUserIds(), true);
15512                    }
15513                    if ((mPackages.containsKey(childPkg.packageName))) {
15514                        childRes.removedInfo = new PackageRemovedInfo();
15515                        childRes.removedInfo.removedPackage = childPkg.packageName;
15516                    }
15517                    if (res.addedChildPackages == null) {
15518                        res.addedChildPackages = new ArrayMap<>();
15519                    }
15520                    res.addedChildPackages.put(childPkg.packageName, childRes);
15521                }
15522            }
15523        }
15524
15525        // If package doesn't declare API override, mark that we have an install
15526        // time CPU ABI override.
15527        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15528            pkg.cpuAbiOverride = args.abiOverride;
15529        }
15530
15531        String pkgName = res.name = pkg.packageName;
15532        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15533            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15534                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15535                return;
15536            }
15537        }
15538
15539        try {
15540            // either use what we've been given or parse directly from the APK
15541            if (args.certificates != null) {
15542                try {
15543                    PackageParser.populateCertificates(pkg, args.certificates);
15544                } catch (PackageParserException e) {
15545                    // there was something wrong with the certificates we were given;
15546                    // try to pull them from the APK
15547                    PackageParser.collectCertificates(pkg, parseFlags);
15548                }
15549            } else {
15550                PackageParser.collectCertificates(pkg, parseFlags);
15551            }
15552        } catch (PackageParserException e) {
15553            res.setError("Failed collect during installPackageLI", e);
15554            return;
15555        }
15556
15557        // Get rid of all references to package scan path via parser.
15558        pp = null;
15559        String oldCodePath = null;
15560        boolean systemApp = false;
15561        synchronized (mPackages) {
15562            // Check if installing already existing package
15563            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15564                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15565                if (pkg.mOriginalPackages != null
15566                        && pkg.mOriginalPackages.contains(oldName)
15567                        && mPackages.containsKey(oldName)) {
15568                    // This package is derived from an original package,
15569                    // and this device has been updating from that original
15570                    // name.  We must continue using the original name, so
15571                    // rename the new package here.
15572                    pkg.setPackageName(oldName);
15573                    pkgName = pkg.packageName;
15574                    replace = true;
15575                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15576                            + oldName + " pkgName=" + pkgName);
15577                } else if (mPackages.containsKey(pkgName)) {
15578                    // This package, under its official name, already exists
15579                    // on the device; we should replace it.
15580                    replace = true;
15581                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15582                }
15583
15584                // Child packages are installed through the parent package
15585                if (pkg.parentPackage != null) {
15586                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15587                            "Package " + pkg.packageName + " is child of package "
15588                                    + pkg.parentPackage.parentPackage + ". Child packages "
15589                                    + "can be updated only through the parent package.");
15590                    return;
15591                }
15592
15593                if (replace) {
15594                    // Prevent apps opting out from runtime permissions
15595                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15596                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15597                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15598                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15599                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15600                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15601                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15602                                        + " doesn't support runtime permissions but the old"
15603                                        + " target SDK " + oldTargetSdk + " does.");
15604                        return;
15605                    }
15606
15607                    // Prevent installing of child packages
15608                    if (oldPackage.parentPackage != null) {
15609                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15610                                "Package " + pkg.packageName + " is child of package "
15611                                        + oldPackage.parentPackage + ". Child packages "
15612                                        + "can be updated only through the parent package.");
15613                        return;
15614                    }
15615                }
15616            }
15617
15618            PackageSetting ps = mSettings.mPackages.get(pkgName);
15619            if (ps != null) {
15620                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15621
15622                // Quick sanity check that we're signed correctly if updating;
15623                // we'll check this again later when scanning, but we want to
15624                // bail early here before tripping over redefined permissions.
15625                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15626                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15627                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15628                                + pkg.packageName + " upgrade keys do not match the "
15629                                + "previously installed version");
15630                        return;
15631                    }
15632                } else {
15633                    try {
15634                        verifySignaturesLP(ps, pkg);
15635                    } catch (PackageManagerException e) {
15636                        res.setError(e.error, e.getMessage());
15637                        return;
15638                    }
15639                }
15640
15641                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15642                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15643                    systemApp = (ps.pkg.applicationInfo.flags &
15644                            ApplicationInfo.FLAG_SYSTEM) != 0;
15645                }
15646                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15647            }
15648
15649            // Check whether the newly-scanned package wants to define an already-defined perm
15650            int N = pkg.permissions.size();
15651            for (int i = N-1; i >= 0; i--) {
15652                PackageParser.Permission perm = pkg.permissions.get(i);
15653                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15654                if (bp != null) {
15655                    // If the defining package is signed with our cert, it's okay.  This
15656                    // also includes the "updating the same package" case, of course.
15657                    // "updating same package" could also involve key-rotation.
15658                    final boolean sigsOk;
15659                    if (bp.sourcePackage.equals(pkg.packageName)
15660                            && (bp.packageSetting instanceof PackageSetting)
15661                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15662                                    scanFlags))) {
15663                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15664                    } else {
15665                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15666                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15667                    }
15668                    if (!sigsOk) {
15669                        // If the owning package is the system itself, we log but allow
15670                        // install to proceed; we fail the install on all other permission
15671                        // redefinitions.
15672                        if (!bp.sourcePackage.equals("android")) {
15673                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15674                                    + pkg.packageName + " attempting to redeclare permission "
15675                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15676                            res.origPermission = perm.info.name;
15677                            res.origPackage = bp.sourcePackage;
15678                            return;
15679                        } else {
15680                            Slog.w(TAG, "Package " + pkg.packageName
15681                                    + " attempting to redeclare system permission "
15682                                    + perm.info.name + "; ignoring new declaration");
15683                            pkg.permissions.remove(i);
15684                        }
15685                    }
15686                }
15687            }
15688        }
15689
15690        if (systemApp) {
15691            if (onExternal) {
15692                // Abort update; system app can't be replaced with app on sdcard
15693                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15694                        "Cannot install updates to system apps on sdcard");
15695                return;
15696            } else if (ephemeral) {
15697                // Abort update; system app can't be replaced with an ephemeral app
15698                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15699                        "Cannot update a system app with an ephemeral app");
15700                return;
15701            }
15702        }
15703
15704        if (args.move != null) {
15705            // We did an in-place move, so dex is ready to roll
15706            scanFlags |= SCAN_NO_DEX;
15707            scanFlags |= SCAN_MOVE;
15708
15709            synchronized (mPackages) {
15710                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15711                if (ps == null) {
15712                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15713                            "Missing settings for moved package " + pkgName);
15714                }
15715
15716                // We moved the entire application as-is, so bring over the
15717                // previously derived ABI information.
15718                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15719                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15720            }
15721
15722        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15723            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15724            scanFlags |= SCAN_NO_DEX;
15725
15726            try {
15727                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15728                    args.abiOverride : pkg.cpuAbiOverride);
15729                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15730                        true /*extractLibs*/, mAppLib32InstallDir);
15731            } catch (PackageManagerException pme) {
15732                Slog.e(TAG, "Error deriving application ABI", pme);
15733                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15734                return;
15735            }
15736
15737            // Shared libraries for the package need to be updated.
15738            synchronized (mPackages) {
15739                try {
15740                    updateSharedLibrariesLPr(pkg, null);
15741                } catch (PackageManagerException e) {
15742                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15743                }
15744            }
15745            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15746            // Do not run PackageDexOptimizer through the local performDexOpt
15747            // method because `pkg` may not be in `mPackages` yet.
15748            //
15749            // Also, don't fail application installs if the dexopt step fails.
15750            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15751                    null /* instructionSets */, false /* checkProfiles */,
15752                    getCompilerFilterForReason(REASON_INSTALL),
15753                    getOrCreateCompilerPackageStats(pkg));
15754            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15755
15756            // Notify BackgroundDexOptService that the package has been changed.
15757            // If this is an update of a package which used to fail to compile,
15758            // BDOS will remove it from its blacklist.
15759            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15760        }
15761
15762        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15763            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15764            return;
15765        }
15766
15767        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15768
15769        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15770                "installPackageLI")) {
15771            if (replace) {
15772                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15773                        installerPackageName, res);
15774            } else {
15775                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15776                        args.user, installerPackageName, volumeUuid, res);
15777            }
15778        }
15779        synchronized (mPackages) {
15780            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15781            if (ps != null) {
15782                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15783            }
15784
15785            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15786            for (int i = 0; i < childCount; i++) {
15787                PackageParser.Package childPkg = pkg.childPackages.get(i);
15788                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15789                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15790                if (childPs != null) {
15791                    childRes.newUsers = childPs.queryInstalledUsers(
15792                            sUserManager.getUserIds(), true);
15793                }
15794            }
15795        }
15796    }
15797
15798    private void startIntentFilterVerifications(int userId, boolean replacing,
15799            PackageParser.Package pkg) {
15800        if (mIntentFilterVerifierComponent == null) {
15801            Slog.w(TAG, "No IntentFilter verification will not be done as "
15802                    + "there is no IntentFilterVerifier available!");
15803            return;
15804        }
15805
15806        final int verifierUid = getPackageUid(
15807                mIntentFilterVerifierComponent.getPackageName(),
15808                MATCH_DEBUG_TRIAGED_MISSING,
15809                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15810
15811        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15812        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15813        mHandler.sendMessage(msg);
15814
15815        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15816        for (int i = 0; i < childCount; i++) {
15817            PackageParser.Package childPkg = pkg.childPackages.get(i);
15818            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15819            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15820            mHandler.sendMessage(msg);
15821        }
15822    }
15823
15824    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15825            PackageParser.Package pkg) {
15826        int size = pkg.activities.size();
15827        if (size == 0) {
15828            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15829                    "No activity, so no need to verify any IntentFilter!");
15830            return;
15831        }
15832
15833        final boolean hasDomainURLs = hasDomainURLs(pkg);
15834        if (!hasDomainURLs) {
15835            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15836                    "No domain URLs, so no need to verify any IntentFilter!");
15837            return;
15838        }
15839
15840        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15841                + " if any IntentFilter from the " + size
15842                + " Activities needs verification ...");
15843
15844        int count = 0;
15845        final String packageName = pkg.packageName;
15846
15847        synchronized (mPackages) {
15848            // If this is a new install and we see that we've already run verification for this
15849            // package, we have nothing to do: it means the state was restored from backup.
15850            if (!replacing) {
15851                IntentFilterVerificationInfo ivi =
15852                        mSettings.getIntentFilterVerificationLPr(packageName);
15853                if (ivi != null) {
15854                    if (DEBUG_DOMAIN_VERIFICATION) {
15855                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15856                                + ivi.getStatusString());
15857                    }
15858                    return;
15859                }
15860            }
15861
15862            // If any filters need to be verified, then all need to be.
15863            boolean needToVerify = false;
15864            for (PackageParser.Activity a : pkg.activities) {
15865                for (ActivityIntentInfo filter : a.intents) {
15866                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15867                        if (DEBUG_DOMAIN_VERIFICATION) {
15868                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15869                        }
15870                        needToVerify = true;
15871                        break;
15872                    }
15873                }
15874            }
15875
15876            if (needToVerify) {
15877                final int verificationId = mIntentFilterVerificationToken++;
15878                for (PackageParser.Activity a : pkg.activities) {
15879                    for (ActivityIntentInfo filter : a.intents) {
15880                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15881                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15882                                    "Verification needed for IntentFilter:" + filter.toString());
15883                            mIntentFilterVerifier.addOneIntentFilterVerification(
15884                                    verifierUid, userId, verificationId, filter, packageName);
15885                            count++;
15886                        }
15887                    }
15888                }
15889            }
15890        }
15891
15892        if (count > 0) {
15893            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15894                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15895                    +  " for userId:" + userId);
15896            mIntentFilterVerifier.startVerifications(userId);
15897        } else {
15898            if (DEBUG_DOMAIN_VERIFICATION) {
15899                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15900            }
15901        }
15902    }
15903
15904    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15905        final ComponentName cn  = filter.activity.getComponentName();
15906        final String packageName = cn.getPackageName();
15907
15908        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15909                packageName);
15910        if (ivi == null) {
15911            return true;
15912        }
15913        int status = ivi.getStatus();
15914        switch (status) {
15915            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15916            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15917                return true;
15918
15919            default:
15920                // Nothing to do
15921                return false;
15922        }
15923    }
15924
15925    private static boolean isMultiArch(ApplicationInfo info) {
15926        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15927    }
15928
15929    private static boolean isExternal(PackageParser.Package pkg) {
15930        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15931    }
15932
15933    private static boolean isExternal(PackageSetting ps) {
15934        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15935    }
15936
15937    private static boolean isEphemeral(PackageParser.Package pkg) {
15938        return pkg.applicationInfo.isEphemeralApp();
15939    }
15940
15941    private static boolean isEphemeral(PackageSetting ps) {
15942        return ps.pkg != null && isEphemeral(ps.pkg);
15943    }
15944
15945    private static boolean isSystemApp(PackageParser.Package pkg) {
15946        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15947    }
15948
15949    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15950        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15951    }
15952
15953    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15954        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15955    }
15956
15957    private static boolean isSystemApp(PackageSetting ps) {
15958        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15959    }
15960
15961    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15962        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15963    }
15964
15965    private int packageFlagsToInstallFlags(PackageSetting ps) {
15966        int installFlags = 0;
15967        if (isEphemeral(ps)) {
15968            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15969        }
15970        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15971            // This existing package was an external ASEC install when we have
15972            // the external flag without a UUID
15973            installFlags |= PackageManager.INSTALL_EXTERNAL;
15974        }
15975        if (ps.isForwardLocked()) {
15976            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15977        }
15978        return installFlags;
15979    }
15980
15981    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15982        if (isExternal(pkg)) {
15983            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15984                return StorageManager.UUID_PRIMARY_PHYSICAL;
15985            } else {
15986                return pkg.volumeUuid;
15987            }
15988        } else {
15989            return StorageManager.UUID_PRIVATE_INTERNAL;
15990        }
15991    }
15992
15993    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15994        if (isExternal(pkg)) {
15995            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15996                return mSettings.getExternalVersion();
15997            } else {
15998                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15999            }
16000        } else {
16001            return mSettings.getInternalVersion();
16002        }
16003    }
16004
16005    private void deleteTempPackageFiles() {
16006        final FilenameFilter filter = new FilenameFilter() {
16007            public boolean accept(File dir, String name) {
16008                return name.startsWith("vmdl") && name.endsWith(".tmp");
16009            }
16010        };
16011        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16012            file.delete();
16013        }
16014    }
16015
16016    @Override
16017    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16018            int flags) {
16019        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16020                flags);
16021    }
16022
16023    @Override
16024    public void deletePackage(final String packageName,
16025            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16026        mContext.enforceCallingOrSelfPermission(
16027                android.Manifest.permission.DELETE_PACKAGES, null);
16028        Preconditions.checkNotNull(packageName);
16029        Preconditions.checkNotNull(observer);
16030        final int uid = Binder.getCallingUid();
16031        if (!isOrphaned(packageName)
16032                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16033            try {
16034                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16035                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16036                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16037                observer.onUserActionRequired(intent);
16038            } catch (RemoteException re) {
16039            }
16040            return;
16041        }
16042        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16043        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16044        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16045            mContext.enforceCallingOrSelfPermission(
16046                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16047                    "deletePackage for user " + userId);
16048        }
16049
16050        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16051            try {
16052                observer.onPackageDeleted(packageName,
16053                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16054            } catch (RemoteException re) {
16055            }
16056            return;
16057        }
16058
16059        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16060            try {
16061                observer.onPackageDeleted(packageName,
16062                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16063            } catch (RemoteException re) {
16064            }
16065            return;
16066        }
16067
16068        if (DEBUG_REMOVE) {
16069            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16070                    + " deleteAllUsers: " + deleteAllUsers );
16071        }
16072        // Queue up an async operation since the package deletion may take a little while.
16073        mHandler.post(new Runnable() {
16074            public void run() {
16075                mHandler.removeCallbacks(this);
16076                int returnCode;
16077                if (!deleteAllUsers) {
16078                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16079                } else {
16080                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16081                    // If nobody is blocking uninstall, proceed with delete for all users
16082                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16083                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16084                    } else {
16085                        // Otherwise uninstall individually for users with blockUninstalls=false
16086                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16087                        for (int userId : users) {
16088                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16089                                returnCode = deletePackageX(packageName, userId, userFlags);
16090                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16091                                    Slog.w(TAG, "Package delete failed for user " + userId
16092                                            + ", returnCode " + returnCode);
16093                                }
16094                            }
16095                        }
16096                        // The app has only been marked uninstalled for certain users.
16097                        // We still need to report that delete was blocked
16098                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16099                    }
16100                }
16101                try {
16102                    observer.onPackageDeleted(packageName, returnCode, null);
16103                } catch (RemoteException e) {
16104                    Log.i(TAG, "Observer no longer exists.");
16105                } //end catch
16106            } //end run
16107        });
16108    }
16109
16110    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16111        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16112              || callingUid == Process.SYSTEM_UID) {
16113            return true;
16114        }
16115        final int callingUserId = UserHandle.getUserId(callingUid);
16116        // If the caller installed the pkgName, then allow it to silently uninstall.
16117        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16118            return true;
16119        }
16120
16121        // Allow package verifier to silently uninstall.
16122        if (mRequiredVerifierPackage != null &&
16123                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16124            return true;
16125        }
16126
16127        // Allow package uninstaller to silently uninstall.
16128        if (mRequiredUninstallerPackage != null &&
16129                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16130            return true;
16131        }
16132
16133        // Allow storage manager to silently uninstall.
16134        if (mStorageManagerPackage != null &&
16135                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16136            return true;
16137        }
16138        return false;
16139    }
16140
16141    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16142        int[] result = EMPTY_INT_ARRAY;
16143        for (int userId : userIds) {
16144            if (getBlockUninstallForUser(packageName, userId)) {
16145                result = ArrayUtils.appendInt(result, userId);
16146            }
16147        }
16148        return result;
16149    }
16150
16151    @Override
16152    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16153        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16154    }
16155
16156    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16157        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16158                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16159        try {
16160            if (dpm != null) {
16161                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16162                        /* callingUserOnly =*/ false);
16163                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16164                        : deviceOwnerComponentName.getPackageName();
16165                // Does the package contains the device owner?
16166                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16167                // this check is probably not needed, since DO should be registered as a device
16168                // admin on some user too. (Original bug for this: b/17657954)
16169                if (packageName.equals(deviceOwnerPackageName)) {
16170                    return true;
16171                }
16172                // Does it contain a device admin for any user?
16173                int[] users;
16174                if (userId == UserHandle.USER_ALL) {
16175                    users = sUserManager.getUserIds();
16176                } else {
16177                    users = new int[]{userId};
16178                }
16179                for (int i = 0; i < users.length; ++i) {
16180                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16181                        return true;
16182                    }
16183                }
16184            }
16185        } catch (RemoteException e) {
16186        }
16187        return false;
16188    }
16189
16190    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16191        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16192    }
16193
16194    /**
16195     *  This method is an internal method that could be get invoked either
16196     *  to delete an installed package or to clean up a failed installation.
16197     *  After deleting an installed package, a broadcast is sent to notify any
16198     *  listeners that the package has been removed. For cleaning up a failed
16199     *  installation, the broadcast is not necessary since the package's
16200     *  installation wouldn't have sent the initial broadcast either
16201     *  The key steps in deleting a package are
16202     *  deleting the package information in internal structures like mPackages,
16203     *  deleting the packages base directories through installd
16204     *  updating mSettings to reflect current status
16205     *  persisting settings for later use
16206     *  sending a broadcast if necessary
16207     */
16208    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16209        final PackageRemovedInfo info = new PackageRemovedInfo();
16210        final boolean res;
16211
16212        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16213                ? UserHandle.USER_ALL : userId;
16214
16215        if (isPackageDeviceAdmin(packageName, removeUser)) {
16216            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16217            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16218        }
16219
16220        PackageSetting uninstalledPs = null;
16221
16222        // for the uninstall-updates case and restricted profiles, remember the per-
16223        // user handle installed state
16224        int[] allUsers;
16225        synchronized (mPackages) {
16226            uninstalledPs = mSettings.mPackages.get(packageName);
16227            if (uninstalledPs == null) {
16228                Slog.w(TAG, "Not removing non-existent package " + packageName);
16229                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16230            }
16231            allUsers = sUserManager.getUserIds();
16232            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16233        }
16234
16235        final int freezeUser;
16236        if (isUpdatedSystemApp(uninstalledPs)
16237                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16238            // We're downgrading a system app, which will apply to all users, so
16239            // freeze them all during the downgrade
16240            freezeUser = UserHandle.USER_ALL;
16241        } else {
16242            freezeUser = removeUser;
16243        }
16244
16245        synchronized (mInstallLock) {
16246            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16247            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16248                    deleteFlags, "deletePackageX")) {
16249                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16250                        deleteFlags | REMOVE_CHATTY, info, true, null);
16251            }
16252            synchronized (mPackages) {
16253                if (res) {
16254                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16255                }
16256            }
16257        }
16258
16259        if (res) {
16260            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16261            info.sendPackageRemovedBroadcasts(killApp);
16262            info.sendSystemPackageUpdatedBroadcasts();
16263            info.sendSystemPackageAppearedBroadcasts();
16264        }
16265        // Force a gc here.
16266        Runtime.getRuntime().gc();
16267        // Delete the resources here after sending the broadcast to let
16268        // other processes clean up before deleting resources.
16269        if (info.args != null) {
16270            synchronized (mInstallLock) {
16271                info.args.doPostDeleteLI(true);
16272            }
16273        }
16274
16275        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16276    }
16277
16278    class PackageRemovedInfo {
16279        String removedPackage;
16280        int uid = -1;
16281        int removedAppId = -1;
16282        int[] origUsers;
16283        int[] removedUsers = null;
16284        boolean isRemovedPackageSystemUpdate = false;
16285        boolean isUpdate;
16286        boolean dataRemoved;
16287        boolean removedForAllUsers;
16288        // Clean up resources deleted packages.
16289        InstallArgs args = null;
16290        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16291        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16292
16293        void sendPackageRemovedBroadcasts(boolean killApp) {
16294            sendPackageRemovedBroadcastInternal(killApp);
16295            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16296            for (int i = 0; i < childCount; i++) {
16297                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16298                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16299            }
16300        }
16301
16302        void sendSystemPackageUpdatedBroadcasts() {
16303            if (isRemovedPackageSystemUpdate) {
16304                sendSystemPackageUpdatedBroadcastsInternal();
16305                final int childCount = (removedChildPackages != null)
16306                        ? removedChildPackages.size() : 0;
16307                for (int i = 0; i < childCount; i++) {
16308                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16309                    if (childInfo.isRemovedPackageSystemUpdate) {
16310                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16311                    }
16312                }
16313            }
16314        }
16315
16316        void sendSystemPackageAppearedBroadcasts() {
16317            final int packageCount = (appearedChildPackages != null)
16318                    ? appearedChildPackages.size() : 0;
16319            for (int i = 0; i < packageCount; i++) {
16320                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16321                sendPackageAddedForNewUsers(installedInfo.name, true,
16322                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16323            }
16324        }
16325
16326        private void sendSystemPackageUpdatedBroadcastsInternal() {
16327            Bundle extras = new Bundle(2);
16328            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16329            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16330            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16331                    extras, 0, null, null, null);
16332            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16333                    extras, 0, null, null, null);
16334            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16335                    null, 0, removedPackage, null, null);
16336        }
16337
16338        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16339            Bundle extras = new Bundle(2);
16340            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16341            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16342            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16343            if (isUpdate || isRemovedPackageSystemUpdate) {
16344                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16345            }
16346            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16347            if (removedPackage != null) {
16348                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16349                        extras, 0, null, null, removedUsers);
16350                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16351                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16352                            removedPackage, extras, 0, null, null, removedUsers);
16353                }
16354            }
16355            if (removedAppId >= 0) {
16356                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16357                        removedUsers);
16358            }
16359        }
16360    }
16361
16362    /*
16363     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16364     * flag is not set, the data directory is removed as well.
16365     * make sure this flag is set for partially installed apps. If not its meaningless to
16366     * delete a partially installed application.
16367     */
16368    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16369            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16370        String packageName = ps.name;
16371        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16372        // Retrieve object to delete permissions for shared user later on
16373        final PackageParser.Package deletedPkg;
16374        final PackageSetting deletedPs;
16375        // reader
16376        synchronized (mPackages) {
16377            deletedPkg = mPackages.get(packageName);
16378            deletedPs = mSettings.mPackages.get(packageName);
16379            if (outInfo != null) {
16380                outInfo.removedPackage = packageName;
16381                outInfo.removedUsers = deletedPs != null
16382                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16383                        : null;
16384            }
16385        }
16386
16387        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16388
16389        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16390            final PackageParser.Package resolvedPkg;
16391            if (deletedPkg != null) {
16392                resolvedPkg = deletedPkg;
16393            } else {
16394                // We don't have a parsed package when it lives on an ejected
16395                // adopted storage device, so fake something together
16396                resolvedPkg = new PackageParser.Package(ps.name);
16397                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16398            }
16399            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16400                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16401            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16402            if (outInfo != null) {
16403                outInfo.dataRemoved = true;
16404            }
16405            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16406        }
16407
16408        // writer
16409        synchronized (mPackages) {
16410            if (deletedPs != null) {
16411                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16412                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16413                    clearDefaultBrowserIfNeeded(packageName);
16414                    if (outInfo != null) {
16415                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16416                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16417                    }
16418                    updatePermissionsLPw(deletedPs.name, null, 0);
16419                    if (deletedPs.sharedUser != null) {
16420                        // Remove permissions associated with package. Since runtime
16421                        // permissions are per user we have to kill the removed package
16422                        // or packages running under the shared user of the removed
16423                        // package if revoking the permissions requested only by the removed
16424                        // package is successful and this causes a change in gids.
16425                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16426                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16427                                    userId);
16428                            if (userIdToKill == UserHandle.USER_ALL
16429                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16430                                // If gids changed for this user, kill all affected packages.
16431                                mHandler.post(new Runnable() {
16432                                    @Override
16433                                    public void run() {
16434                                        // This has to happen with no lock held.
16435                                        killApplication(deletedPs.name, deletedPs.appId,
16436                                                KILL_APP_REASON_GIDS_CHANGED);
16437                                    }
16438                                });
16439                                break;
16440                            }
16441                        }
16442                    }
16443                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16444                }
16445                // make sure to preserve per-user disabled state if this removal was just
16446                // a downgrade of a system app to the factory package
16447                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16448                    if (DEBUG_REMOVE) {
16449                        Slog.d(TAG, "Propagating install state across downgrade");
16450                    }
16451                    for (int userId : allUserHandles) {
16452                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16453                        if (DEBUG_REMOVE) {
16454                            Slog.d(TAG, "    user " + userId + " => " + installed);
16455                        }
16456                        ps.setInstalled(installed, userId);
16457                    }
16458                }
16459            }
16460            // can downgrade to reader
16461            if (writeSettings) {
16462                // Save settings now
16463                mSettings.writeLPr();
16464            }
16465        }
16466        if (outInfo != null) {
16467            // A user ID was deleted here. Go through all users and remove it
16468            // from KeyStore.
16469            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16470        }
16471    }
16472
16473    static boolean locationIsPrivileged(File path) {
16474        try {
16475            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16476                    .getCanonicalPath();
16477            return path.getCanonicalPath().startsWith(privilegedAppDir);
16478        } catch (IOException e) {
16479            Slog.e(TAG, "Unable to access code path " + path);
16480        }
16481        return false;
16482    }
16483
16484    /*
16485     * Tries to delete system package.
16486     */
16487    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16488            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16489            boolean writeSettings) {
16490        if (deletedPs.parentPackageName != null) {
16491            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16492            return false;
16493        }
16494
16495        final boolean applyUserRestrictions
16496                = (allUserHandles != null) && (outInfo.origUsers != null);
16497        final PackageSetting disabledPs;
16498        // Confirm if the system package has been updated
16499        // An updated system app can be deleted. This will also have to restore
16500        // the system pkg from system partition
16501        // reader
16502        synchronized (mPackages) {
16503            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16504        }
16505
16506        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16507                + " disabledPs=" + disabledPs);
16508
16509        if (disabledPs == null) {
16510            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16511            return false;
16512        } else if (DEBUG_REMOVE) {
16513            Slog.d(TAG, "Deleting system pkg from data partition");
16514        }
16515
16516        if (DEBUG_REMOVE) {
16517            if (applyUserRestrictions) {
16518                Slog.d(TAG, "Remembering install states:");
16519                for (int userId : allUserHandles) {
16520                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16521                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16522                }
16523            }
16524        }
16525
16526        // Delete the updated package
16527        outInfo.isRemovedPackageSystemUpdate = true;
16528        if (outInfo.removedChildPackages != null) {
16529            final int childCount = (deletedPs.childPackageNames != null)
16530                    ? deletedPs.childPackageNames.size() : 0;
16531            for (int i = 0; i < childCount; i++) {
16532                String childPackageName = deletedPs.childPackageNames.get(i);
16533                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16534                        .contains(childPackageName)) {
16535                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16536                            childPackageName);
16537                    if (childInfo != null) {
16538                        childInfo.isRemovedPackageSystemUpdate = true;
16539                    }
16540                }
16541            }
16542        }
16543
16544        if (disabledPs.versionCode < deletedPs.versionCode) {
16545            // Delete data for downgrades
16546            flags &= ~PackageManager.DELETE_KEEP_DATA;
16547        } else {
16548            // Preserve data by setting flag
16549            flags |= PackageManager.DELETE_KEEP_DATA;
16550        }
16551
16552        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16553                outInfo, writeSettings, disabledPs.pkg);
16554        if (!ret) {
16555            return false;
16556        }
16557
16558        // writer
16559        synchronized (mPackages) {
16560            // Reinstate the old system package
16561            enableSystemPackageLPw(disabledPs.pkg);
16562            // Remove any native libraries from the upgraded package.
16563            removeNativeBinariesLI(deletedPs);
16564        }
16565
16566        // Install the system package
16567        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16568        int parseFlags = mDefParseFlags
16569                | PackageParser.PARSE_MUST_BE_APK
16570                | PackageParser.PARSE_IS_SYSTEM
16571                | PackageParser.PARSE_IS_SYSTEM_DIR;
16572        if (locationIsPrivileged(disabledPs.codePath)) {
16573            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16574        }
16575
16576        final PackageParser.Package newPkg;
16577        try {
16578            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16579                0 /* currentTime */, null);
16580        } catch (PackageManagerException e) {
16581            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16582                    + e.getMessage());
16583            return false;
16584        }
16585        try {
16586            // update shared libraries for the newly re-installed system package
16587            updateSharedLibrariesLPr(newPkg, null);
16588        } catch (PackageManagerException e) {
16589            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16590        }
16591
16592        prepareAppDataAfterInstallLIF(newPkg);
16593
16594        // writer
16595        synchronized (mPackages) {
16596            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16597
16598            // Propagate the permissions state as we do not want to drop on the floor
16599            // runtime permissions. The update permissions method below will take
16600            // care of removing obsolete permissions and grant install permissions.
16601            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16602            updatePermissionsLPw(newPkg.packageName, newPkg,
16603                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16604
16605            if (applyUserRestrictions) {
16606                if (DEBUG_REMOVE) {
16607                    Slog.d(TAG, "Propagating install state across reinstall");
16608                }
16609                for (int userId : allUserHandles) {
16610                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16611                    if (DEBUG_REMOVE) {
16612                        Slog.d(TAG, "    user " + userId + " => " + installed);
16613                    }
16614                    ps.setInstalled(installed, userId);
16615
16616                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16617                }
16618                // Regardless of writeSettings we need to ensure that this restriction
16619                // state propagation is persisted
16620                mSettings.writeAllUsersPackageRestrictionsLPr();
16621            }
16622            // can downgrade to reader here
16623            if (writeSettings) {
16624                mSettings.writeLPr();
16625            }
16626        }
16627        return true;
16628    }
16629
16630    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16631            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16632            PackageRemovedInfo outInfo, boolean writeSettings,
16633            PackageParser.Package replacingPackage) {
16634        synchronized (mPackages) {
16635            if (outInfo != null) {
16636                outInfo.uid = ps.appId;
16637            }
16638
16639            if (outInfo != null && outInfo.removedChildPackages != null) {
16640                final int childCount = (ps.childPackageNames != null)
16641                        ? ps.childPackageNames.size() : 0;
16642                for (int i = 0; i < childCount; i++) {
16643                    String childPackageName = ps.childPackageNames.get(i);
16644                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16645                    if (childPs == null) {
16646                        return false;
16647                    }
16648                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16649                            childPackageName);
16650                    if (childInfo != null) {
16651                        childInfo.uid = childPs.appId;
16652                    }
16653                }
16654            }
16655        }
16656
16657        // Delete package data from internal structures and also remove data if flag is set
16658        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16659
16660        // Delete the child packages data
16661        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16662        for (int i = 0; i < childCount; i++) {
16663            PackageSetting childPs;
16664            synchronized (mPackages) {
16665                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16666            }
16667            if (childPs != null) {
16668                PackageRemovedInfo childOutInfo = (outInfo != null
16669                        && outInfo.removedChildPackages != null)
16670                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16671                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16672                        && (replacingPackage != null
16673                        && !replacingPackage.hasChildPackage(childPs.name))
16674                        ? flags & ~DELETE_KEEP_DATA : flags;
16675                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16676                        deleteFlags, writeSettings);
16677            }
16678        }
16679
16680        // Delete application code and resources only for parent packages
16681        if (ps.parentPackageName == null) {
16682            if (deleteCodeAndResources && (outInfo != null)) {
16683                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16684                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16685                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16686            }
16687        }
16688
16689        return true;
16690    }
16691
16692    @Override
16693    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16694            int userId) {
16695        mContext.enforceCallingOrSelfPermission(
16696                android.Manifest.permission.DELETE_PACKAGES, null);
16697        synchronized (mPackages) {
16698            PackageSetting ps = mSettings.mPackages.get(packageName);
16699            if (ps == null) {
16700                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16701                return false;
16702            }
16703            if (!ps.getInstalled(userId)) {
16704                // Can't block uninstall for an app that is not installed or enabled.
16705                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16706                return false;
16707            }
16708            ps.setBlockUninstall(blockUninstall, userId);
16709            mSettings.writePackageRestrictionsLPr(userId);
16710        }
16711        return true;
16712    }
16713
16714    @Override
16715    public boolean getBlockUninstallForUser(String packageName, int userId) {
16716        synchronized (mPackages) {
16717            PackageSetting ps = mSettings.mPackages.get(packageName);
16718            if (ps == null) {
16719                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16720                return false;
16721            }
16722            return ps.getBlockUninstall(userId);
16723        }
16724    }
16725
16726    @Override
16727    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16728        int callingUid = Binder.getCallingUid();
16729        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16730            throw new SecurityException(
16731                    "setRequiredForSystemUser can only be run by the system or root");
16732        }
16733        synchronized (mPackages) {
16734            PackageSetting ps = mSettings.mPackages.get(packageName);
16735            if (ps == null) {
16736                Log.w(TAG, "Package doesn't exist: " + packageName);
16737                return false;
16738            }
16739            if (systemUserApp) {
16740                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16741            } else {
16742                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16743            }
16744            mSettings.writeLPr();
16745        }
16746        return true;
16747    }
16748
16749    /*
16750     * This method handles package deletion in general
16751     */
16752    private boolean deletePackageLIF(String packageName, UserHandle user,
16753            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16754            PackageRemovedInfo outInfo, boolean writeSettings,
16755            PackageParser.Package replacingPackage) {
16756        if (packageName == null) {
16757            Slog.w(TAG, "Attempt to delete null packageName.");
16758            return false;
16759        }
16760
16761        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16762
16763        PackageSetting ps;
16764
16765        synchronized (mPackages) {
16766            ps = mSettings.mPackages.get(packageName);
16767            if (ps == null) {
16768                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16769                return false;
16770            }
16771
16772            if (ps.parentPackageName != null && (!isSystemApp(ps)
16773                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16774                if (DEBUG_REMOVE) {
16775                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16776                            + ((user == null) ? UserHandle.USER_ALL : user));
16777                }
16778                final int removedUserId = (user != null) ? user.getIdentifier()
16779                        : UserHandle.USER_ALL;
16780                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16781                    return false;
16782                }
16783                markPackageUninstalledForUserLPw(ps, user);
16784                scheduleWritePackageRestrictionsLocked(user);
16785                return true;
16786            }
16787        }
16788
16789        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16790                && user.getIdentifier() != UserHandle.USER_ALL)) {
16791            // The caller is asking that the package only be deleted for a single
16792            // user.  To do this, we just mark its uninstalled state and delete
16793            // its data. If this is a system app, we only allow this to happen if
16794            // they have set the special DELETE_SYSTEM_APP which requests different
16795            // semantics than normal for uninstalling system apps.
16796            markPackageUninstalledForUserLPw(ps, user);
16797
16798            if (!isSystemApp(ps)) {
16799                // Do not uninstall the APK if an app should be cached
16800                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16801                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16802                    // Other user still have this package installed, so all
16803                    // we need to do is clear this user's data and save that
16804                    // it is uninstalled.
16805                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16806                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16807                        return false;
16808                    }
16809                    scheduleWritePackageRestrictionsLocked(user);
16810                    return true;
16811                } else {
16812                    // We need to set it back to 'installed' so the uninstall
16813                    // broadcasts will be sent correctly.
16814                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16815                    ps.setInstalled(true, user.getIdentifier());
16816                }
16817            } else {
16818                // This is a system app, so we assume that the
16819                // other users still have this package installed, so all
16820                // we need to do is clear this user's data and save that
16821                // it is uninstalled.
16822                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16823                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16824                    return false;
16825                }
16826                scheduleWritePackageRestrictionsLocked(user);
16827                return true;
16828            }
16829        }
16830
16831        // If we are deleting a composite package for all users, keep track
16832        // of result for each child.
16833        if (ps.childPackageNames != null && outInfo != null) {
16834            synchronized (mPackages) {
16835                final int childCount = ps.childPackageNames.size();
16836                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16837                for (int i = 0; i < childCount; i++) {
16838                    String childPackageName = ps.childPackageNames.get(i);
16839                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16840                    childInfo.removedPackage = childPackageName;
16841                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16842                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16843                    if (childPs != null) {
16844                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16845                    }
16846                }
16847            }
16848        }
16849
16850        boolean ret = false;
16851        if (isSystemApp(ps)) {
16852            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16853            // When an updated system application is deleted we delete the existing resources
16854            // as well and fall back to existing code in system partition
16855            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16856        } else {
16857            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16858            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16859                    outInfo, writeSettings, replacingPackage);
16860        }
16861
16862        // Take a note whether we deleted the package for all users
16863        if (outInfo != null) {
16864            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16865            if (outInfo.removedChildPackages != null) {
16866                synchronized (mPackages) {
16867                    final int childCount = outInfo.removedChildPackages.size();
16868                    for (int i = 0; i < childCount; i++) {
16869                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16870                        if (childInfo != null) {
16871                            childInfo.removedForAllUsers = mPackages.get(
16872                                    childInfo.removedPackage) == null;
16873                        }
16874                    }
16875                }
16876            }
16877            // If we uninstalled an update to a system app there may be some
16878            // child packages that appeared as they are declared in the system
16879            // app but were not declared in the update.
16880            if (isSystemApp(ps)) {
16881                synchronized (mPackages) {
16882                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16883                    final int childCount = (updatedPs.childPackageNames != null)
16884                            ? updatedPs.childPackageNames.size() : 0;
16885                    for (int i = 0; i < childCount; i++) {
16886                        String childPackageName = updatedPs.childPackageNames.get(i);
16887                        if (outInfo.removedChildPackages == null
16888                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16889                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16890                            if (childPs == null) {
16891                                continue;
16892                            }
16893                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16894                            installRes.name = childPackageName;
16895                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16896                            installRes.pkg = mPackages.get(childPackageName);
16897                            installRes.uid = childPs.pkg.applicationInfo.uid;
16898                            if (outInfo.appearedChildPackages == null) {
16899                                outInfo.appearedChildPackages = new ArrayMap<>();
16900                            }
16901                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16902                        }
16903                    }
16904                }
16905            }
16906        }
16907
16908        return ret;
16909    }
16910
16911    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16912        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16913                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16914        for (int nextUserId : userIds) {
16915            if (DEBUG_REMOVE) {
16916                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16917            }
16918            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16919                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16920                    false /*hidden*/, false /*suspended*/, null, null, null,
16921                    false /*blockUninstall*/,
16922                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16923        }
16924    }
16925
16926    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16927            PackageRemovedInfo outInfo) {
16928        final PackageParser.Package pkg;
16929        synchronized (mPackages) {
16930            pkg = mPackages.get(ps.name);
16931        }
16932
16933        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16934                : new int[] {userId};
16935        for (int nextUserId : userIds) {
16936            if (DEBUG_REMOVE) {
16937                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16938                        + nextUserId);
16939            }
16940
16941            destroyAppDataLIF(pkg, userId,
16942                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16943            destroyAppProfilesLIF(pkg, userId);
16944            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16945            schedulePackageCleaning(ps.name, nextUserId, false);
16946            synchronized (mPackages) {
16947                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16948                    scheduleWritePackageRestrictionsLocked(nextUserId);
16949                }
16950                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16951            }
16952        }
16953
16954        if (outInfo != null) {
16955            outInfo.removedPackage = ps.name;
16956            outInfo.removedAppId = ps.appId;
16957            outInfo.removedUsers = userIds;
16958        }
16959
16960        return true;
16961    }
16962
16963    private final class ClearStorageConnection implements ServiceConnection {
16964        IMediaContainerService mContainerService;
16965
16966        @Override
16967        public void onServiceConnected(ComponentName name, IBinder service) {
16968            synchronized (this) {
16969                mContainerService = IMediaContainerService.Stub
16970                        .asInterface(Binder.allowBlocking(service));
16971                notifyAll();
16972            }
16973        }
16974
16975        @Override
16976        public void onServiceDisconnected(ComponentName name) {
16977        }
16978    }
16979
16980    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16981        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16982
16983        final boolean mounted;
16984        if (Environment.isExternalStorageEmulated()) {
16985            mounted = true;
16986        } else {
16987            final String status = Environment.getExternalStorageState();
16988
16989            mounted = status.equals(Environment.MEDIA_MOUNTED)
16990                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16991        }
16992
16993        if (!mounted) {
16994            return;
16995        }
16996
16997        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16998        int[] users;
16999        if (userId == UserHandle.USER_ALL) {
17000            users = sUserManager.getUserIds();
17001        } else {
17002            users = new int[] { userId };
17003        }
17004        final ClearStorageConnection conn = new ClearStorageConnection();
17005        if (mContext.bindServiceAsUser(
17006                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17007            try {
17008                for (int curUser : users) {
17009                    long timeout = SystemClock.uptimeMillis() + 5000;
17010                    synchronized (conn) {
17011                        long now;
17012                        while (conn.mContainerService == null &&
17013                                (now = SystemClock.uptimeMillis()) < timeout) {
17014                            try {
17015                                conn.wait(timeout - now);
17016                            } catch (InterruptedException e) {
17017                            }
17018                        }
17019                    }
17020                    if (conn.mContainerService == null) {
17021                        return;
17022                    }
17023
17024                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17025                    clearDirectory(conn.mContainerService,
17026                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17027                    if (allData) {
17028                        clearDirectory(conn.mContainerService,
17029                                userEnv.buildExternalStorageAppDataDirs(packageName));
17030                        clearDirectory(conn.mContainerService,
17031                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17032                    }
17033                }
17034            } finally {
17035                mContext.unbindService(conn);
17036            }
17037        }
17038    }
17039
17040    @Override
17041    public void clearApplicationProfileData(String packageName) {
17042        enforceSystemOrRoot("Only the system can clear all profile data");
17043
17044        final PackageParser.Package pkg;
17045        synchronized (mPackages) {
17046            pkg = mPackages.get(packageName);
17047        }
17048
17049        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17050            synchronized (mInstallLock) {
17051                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17052                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17053                        true /* removeBaseMarker */);
17054            }
17055        }
17056    }
17057
17058    @Override
17059    public void clearApplicationUserData(final String packageName,
17060            final IPackageDataObserver observer, final int userId) {
17061        mContext.enforceCallingOrSelfPermission(
17062                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17063
17064        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17065                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17066
17067        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17068            throw new SecurityException("Cannot clear data for a protected package: "
17069                    + packageName);
17070        }
17071        // Queue up an async operation since the package deletion may take a little while.
17072        mHandler.post(new Runnable() {
17073            public void run() {
17074                mHandler.removeCallbacks(this);
17075                final boolean succeeded;
17076                try (PackageFreezer freezer = freezePackage(packageName,
17077                        "clearApplicationUserData")) {
17078                    synchronized (mInstallLock) {
17079                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17080                    }
17081                    clearExternalStorageDataSync(packageName, userId, true);
17082                }
17083                if (succeeded) {
17084                    // invoke DeviceStorageMonitor's update method to clear any notifications
17085                    DeviceStorageMonitorInternal dsm = LocalServices
17086                            .getService(DeviceStorageMonitorInternal.class);
17087                    if (dsm != null) {
17088                        dsm.checkMemory();
17089                    }
17090                }
17091                if(observer != null) {
17092                    try {
17093                        observer.onRemoveCompleted(packageName, succeeded);
17094                    } catch (RemoteException e) {
17095                        Log.i(TAG, "Observer no longer exists.");
17096                    }
17097                } //end if observer
17098            } //end run
17099        });
17100    }
17101
17102    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17103        if (packageName == null) {
17104            Slog.w(TAG, "Attempt to delete null packageName.");
17105            return false;
17106        }
17107
17108        // Try finding details about the requested package
17109        PackageParser.Package pkg;
17110        synchronized (mPackages) {
17111            pkg = mPackages.get(packageName);
17112            if (pkg == null) {
17113                final PackageSetting ps = mSettings.mPackages.get(packageName);
17114                if (ps != null) {
17115                    pkg = ps.pkg;
17116                }
17117            }
17118
17119            if (pkg == null) {
17120                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17121                return false;
17122            }
17123
17124            PackageSetting ps = (PackageSetting) pkg.mExtras;
17125            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17126        }
17127
17128        clearAppDataLIF(pkg, userId,
17129                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17130
17131        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17132        removeKeystoreDataIfNeeded(userId, appId);
17133
17134        UserManagerInternal umInternal = getUserManagerInternal();
17135        final int flags;
17136        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17137            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17138        } else if (umInternal.isUserRunning(userId)) {
17139            flags = StorageManager.FLAG_STORAGE_DE;
17140        } else {
17141            flags = 0;
17142        }
17143        prepareAppDataContentsLIF(pkg, userId, flags);
17144
17145        return true;
17146    }
17147
17148    /**
17149     * Reverts user permission state changes (permissions and flags) in
17150     * all packages for a given user.
17151     *
17152     * @param userId The device user for which to do a reset.
17153     */
17154    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17155        final int packageCount = mPackages.size();
17156        for (int i = 0; i < packageCount; i++) {
17157            PackageParser.Package pkg = mPackages.valueAt(i);
17158            PackageSetting ps = (PackageSetting) pkg.mExtras;
17159            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17160        }
17161    }
17162
17163    private void resetNetworkPolicies(int userId) {
17164        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17165    }
17166
17167    /**
17168     * Reverts user permission state changes (permissions and flags).
17169     *
17170     * @param ps The package for which to reset.
17171     * @param userId The device user for which to do a reset.
17172     */
17173    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17174            final PackageSetting ps, final int userId) {
17175        if (ps.pkg == null) {
17176            return;
17177        }
17178
17179        // These are flags that can change base on user actions.
17180        final int userSettableMask = FLAG_PERMISSION_USER_SET
17181                | FLAG_PERMISSION_USER_FIXED
17182                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17183                | FLAG_PERMISSION_REVIEW_REQUIRED;
17184
17185        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17186                | FLAG_PERMISSION_POLICY_FIXED;
17187
17188        boolean writeInstallPermissions = false;
17189        boolean writeRuntimePermissions = false;
17190
17191        final int permissionCount = ps.pkg.requestedPermissions.size();
17192        for (int i = 0; i < permissionCount; i++) {
17193            String permission = ps.pkg.requestedPermissions.get(i);
17194
17195            BasePermission bp = mSettings.mPermissions.get(permission);
17196            if (bp == null) {
17197                continue;
17198            }
17199
17200            // If shared user we just reset the state to which only this app contributed.
17201            if (ps.sharedUser != null) {
17202                boolean used = false;
17203                final int packageCount = ps.sharedUser.packages.size();
17204                for (int j = 0; j < packageCount; j++) {
17205                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17206                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17207                            && pkg.pkg.requestedPermissions.contains(permission)) {
17208                        used = true;
17209                        break;
17210                    }
17211                }
17212                if (used) {
17213                    continue;
17214                }
17215            }
17216
17217            PermissionsState permissionsState = ps.getPermissionsState();
17218
17219            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17220
17221            // Always clear the user settable flags.
17222            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17223                    bp.name) != null;
17224            // If permission review is enabled and this is a legacy app, mark the
17225            // permission as requiring a review as this is the initial state.
17226            int flags = 0;
17227            if (mPermissionReviewRequired
17228                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17229                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17230            }
17231            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17232                if (hasInstallState) {
17233                    writeInstallPermissions = true;
17234                } else {
17235                    writeRuntimePermissions = true;
17236                }
17237            }
17238
17239            // Below is only runtime permission handling.
17240            if (!bp.isRuntime()) {
17241                continue;
17242            }
17243
17244            // Never clobber system or policy.
17245            if ((oldFlags & policyOrSystemFlags) != 0) {
17246                continue;
17247            }
17248
17249            // If this permission was granted by default, make sure it is.
17250            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17251                if (permissionsState.grantRuntimePermission(bp, userId)
17252                        != PERMISSION_OPERATION_FAILURE) {
17253                    writeRuntimePermissions = true;
17254                }
17255            // If permission review is enabled the permissions for a legacy apps
17256            // are represented as constantly granted runtime ones, so don't revoke.
17257            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17258                // Otherwise, reset the permission.
17259                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17260                switch (revokeResult) {
17261                    case PERMISSION_OPERATION_SUCCESS:
17262                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17263                        writeRuntimePermissions = true;
17264                        final int appId = ps.appId;
17265                        mHandler.post(new Runnable() {
17266                            @Override
17267                            public void run() {
17268                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17269                            }
17270                        });
17271                    } break;
17272                }
17273            }
17274        }
17275
17276        // Synchronously write as we are taking permissions away.
17277        if (writeRuntimePermissions) {
17278            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17279        }
17280
17281        // Synchronously write as we are taking permissions away.
17282        if (writeInstallPermissions) {
17283            mSettings.writeLPr();
17284        }
17285    }
17286
17287    /**
17288     * Remove entries from the keystore daemon. Will only remove it if the
17289     * {@code appId} is valid.
17290     */
17291    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17292        if (appId < 0) {
17293            return;
17294        }
17295
17296        final KeyStore keyStore = KeyStore.getInstance();
17297        if (keyStore != null) {
17298            if (userId == UserHandle.USER_ALL) {
17299                for (final int individual : sUserManager.getUserIds()) {
17300                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17301                }
17302            } else {
17303                keyStore.clearUid(UserHandle.getUid(userId, appId));
17304            }
17305        } else {
17306            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17307        }
17308    }
17309
17310    @Override
17311    public void deleteApplicationCacheFiles(final String packageName,
17312            final IPackageDataObserver observer) {
17313        final int userId = UserHandle.getCallingUserId();
17314        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17315    }
17316
17317    @Override
17318    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17319            final IPackageDataObserver observer) {
17320        mContext.enforceCallingOrSelfPermission(
17321                android.Manifest.permission.DELETE_CACHE_FILES, null);
17322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17323                /* requireFullPermission= */ true, /* checkShell= */ false,
17324                "delete application cache files");
17325
17326        final PackageParser.Package pkg;
17327        synchronized (mPackages) {
17328            pkg = mPackages.get(packageName);
17329        }
17330
17331        // Queue up an async operation since the package deletion may take a little while.
17332        mHandler.post(new Runnable() {
17333            public void run() {
17334                synchronized (mInstallLock) {
17335                    final int flags = StorageManager.FLAG_STORAGE_DE
17336                            | StorageManager.FLAG_STORAGE_CE;
17337                    // We're only clearing cache files, so we don't care if the
17338                    // app is unfrozen and still able to run
17339                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17340                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17341                }
17342                clearExternalStorageDataSync(packageName, userId, false);
17343                if (observer != null) {
17344                    try {
17345                        observer.onRemoveCompleted(packageName, true);
17346                    } catch (RemoteException e) {
17347                        Log.i(TAG, "Observer no longer exists.");
17348                    }
17349                }
17350            }
17351        });
17352    }
17353
17354    @Override
17355    public void getPackageSizeInfo(final String packageName, int userHandle,
17356            final IPackageStatsObserver observer) {
17357        mContext.enforceCallingOrSelfPermission(
17358                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17359        if (packageName == null) {
17360            throw new IllegalArgumentException("Attempt to get size of null packageName");
17361        }
17362
17363        PackageStats stats = new PackageStats(packageName, userHandle);
17364
17365        /*
17366         * Queue up an async operation since the package measurement may take a
17367         * little while.
17368         */
17369        Message msg = mHandler.obtainMessage(INIT_COPY);
17370        msg.obj = new MeasureParams(stats, observer);
17371        mHandler.sendMessage(msg);
17372    }
17373
17374    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17375        final PackageSetting ps;
17376        synchronized (mPackages) {
17377            ps = mSettings.mPackages.get(packageName);
17378            if (ps == null) {
17379                Slog.w(TAG, "Failed to find settings for " + packageName);
17380                return false;
17381            }
17382        }
17383        try {
17384            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17385                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17386                    ps.getCeDataInode(userId), ps.codePathString, stats);
17387        } catch (InstallerException e) {
17388            Slog.w(TAG, String.valueOf(e));
17389            return false;
17390        }
17391
17392        // For now, ignore code size of packages on system partition
17393        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17394            stats.codeSize = 0;
17395        }
17396
17397        return true;
17398    }
17399
17400    private int getUidTargetSdkVersionLockedLPr(int uid) {
17401        Object obj = mSettings.getUserIdLPr(uid);
17402        if (obj instanceof SharedUserSetting) {
17403            final SharedUserSetting sus = (SharedUserSetting) obj;
17404            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17405            final Iterator<PackageSetting> it = sus.packages.iterator();
17406            while (it.hasNext()) {
17407                final PackageSetting ps = it.next();
17408                if (ps.pkg != null) {
17409                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17410                    if (v < vers) vers = v;
17411                }
17412            }
17413            return vers;
17414        } else if (obj instanceof PackageSetting) {
17415            final PackageSetting ps = (PackageSetting) obj;
17416            if (ps.pkg != null) {
17417                return ps.pkg.applicationInfo.targetSdkVersion;
17418            }
17419        }
17420        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17421    }
17422
17423    @Override
17424    public void addPreferredActivity(IntentFilter filter, int match,
17425            ComponentName[] set, ComponentName activity, int userId) {
17426        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17427                "Adding preferred");
17428    }
17429
17430    private void addPreferredActivityInternal(IntentFilter filter, int match,
17431            ComponentName[] set, ComponentName activity, boolean always, int userId,
17432            String opname) {
17433        // writer
17434        int callingUid = Binder.getCallingUid();
17435        enforceCrossUserPermission(callingUid, userId,
17436                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17437        if (filter.countActions() == 0) {
17438            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17439            return;
17440        }
17441        synchronized (mPackages) {
17442            if (mContext.checkCallingOrSelfPermission(
17443                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17444                    != PackageManager.PERMISSION_GRANTED) {
17445                if (getUidTargetSdkVersionLockedLPr(callingUid)
17446                        < Build.VERSION_CODES.FROYO) {
17447                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17448                            + callingUid);
17449                    return;
17450                }
17451                mContext.enforceCallingOrSelfPermission(
17452                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17453            }
17454
17455            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17456            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17457                    + userId + ":");
17458            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17459            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17460            scheduleWritePackageRestrictionsLocked(userId);
17461            postPreferredActivityChangedBroadcast(userId);
17462        }
17463    }
17464
17465    private void postPreferredActivityChangedBroadcast(int userId) {
17466        mHandler.post(() -> {
17467            final IActivityManager am = ActivityManager.getService();
17468            if (am == null) {
17469                return;
17470            }
17471
17472            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17473            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17474            try {
17475                am.broadcastIntent(null, intent, null, null,
17476                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17477                        null, false, false, userId);
17478            } catch (RemoteException e) {
17479            }
17480        });
17481    }
17482
17483    @Override
17484    public void replacePreferredActivity(IntentFilter filter, int match,
17485            ComponentName[] set, ComponentName activity, int userId) {
17486        if (filter.countActions() != 1) {
17487            throw new IllegalArgumentException(
17488                    "replacePreferredActivity expects filter to have only 1 action.");
17489        }
17490        if (filter.countDataAuthorities() != 0
17491                || filter.countDataPaths() != 0
17492                || filter.countDataSchemes() > 1
17493                || filter.countDataTypes() != 0) {
17494            throw new IllegalArgumentException(
17495                    "replacePreferredActivity expects filter to have no data authorities, " +
17496                    "paths, or types; and at most one scheme.");
17497        }
17498
17499        final int callingUid = Binder.getCallingUid();
17500        enforceCrossUserPermission(callingUid, userId,
17501                true /* requireFullPermission */, false /* checkShell */,
17502                "replace preferred activity");
17503        synchronized (mPackages) {
17504            if (mContext.checkCallingOrSelfPermission(
17505                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17506                    != PackageManager.PERMISSION_GRANTED) {
17507                if (getUidTargetSdkVersionLockedLPr(callingUid)
17508                        < Build.VERSION_CODES.FROYO) {
17509                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17510                            + Binder.getCallingUid());
17511                    return;
17512                }
17513                mContext.enforceCallingOrSelfPermission(
17514                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17515            }
17516
17517            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17518            if (pir != null) {
17519                // Get all of the existing entries that exactly match this filter.
17520                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17521                if (existing != null && existing.size() == 1) {
17522                    PreferredActivity cur = existing.get(0);
17523                    if (DEBUG_PREFERRED) {
17524                        Slog.i(TAG, "Checking replace of preferred:");
17525                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17526                        if (!cur.mPref.mAlways) {
17527                            Slog.i(TAG, "  -- CUR; not mAlways!");
17528                        } else {
17529                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17530                            Slog.i(TAG, "  -- CUR: mSet="
17531                                    + Arrays.toString(cur.mPref.mSetComponents));
17532                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17533                            Slog.i(TAG, "  -- NEW: mMatch="
17534                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17535                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17536                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17537                        }
17538                    }
17539                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17540                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17541                            && cur.mPref.sameSet(set)) {
17542                        // Setting the preferred activity to what it happens to be already
17543                        if (DEBUG_PREFERRED) {
17544                            Slog.i(TAG, "Replacing with same preferred activity "
17545                                    + cur.mPref.mShortComponent + " for user "
17546                                    + userId + ":");
17547                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17548                        }
17549                        return;
17550                    }
17551                }
17552
17553                if (existing != null) {
17554                    if (DEBUG_PREFERRED) {
17555                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17556                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17557                    }
17558                    for (int i = 0; i < existing.size(); i++) {
17559                        PreferredActivity pa = existing.get(i);
17560                        if (DEBUG_PREFERRED) {
17561                            Slog.i(TAG, "Removing existing preferred activity "
17562                                    + pa.mPref.mComponent + ":");
17563                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17564                        }
17565                        pir.removeFilter(pa);
17566                    }
17567                }
17568            }
17569            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17570                    "Replacing preferred");
17571        }
17572    }
17573
17574    @Override
17575    public void clearPackagePreferredActivities(String packageName) {
17576        final int uid = Binder.getCallingUid();
17577        // writer
17578        synchronized (mPackages) {
17579            PackageParser.Package pkg = mPackages.get(packageName);
17580            if (pkg == null || pkg.applicationInfo.uid != uid) {
17581                if (mContext.checkCallingOrSelfPermission(
17582                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17583                        != PackageManager.PERMISSION_GRANTED) {
17584                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17585                            < Build.VERSION_CODES.FROYO) {
17586                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17587                                + Binder.getCallingUid());
17588                        return;
17589                    }
17590                    mContext.enforceCallingOrSelfPermission(
17591                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17592                }
17593            }
17594
17595            int user = UserHandle.getCallingUserId();
17596            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17597                scheduleWritePackageRestrictionsLocked(user);
17598            }
17599        }
17600    }
17601
17602    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17603    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17604        ArrayList<PreferredActivity> removed = null;
17605        boolean changed = false;
17606        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17607            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17608            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17609            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17610                continue;
17611            }
17612            Iterator<PreferredActivity> it = pir.filterIterator();
17613            while (it.hasNext()) {
17614                PreferredActivity pa = it.next();
17615                // Mark entry for removal only if it matches the package name
17616                // and the entry is of type "always".
17617                if (packageName == null ||
17618                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17619                                && pa.mPref.mAlways)) {
17620                    if (removed == null) {
17621                        removed = new ArrayList<PreferredActivity>();
17622                    }
17623                    removed.add(pa);
17624                }
17625            }
17626            if (removed != null) {
17627                for (int j=0; j<removed.size(); j++) {
17628                    PreferredActivity pa = removed.get(j);
17629                    pir.removeFilter(pa);
17630                }
17631                changed = true;
17632            }
17633        }
17634        if (changed) {
17635            postPreferredActivityChangedBroadcast(userId);
17636        }
17637        return changed;
17638    }
17639
17640    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17641    private void clearIntentFilterVerificationsLPw(int userId) {
17642        final int packageCount = mPackages.size();
17643        for (int i = 0; i < packageCount; i++) {
17644            PackageParser.Package pkg = mPackages.valueAt(i);
17645            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17646        }
17647    }
17648
17649    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17650    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17651        if (userId == UserHandle.USER_ALL) {
17652            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17653                    sUserManager.getUserIds())) {
17654                for (int oneUserId : sUserManager.getUserIds()) {
17655                    scheduleWritePackageRestrictionsLocked(oneUserId);
17656                }
17657            }
17658        } else {
17659            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17660                scheduleWritePackageRestrictionsLocked(userId);
17661            }
17662        }
17663    }
17664
17665    void clearDefaultBrowserIfNeeded(String packageName) {
17666        for (int oneUserId : sUserManager.getUserIds()) {
17667            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17668            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17669            if (packageName.equals(defaultBrowserPackageName)) {
17670                setDefaultBrowserPackageName(null, oneUserId);
17671            }
17672        }
17673    }
17674
17675    @Override
17676    public void resetApplicationPreferences(int userId) {
17677        mContext.enforceCallingOrSelfPermission(
17678                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17679        final long identity = Binder.clearCallingIdentity();
17680        // writer
17681        try {
17682            synchronized (mPackages) {
17683                clearPackagePreferredActivitiesLPw(null, userId);
17684                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17685                // TODO: We have to reset the default SMS and Phone. This requires
17686                // significant refactoring to keep all default apps in the package
17687                // manager (cleaner but more work) or have the services provide
17688                // callbacks to the package manager to request a default app reset.
17689                applyFactoryDefaultBrowserLPw(userId);
17690                clearIntentFilterVerificationsLPw(userId);
17691                primeDomainVerificationsLPw(userId);
17692                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17693                scheduleWritePackageRestrictionsLocked(userId);
17694            }
17695            resetNetworkPolicies(userId);
17696        } finally {
17697            Binder.restoreCallingIdentity(identity);
17698        }
17699    }
17700
17701    @Override
17702    public int getPreferredActivities(List<IntentFilter> outFilters,
17703            List<ComponentName> outActivities, String packageName) {
17704
17705        int num = 0;
17706        final int userId = UserHandle.getCallingUserId();
17707        // reader
17708        synchronized (mPackages) {
17709            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17710            if (pir != null) {
17711                final Iterator<PreferredActivity> it = pir.filterIterator();
17712                while (it.hasNext()) {
17713                    final PreferredActivity pa = it.next();
17714                    if (packageName == null
17715                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17716                                    && pa.mPref.mAlways)) {
17717                        if (outFilters != null) {
17718                            outFilters.add(new IntentFilter(pa));
17719                        }
17720                        if (outActivities != null) {
17721                            outActivities.add(pa.mPref.mComponent);
17722                        }
17723                    }
17724                }
17725            }
17726        }
17727
17728        return num;
17729    }
17730
17731    @Override
17732    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17733            int userId) {
17734        int callingUid = Binder.getCallingUid();
17735        if (callingUid != Process.SYSTEM_UID) {
17736            throw new SecurityException(
17737                    "addPersistentPreferredActivity can only be run by the system");
17738        }
17739        if (filter.countActions() == 0) {
17740            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17741            return;
17742        }
17743        synchronized (mPackages) {
17744            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17745                    ":");
17746            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17747            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17748                    new PersistentPreferredActivity(filter, activity));
17749            scheduleWritePackageRestrictionsLocked(userId);
17750            postPreferredActivityChangedBroadcast(userId);
17751        }
17752    }
17753
17754    @Override
17755    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17756        int callingUid = Binder.getCallingUid();
17757        if (callingUid != Process.SYSTEM_UID) {
17758            throw new SecurityException(
17759                    "clearPackagePersistentPreferredActivities can only be run by the system");
17760        }
17761        ArrayList<PersistentPreferredActivity> removed = null;
17762        boolean changed = false;
17763        synchronized (mPackages) {
17764            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17765                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17766                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17767                        .valueAt(i);
17768                if (userId != thisUserId) {
17769                    continue;
17770                }
17771                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17772                while (it.hasNext()) {
17773                    PersistentPreferredActivity ppa = it.next();
17774                    // Mark entry for removal only if it matches the package name.
17775                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17776                        if (removed == null) {
17777                            removed = new ArrayList<PersistentPreferredActivity>();
17778                        }
17779                        removed.add(ppa);
17780                    }
17781                }
17782                if (removed != null) {
17783                    for (int j=0; j<removed.size(); j++) {
17784                        PersistentPreferredActivity ppa = removed.get(j);
17785                        ppir.removeFilter(ppa);
17786                    }
17787                    changed = true;
17788                }
17789            }
17790
17791            if (changed) {
17792                scheduleWritePackageRestrictionsLocked(userId);
17793                postPreferredActivityChangedBroadcast(userId);
17794            }
17795        }
17796    }
17797
17798    /**
17799     * Common machinery for picking apart a restored XML blob and passing
17800     * it to a caller-supplied functor to be applied to the running system.
17801     */
17802    private void restoreFromXml(XmlPullParser parser, int userId,
17803            String expectedStartTag, BlobXmlRestorer functor)
17804            throws IOException, XmlPullParserException {
17805        int type;
17806        while ((type = parser.next()) != XmlPullParser.START_TAG
17807                && type != XmlPullParser.END_DOCUMENT) {
17808        }
17809        if (type != XmlPullParser.START_TAG) {
17810            // oops didn't find a start tag?!
17811            if (DEBUG_BACKUP) {
17812                Slog.e(TAG, "Didn't find start tag during restore");
17813            }
17814            return;
17815        }
17816Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17817        // this is supposed to be TAG_PREFERRED_BACKUP
17818        if (!expectedStartTag.equals(parser.getName())) {
17819            if (DEBUG_BACKUP) {
17820                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17821            }
17822            return;
17823        }
17824
17825        // skip interfering stuff, then we're aligned with the backing implementation
17826        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17827Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17828        functor.apply(parser, userId);
17829    }
17830
17831    private interface BlobXmlRestorer {
17832        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17833    }
17834
17835    /**
17836     * Non-Binder method, support for the backup/restore mechanism: write the
17837     * full set of preferred activities in its canonical XML format.  Returns the
17838     * XML output as a byte array, or null if there is none.
17839     */
17840    @Override
17841    public byte[] getPreferredActivityBackup(int userId) {
17842        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17843            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17844        }
17845
17846        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17847        try {
17848            final XmlSerializer serializer = new FastXmlSerializer();
17849            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17850            serializer.startDocument(null, true);
17851            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17852
17853            synchronized (mPackages) {
17854                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17855            }
17856
17857            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17858            serializer.endDocument();
17859            serializer.flush();
17860        } catch (Exception e) {
17861            if (DEBUG_BACKUP) {
17862                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17863            }
17864            return null;
17865        }
17866
17867        return dataStream.toByteArray();
17868    }
17869
17870    @Override
17871    public void restorePreferredActivities(byte[] backup, int userId) {
17872        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17873            throw new SecurityException("Only the system may call restorePreferredActivities()");
17874        }
17875
17876        try {
17877            final XmlPullParser parser = Xml.newPullParser();
17878            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17879            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17880                    new BlobXmlRestorer() {
17881                        @Override
17882                        public void apply(XmlPullParser parser, int userId)
17883                                throws XmlPullParserException, IOException {
17884                            synchronized (mPackages) {
17885                                mSettings.readPreferredActivitiesLPw(parser, userId);
17886                            }
17887                        }
17888                    } );
17889        } catch (Exception e) {
17890            if (DEBUG_BACKUP) {
17891                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17892            }
17893        }
17894    }
17895
17896    /**
17897     * Non-Binder method, support for the backup/restore mechanism: write the
17898     * default browser (etc) settings in its canonical XML format.  Returns the default
17899     * browser XML representation as a byte array, or null if there is none.
17900     */
17901    @Override
17902    public byte[] getDefaultAppsBackup(int userId) {
17903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17904            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17905        }
17906
17907        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17908        try {
17909            final XmlSerializer serializer = new FastXmlSerializer();
17910            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17911            serializer.startDocument(null, true);
17912            serializer.startTag(null, TAG_DEFAULT_APPS);
17913
17914            synchronized (mPackages) {
17915                mSettings.writeDefaultAppsLPr(serializer, userId);
17916            }
17917
17918            serializer.endTag(null, TAG_DEFAULT_APPS);
17919            serializer.endDocument();
17920            serializer.flush();
17921        } catch (Exception e) {
17922            if (DEBUG_BACKUP) {
17923                Slog.e(TAG, "Unable to write default apps for backup", e);
17924            }
17925            return null;
17926        }
17927
17928        return dataStream.toByteArray();
17929    }
17930
17931    @Override
17932    public void restoreDefaultApps(byte[] backup, int userId) {
17933        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17934            throw new SecurityException("Only the system may call restoreDefaultApps()");
17935        }
17936
17937        try {
17938            final XmlPullParser parser = Xml.newPullParser();
17939            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17940            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17941                    new BlobXmlRestorer() {
17942                        @Override
17943                        public void apply(XmlPullParser parser, int userId)
17944                                throws XmlPullParserException, IOException {
17945                            synchronized (mPackages) {
17946                                mSettings.readDefaultAppsLPw(parser, userId);
17947                            }
17948                        }
17949                    } );
17950        } catch (Exception e) {
17951            if (DEBUG_BACKUP) {
17952                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17953            }
17954        }
17955    }
17956
17957    @Override
17958    public byte[] getIntentFilterVerificationBackup(int userId) {
17959        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17960            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17961        }
17962
17963        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17964        try {
17965            final XmlSerializer serializer = new FastXmlSerializer();
17966            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17967            serializer.startDocument(null, true);
17968            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17969
17970            synchronized (mPackages) {
17971                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17972            }
17973
17974            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17975            serializer.endDocument();
17976            serializer.flush();
17977        } catch (Exception e) {
17978            if (DEBUG_BACKUP) {
17979                Slog.e(TAG, "Unable to write default apps for backup", e);
17980            }
17981            return null;
17982        }
17983
17984        return dataStream.toByteArray();
17985    }
17986
17987    @Override
17988    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17989        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17990            throw new SecurityException("Only the system may call restorePreferredActivities()");
17991        }
17992
17993        try {
17994            final XmlPullParser parser = Xml.newPullParser();
17995            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17996            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17997                    new BlobXmlRestorer() {
17998                        @Override
17999                        public void apply(XmlPullParser parser, int userId)
18000                                throws XmlPullParserException, IOException {
18001                            synchronized (mPackages) {
18002                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18003                                mSettings.writeLPr();
18004                            }
18005                        }
18006                    } );
18007        } catch (Exception e) {
18008            if (DEBUG_BACKUP) {
18009                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18010            }
18011        }
18012    }
18013
18014    @Override
18015    public byte[] getPermissionGrantBackup(int userId) {
18016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18017            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18018        }
18019
18020        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18021        try {
18022            final XmlSerializer serializer = new FastXmlSerializer();
18023            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18024            serializer.startDocument(null, true);
18025            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18026
18027            synchronized (mPackages) {
18028                serializeRuntimePermissionGrantsLPr(serializer, userId);
18029            }
18030
18031            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18032            serializer.endDocument();
18033            serializer.flush();
18034        } catch (Exception e) {
18035            if (DEBUG_BACKUP) {
18036                Slog.e(TAG, "Unable to write default apps for backup", e);
18037            }
18038            return null;
18039        }
18040
18041        return dataStream.toByteArray();
18042    }
18043
18044    @Override
18045    public void restorePermissionGrants(byte[] backup, int userId) {
18046        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18047            throw new SecurityException("Only the system may call restorePermissionGrants()");
18048        }
18049
18050        try {
18051            final XmlPullParser parser = Xml.newPullParser();
18052            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18053            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18054                    new BlobXmlRestorer() {
18055                        @Override
18056                        public void apply(XmlPullParser parser, int userId)
18057                                throws XmlPullParserException, IOException {
18058                            synchronized (mPackages) {
18059                                processRestoredPermissionGrantsLPr(parser, userId);
18060                            }
18061                        }
18062                    } );
18063        } catch (Exception e) {
18064            if (DEBUG_BACKUP) {
18065                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18066            }
18067        }
18068    }
18069
18070    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18071            throws IOException {
18072        serializer.startTag(null, TAG_ALL_GRANTS);
18073
18074        final int N = mSettings.mPackages.size();
18075        for (int i = 0; i < N; i++) {
18076            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18077            boolean pkgGrantsKnown = false;
18078
18079            PermissionsState packagePerms = ps.getPermissionsState();
18080
18081            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18082                final int grantFlags = state.getFlags();
18083                // only look at grants that are not system/policy fixed
18084                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18085                    final boolean isGranted = state.isGranted();
18086                    // And only back up the user-twiddled state bits
18087                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18088                        final String packageName = mSettings.mPackages.keyAt(i);
18089                        if (!pkgGrantsKnown) {
18090                            serializer.startTag(null, TAG_GRANT);
18091                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18092                            pkgGrantsKnown = true;
18093                        }
18094
18095                        final boolean userSet =
18096                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18097                        final boolean userFixed =
18098                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18099                        final boolean revoke =
18100                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18101
18102                        serializer.startTag(null, TAG_PERMISSION);
18103                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18104                        if (isGranted) {
18105                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18106                        }
18107                        if (userSet) {
18108                            serializer.attribute(null, ATTR_USER_SET, "true");
18109                        }
18110                        if (userFixed) {
18111                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18112                        }
18113                        if (revoke) {
18114                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18115                        }
18116                        serializer.endTag(null, TAG_PERMISSION);
18117                    }
18118                }
18119            }
18120
18121            if (pkgGrantsKnown) {
18122                serializer.endTag(null, TAG_GRANT);
18123            }
18124        }
18125
18126        serializer.endTag(null, TAG_ALL_GRANTS);
18127    }
18128
18129    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18130            throws XmlPullParserException, IOException {
18131        String pkgName = null;
18132        int outerDepth = parser.getDepth();
18133        int type;
18134        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18135                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18136            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18137                continue;
18138            }
18139
18140            final String tagName = parser.getName();
18141            if (tagName.equals(TAG_GRANT)) {
18142                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18143                if (DEBUG_BACKUP) {
18144                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18145                }
18146            } else if (tagName.equals(TAG_PERMISSION)) {
18147
18148                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18149                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18150
18151                int newFlagSet = 0;
18152                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18153                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18154                }
18155                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18156                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18157                }
18158                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18159                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18160                }
18161                if (DEBUG_BACKUP) {
18162                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18163                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18164                }
18165                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18166                if (ps != null) {
18167                    // Already installed so we apply the grant immediately
18168                    if (DEBUG_BACKUP) {
18169                        Slog.v(TAG, "        + already installed; applying");
18170                    }
18171                    PermissionsState perms = ps.getPermissionsState();
18172                    BasePermission bp = mSettings.mPermissions.get(permName);
18173                    if (bp != null) {
18174                        if (isGranted) {
18175                            perms.grantRuntimePermission(bp, userId);
18176                        }
18177                        if (newFlagSet != 0) {
18178                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18179                        }
18180                    }
18181                } else {
18182                    // Need to wait for post-restore install to apply the grant
18183                    if (DEBUG_BACKUP) {
18184                        Slog.v(TAG, "        - not yet installed; saving for later");
18185                    }
18186                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18187                            isGranted, newFlagSet, userId);
18188                }
18189            } else {
18190                PackageManagerService.reportSettingsProblem(Log.WARN,
18191                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18192                XmlUtils.skipCurrentTag(parser);
18193            }
18194        }
18195
18196        scheduleWriteSettingsLocked();
18197        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18198    }
18199
18200    @Override
18201    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18202            int sourceUserId, int targetUserId, int flags) {
18203        mContext.enforceCallingOrSelfPermission(
18204                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18205        int callingUid = Binder.getCallingUid();
18206        enforceOwnerRights(ownerPackage, callingUid);
18207        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18208        if (intentFilter.countActions() == 0) {
18209            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18210            return;
18211        }
18212        synchronized (mPackages) {
18213            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18214                    ownerPackage, targetUserId, flags);
18215            CrossProfileIntentResolver resolver =
18216                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18217            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18218            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18219            if (existing != null) {
18220                int size = existing.size();
18221                for (int i = 0; i < size; i++) {
18222                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18223                        return;
18224                    }
18225                }
18226            }
18227            resolver.addFilter(newFilter);
18228            scheduleWritePackageRestrictionsLocked(sourceUserId);
18229        }
18230    }
18231
18232    @Override
18233    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18234        mContext.enforceCallingOrSelfPermission(
18235                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18236        int callingUid = Binder.getCallingUid();
18237        enforceOwnerRights(ownerPackage, callingUid);
18238        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18239        synchronized (mPackages) {
18240            CrossProfileIntentResolver resolver =
18241                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18242            ArraySet<CrossProfileIntentFilter> set =
18243                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18244            for (CrossProfileIntentFilter filter : set) {
18245                if (filter.getOwnerPackage().equals(ownerPackage)) {
18246                    resolver.removeFilter(filter);
18247                }
18248            }
18249            scheduleWritePackageRestrictionsLocked(sourceUserId);
18250        }
18251    }
18252
18253    // Enforcing that callingUid is owning pkg on userId
18254    private void enforceOwnerRights(String pkg, int callingUid) {
18255        // The system owns everything.
18256        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18257            return;
18258        }
18259        int callingUserId = UserHandle.getUserId(callingUid);
18260        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18261        if (pi == null) {
18262            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18263                    + callingUserId);
18264        }
18265        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18266            throw new SecurityException("Calling uid " + callingUid
18267                    + " does not own package " + pkg);
18268        }
18269    }
18270
18271    @Override
18272    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18273        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18274    }
18275
18276    private Intent getHomeIntent() {
18277        Intent intent = new Intent(Intent.ACTION_MAIN);
18278        intent.addCategory(Intent.CATEGORY_HOME);
18279        intent.addCategory(Intent.CATEGORY_DEFAULT);
18280        return intent;
18281    }
18282
18283    private IntentFilter getHomeFilter() {
18284        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18285        filter.addCategory(Intent.CATEGORY_HOME);
18286        filter.addCategory(Intent.CATEGORY_DEFAULT);
18287        return filter;
18288    }
18289
18290    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18291            int userId) {
18292        Intent intent  = getHomeIntent();
18293        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18294                PackageManager.GET_META_DATA, userId);
18295        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18296                true, false, false, userId);
18297
18298        allHomeCandidates.clear();
18299        if (list != null) {
18300            for (ResolveInfo ri : list) {
18301                allHomeCandidates.add(ri);
18302            }
18303        }
18304        return (preferred == null || preferred.activityInfo == null)
18305                ? null
18306                : new ComponentName(preferred.activityInfo.packageName,
18307                        preferred.activityInfo.name);
18308    }
18309
18310    @Override
18311    public void setHomeActivity(ComponentName comp, int userId) {
18312        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18313        getHomeActivitiesAsUser(homeActivities, userId);
18314
18315        boolean found = false;
18316
18317        final int size = homeActivities.size();
18318        final ComponentName[] set = new ComponentName[size];
18319        for (int i = 0; i < size; i++) {
18320            final ResolveInfo candidate = homeActivities.get(i);
18321            final ActivityInfo info = candidate.activityInfo;
18322            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18323            set[i] = activityName;
18324            if (!found && activityName.equals(comp)) {
18325                found = true;
18326            }
18327        }
18328        if (!found) {
18329            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18330                    + userId);
18331        }
18332        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18333                set, comp, userId);
18334    }
18335
18336    private @Nullable String getSetupWizardPackageName() {
18337        final Intent intent = new Intent(Intent.ACTION_MAIN);
18338        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18339
18340        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18341                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18342                        | MATCH_DISABLED_COMPONENTS,
18343                UserHandle.myUserId());
18344        if (matches.size() == 1) {
18345            return matches.get(0).getComponentInfo().packageName;
18346        } else {
18347            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18348                    + ": matches=" + matches);
18349            return null;
18350        }
18351    }
18352
18353    private @Nullable String getStorageManagerPackageName() {
18354        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18355
18356        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18357                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18358                        | MATCH_DISABLED_COMPONENTS,
18359                UserHandle.myUserId());
18360        if (matches.size() == 1) {
18361            return matches.get(0).getComponentInfo().packageName;
18362        } else {
18363            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18364                    + matches.size() + ": matches=" + matches);
18365            return null;
18366        }
18367    }
18368
18369    @Override
18370    public void setApplicationEnabledSetting(String appPackageName,
18371            int newState, int flags, int userId, String callingPackage) {
18372        if (!sUserManager.exists(userId)) return;
18373        if (callingPackage == null) {
18374            callingPackage = Integer.toString(Binder.getCallingUid());
18375        }
18376        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18377    }
18378
18379    @Override
18380    public void setComponentEnabledSetting(ComponentName componentName,
18381            int newState, int flags, int userId) {
18382        if (!sUserManager.exists(userId)) return;
18383        setEnabledSetting(componentName.getPackageName(),
18384                componentName.getClassName(), newState, flags, userId, null);
18385    }
18386
18387    private void setEnabledSetting(final String packageName, String className, int newState,
18388            final int flags, int userId, String callingPackage) {
18389        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18390              || newState == COMPONENT_ENABLED_STATE_ENABLED
18391              || newState == COMPONENT_ENABLED_STATE_DISABLED
18392              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18393              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18394            throw new IllegalArgumentException("Invalid new component state: "
18395                    + newState);
18396        }
18397        PackageSetting pkgSetting;
18398        final int uid = Binder.getCallingUid();
18399        final int permission;
18400        if (uid == Process.SYSTEM_UID) {
18401            permission = PackageManager.PERMISSION_GRANTED;
18402        } else {
18403            permission = mContext.checkCallingOrSelfPermission(
18404                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18405        }
18406        enforceCrossUserPermission(uid, userId,
18407                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18408        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18409        boolean sendNow = false;
18410        boolean isApp = (className == null);
18411        String componentName = isApp ? packageName : className;
18412        int packageUid = -1;
18413        ArrayList<String> components;
18414
18415        // writer
18416        synchronized (mPackages) {
18417            pkgSetting = mSettings.mPackages.get(packageName);
18418            if (pkgSetting == null) {
18419                if (className == null) {
18420                    throw new IllegalArgumentException("Unknown package: " + packageName);
18421                }
18422                throw new IllegalArgumentException(
18423                        "Unknown component: " + packageName + "/" + className);
18424            }
18425        }
18426
18427        // Limit who can change which apps
18428        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18429            // Don't allow apps that don't have permission to modify other apps
18430            if (!allowedByPermission) {
18431                throw new SecurityException(
18432                        "Permission Denial: attempt to change component state from pid="
18433                        + Binder.getCallingPid()
18434                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18435            }
18436            // Don't allow changing protected packages.
18437            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18438                throw new SecurityException("Cannot disable a protected package: " + packageName);
18439            }
18440        }
18441
18442        synchronized (mPackages) {
18443            if (uid == Process.SHELL_UID
18444                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18445                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18446                // unless it is a test package.
18447                int oldState = pkgSetting.getEnabled(userId);
18448                if (className == null
18449                    &&
18450                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18451                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18452                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18453                    &&
18454                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18455                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18456                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18457                    // ok
18458                } else {
18459                    throw new SecurityException(
18460                            "Shell cannot change component state for " + packageName + "/"
18461                            + className + " to " + newState);
18462                }
18463            }
18464            if (className == null) {
18465                // We're dealing with an application/package level state change
18466                if (pkgSetting.getEnabled(userId) == newState) {
18467                    // Nothing to do
18468                    return;
18469                }
18470                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18471                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18472                    // Don't care about who enables an app.
18473                    callingPackage = null;
18474                }
18475                pkgSetting.setEnabled(newState, userId, callingPackage);
18476                // pkgSetting.pkg.mSetEnabled = newState;
18477            } else {
18478                // We're dealing with a component level state change
18479                // First, verify that this is a valid class name.
18480                PackageParser.Package pkg = pkgSetting.pkg;
18481                if (pkg == null || !pkg.hasComponentClassName(className)) {
18482                    if (pkg != null &&
18483                            pkg.applicationInfo.targetSdkVersion >=
18484                                    Build.VERSION_CODES.JELLY_BEAN) {
18485                        throw new IllegalArgumentException("Component class " + className
18486                                + " does not exist in " + packageName);
18487                    } else {
18488                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18489                                + className + " does not exist in " + packageName);
18490                    }
18491                }
18492                switch (newState) {
18493                case COMPONENT_ENABLED_STATE_ENABLED:
18494                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18495                        return;
18496                    }
18497                    break;
18498                case COMPONENT_ENABLED_STATE_DISABLED:
18499                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18500                        return;
18501                    }
18502                    break;
18503                case COMPONENT_ENABLED_STATE_DEFAULT:
18504                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18505                        return;
18506                    }
18507                    break;
18508                default:
18509                    Slog.e(TAG, "Invalid new component state: " + newState);
18510                    return;
18511                }
18512            }
18513            scheduleWritePackageRestrictionsLocked(userId);
18514            components = mPendingBroadcasts.get(userId, packageName);
18515            final boolean newPackage = components == null;
18516            if (newPackage) {
18517                components = new ArrayList<String>();
18518            }
18519            if (!components.contains(componentName)) {
18520                components.add(componentName);
18521            }
18522            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18523                sendNow = true;
18524                // Purge entry from pending broadcast list if another one exists already
18525                // since we are sending one right away.
18526                mPendingBroadcasts.remove(userId, packageName);
18527            } else {
18528                if (newPackage) {
18529                    mPendingBroadcasts.put(userId, packageName, components);
18530                }
18531                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18532                    // Schedule a message
18533                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18534                }
18535            }
18536        }
18537
18538        long callingId = Binder.clearCallingIdentity();
18539        try {
18540            if (sendNow) {
18541                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18542                sendPackageChangedBroadcast(packageName,
18543                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18544            }
18545        } finally {
18546            Binder.restoreCallingIdentity(callingId);
18547        }
18548    }
18549
18550    @Override
18551    public void flushPackageRestrictionsAsUser(int userId) {
18552        if (!sUserManager.exists(userId)) {
18553            return;
18554        }
18555        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18556                false /* checkShell */, "flushPackageRestrictions");
18557        synchronized (mPackages) {
18558            mSettings.writePackageRestrictionsLPr(userId);
18559            mDirtyUsers.remove(userId);
18560            if (mDirtyUsers.isEmpty()) {
18561                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18562            }
18563        }
18564    }
18565
18566    private void sendPackageChangedBroadcast(String packageName,
18567            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18568        if (DEBUG_INSTALL)
18569            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18570                    + componentNames);
18571        Bundle extras = new Bundle(4);
18572        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18573        String nameList[] = new String[componentNames.size()];
18574        componentNames.toArray(nameList);
18575        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18576        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18577        extras.putInt(Intent.EXTRA_UID, packageUid);
18578        // If this is not reporting a change of the overall package, then only send it
18579        // to registered receivers.  We don't want to launch a swath of apps for every
18580        // little component state change.
18581        final int flags = !componentNames.contains(packageName)
18582                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18583        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18584                new int[] {UserHandle.getUserId(packageUid)});
18585    }
18586
18587    @Override
18588    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18589        if (!sUserManager.exists(userId)) return;
18590        final int uid = Binder.getCallingUid();
18591        final int permission = mContext.checkCallingOrSelfPermission(
18592                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18593        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18594        enforceCrossUserPermission(uid, userId,
18595                true /* requireFullPermission */, true /* checkShell */, "stop package");
18596        // writer
18597        synchronized (mPackages) {
18598            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18599                    allowedByPermission, uid, userId)) {
18600                scheduleWritePackageRestrictionsLocked(userId);
18601            }
18602        }
18603    }
18604
18605    @Override
18606    public String getInstallerPackageName(String packageName) {
18607        // reader
18608        synchronized (mPackages) {
18609            return mSettings.getInstallerPackageNameLPr(packageName);
18610        }
18611    }
18612
18613    public boolean isOrphaned(String packageName) {
18614        // reader
18615        synchronized (mPackages) {
18616            return mSettings.isOrphaned(packageName);
18617        }
18618    }
18619
18620    @Override
18621    public int getApplicationEnabledSetting(String packageName, int userId) {
18622        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18623        int uid = Binder.getCallingUid();
18624        enforceCrossUserPermission(uid, userId,
18625                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18626        // reader
18627        synchronized (mPackages) {
18628            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18629        }
18630    }
18631
18632    @Override
18633    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18634        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18635        int uid = Binder.getCallingUid();
18636        enforceCrossUserPermission(uid, userId,
18637                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18638        // reader
18639        synchronized (mPackages) {
18640            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18641        }
18642    }
18643
18644    @Override
18645    public void enterSafeMode() {
18646        enforceSystemOrRoot("Only the system can request entering safe mode");
18647
18648        if (!mSystemReady) {
18649            mSafeMode = true;
18650        }
18651    }
18652
18653    @Override
18654    public void systemReady() {
18655        mSystemReady = true;
18656
18657        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18658        // disabled after already being started.
18659        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18660                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18661
18662        // Read the compatibilty setting when the system is ready.
18663        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18664                mContext.getContentResolver(),
18665                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18666        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18667        if (DEBUG_SETTINGS) {
18668            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18669        }
18670
18671        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18672
18673        synchronized (mPackages) {
18674            // Verify that all of the preferred activity components actually
18675            // exist.  It is possible for applications to be updated and at
18676            // that point remove a previously declared activity component that
18677            // had been set as a preferred activity.  We try to clean this up
18678            // the next time we encounter that preferred activity, but it is
18679            // possible for the user flow to never be able to return to that
18680            // situation so here we do a sanity check to make sure we haven't
18681            // left any junk around.
18682            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18683            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18684                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18685                removed.clear();
18686                for (PreferredActivity pa : pir.filterSet()) {
18687                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18688                        removed.add(pa);
18689                    }
18690                }
18691                if (removed.size() > 0) {
18692                    for (int r=0; r<removed.size(); r++) {
18693                        PreferredActivity pa = removed.get(r);
18694                        Slog.w(TAG, "Removing dangling preferred activity: "
18695                                + pa.mPref.mComponent);
18696                        pir.removeFilter(pa);
18697                    }
18698                    mSettings.writePackageRestrictionsLPr(
18699                            mSettings.mPreferredActivities.keyAt(i));
18700                }
18701            }
18702
18703            for (int userId : UserManagerService.getInstance().getUserIds()) {
18704                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18705                    grantPermissionsUserIds = ArrayUtils.appendInt(
18706                            grantPermissionsUserIds, userId);
18707                }
18708            }
18709        }
18710        sUserManager.systemReady();
18711
18712        // If we upgraded grant all default permissions before kicking off.
18713        for (int userId : grantPermissionsUserIds) {
18714            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18715        }
18716
18717        // If we did not grant default permissions, we preload from this the
18718        // default permission exceptions lazily to ensure we don't hit the
18719        // disk on a new user creation.
18720        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18721            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18722        }
18723
18724        // Kick off any messages waiting for system ready
18725        if (mPostSystemReadyMessages != null) {
18726            for (Message msg : mPostSystemReadyMessages) {
18727                msg.sendToTarget();
18728            }
18729            mPostSystemReadyMessages = null;
18730        }
18731
18732        // Watch for external volumes that come and go over time
18733        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18734        storage.registerListener(mStorageListener);
18735
18736        mInstallerService.systemReady();
18737        mPackageDexOptimizer.systemReady();
18738
18739        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18740                StorageManagerInternal.class);
18741        StorageManagerInternal.addExternalStoragePolicy(
18742                new StorageManagerInternal.ExternalStorageMountPolicy() {
18743            @Override
18744            public int getMountMode(int uid, String packageName) {
18745                if (Process.isIsolated(uid)) {
18746                    return Zygote.MOUNT_EXTERNAL_NONE;
18747                }
18748                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18749                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18750                }
18751                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18752                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18753                }
18754                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18755                    return Zygote.MOUNT_EXTERNAL_READ;
18756                }
18757                return Zygote.MOUNT_EXTERNAL_WRITE;
18758            }
18759
18760            @Override
18761            public boolean hasExternalStorage(int uid, String packageName) {
18762                return true;
18763            }
18764        });
18765
18766        // Now that we're mostly running, clean up stale users and apps
18767        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18768        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18769    }
18770
18771    @Override
18772    public boolean isSafeMode() {
18773        return mSafeMode;
18774    }
18775
18776    @Override
18777    public boolean hasSystemUidErrors() {
18778        return mHasSystemUidErrors;
18779    }
18780
18781    static String arrayToString(int[] array) {
18782        StringBuffer buf = new StringBuffer(128);
18783        buf.append('[');
18784        if (array != null) {
18785            for (int i=0; i<array.length; i++) {
18786                if (i > 0) buf.append(", ");
18787                buf.append(array[i]);
18788            }
18789        }
18790        buf.append(']');
18791        return buf.toString();
18792    }
18793
18794    static class DumpState {
18795        public static final int DUMP_LIBS = 1 << 0;
18796        public static final int DUMP_FEATURES = 1 << 1;
18797        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18798        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18799        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18800        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18801        public static final int DUMP_PERMISSIONS = 1 << 6;
18802        public static final int DUMP_PACKAGES = 1 << 7;
18803        public static final int DUMP_SHARED_USERS = 1 << 8;
18804        public static final int DUMP_MESSAGES = 1 << 9;
18805        public static final int DUMP_PROVIDERS = 1 << 10;
18806        public static final int DUMP_VERIFIERS = 1 << 11;
18807        public static final int DUMP_PREFERRED = 1 << 12;
18808        public static final int DUMP_PREFERRED_XML = 1 << 13;
18809        public static final int DUMP_KEYSETS = 1 << 14;
18810        public static final int DUMP_VERSION = 1 << 15;
18811        public static final int DUMP_INSTALLS = 1 << 16;
18812        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18813        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18814        public static final int DUMP_FROZEN = 1 << 19;
18815        public static final int DUMP_DEXOPT = 1 << 20;
18816        public static final int DUMP_COMPILER_STATS = 1 << 21;
18817
18818        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18819
18820        private int mTypes;
18821
18822        private int mOptions;
18823
18824        private boolean mTitlePrinted;
18825
18826        private SharedUserSetting mSharedUser;
18827
18828        public boolean isDumping(int type) {
18829            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18830                return true;
18831            }
18832
18833            return (mTypes & type) != 0;
18834        }
18835
18836        public void setDump(int type) {
18837            mTypes |= type;
18838        }
18839
18840        public boolean isOptionEnabled(int option) {
18841            return (mOptions & option) != 0;
18842        }
18843
18844        public void setOptionEnabled(int option) {
18845            mOptions |= option;
18846        }
18847
18848        public boolean onTitlePrinted() {
18849            final boolean printed = mTitlePrinted;
18850            mTitlePrinted = true;
18851            return printed;
18852        }
18853
18854        public boolean getTitlePrinted() {
18855            return mTitlePrinted;
18856        }
18857
18858        public void setTitlePrinted(boolean enabled) {
18859            mTitlePrinted = enabled;
18860        }
18861
18862        public SharedUserSetting getSharedUser() {
18863            return mSharedUser;
18864        }
18865
18866        public void setSharedUser(SharedUserSetting user) {
18867            mSharedUser = user;
18868        }
18869    }
18870
18871    @Override
18872    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18873            FileDescriptor err, String[] args, ShellCallback callback,
18874            ResultReceiver resultReceiver) {
18875        (new PackageManagerShellCommand(this)).exec(
18876                this, in, out, err, args, callback, resultReceiver);
18877    }
18878
18879    @Override
18880    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18881        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18882                != PackageManager.PERMISSION_GRANTED) {
18883            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18884                    + Binder.getCallingPid()
18885                    + ", uid=" + Binder.getCallingUid()
18886                    + " without permission "
18887                    + android.Manifest.permission.DUMP);
18888            return;
18889        }
18890
18891        DumpState dumpState = new DumpState();
18892        boolean fullPreferred = false;
18893        boolean checkin = false;
18894
18895        String packageName = null;
18896        ArraySet<String> permissionNames = null;
18897
18898        int opti = 0;
18899        while (opti < args.length) {
18900            String opt = args[opti];
18901            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18902                break;
18903            }
18904            opti++;
18905
18906            if ("-a".equals(opt)) {
18907                // Right now we only know how to print all.
18908            } else if ("-h".equals(opt)) {
18909                pw.println("Package manager dump options:");
18910                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18911                pw.println("    --checkin: dump for a checkin");
18912                pw.println("    -f: print details of intent filters");
18913                pw.println("    -h: print this help");
18914                pw.println("  cmd may be one of:");
18915                pw.println("    l[ibraries]: list known shared libraries");
18916                pw.println("    f[eatures]: list device features");
18917                pw.println("    k[eysets]: print known keysets");
18918                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18919                pw.println("    perm[issions]: dump permissions");
18920                pw.println("    permission [name ...]: dump declaration and use of given permission");
18921                pw.println("    pref[erred]: print preferred package settings");
18922                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18923                pw.println("    prov[iders]: dump content providers");
18924                pw.println("    p[ackages]: dump installed packages");
18925                pw.println("    s[hared-users]: dump shared user IDs");
18926                pw.println("    m[essages]: print collected runtime messages");
18927                pw.println("    v[erifiers]: print package verifier info");
18928                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18929                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18930                pw.println("    version: print database version info");
18931                pw.println("    write: write current settings now");
18932                pw.println("    installs: details about install sessions");
18933                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18934                pw.println("    dexopt: dump dexopt state");
18935                pw.println("    compiler-stats: dump compiler statistics");
18936                pw.println("    <package.name>: info about given package");
18937                return;
18938            } else if ("--checkin".equals(opt)) {
18939                checkin = true;
18940            } else if ("-f".equals(opt)) {
18941                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18942            } else {
18943                pw.println("Unknown argument: " + opt + "; use -h for help");
18944            }
18945        }
18946
18947        // Is the caller requesting to dump a particular piece of data?
18948        if (opti < args.length) {
18949            String cmd = args[opti];
18950            opti++;
18951            // Is this a package name?
18952            if ("android".equals(cmd) || cmd.contains(".")) {
18953                packageName = cmd;
18954                // When dumping a single package, we always dump all of its
18955                // filter information since the amount of data will be reasonable.
18956                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18957            } else if ("check-permission".equals(cmd)) {
18958                if (opti >= args.length) {
18959                    pw.println("Error: check-permission missing permission argument");
18960                    return;
18961                }
18962                String perm = args[opti];
18963                opti++;
18964                if (opti >= args.length) {
18965                    pw.println("Error: check-permission missing package argument");
18966                    return;
18967                }
18968                String pkg = args[opti];
18969                opti++;
18970                int user = UserHandle.getUserId(Binder.getCallingUid());
18971                if (opti < args.length) {
18972                    try {
18973                        user = Integer.parseInt(args[opti]);
18974                    } catch (NumberFormatException e) {
18975                        pw.println("Error: check-permission user argument is not a number: "
18976                                + args[opti]);
18977                        return;
18978                    }
18979                }
18980                pw.println(checkPermission(perm, pkg, user));
18981                return;
18982            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18983                dumpState.setDump(DumpState.DUMP_LIBS);
18984            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18985                dumpState.setDump(DumpState.DUMP_FEATURES);
18986            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18987                if (opti >= args.length) {
18988                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18989                            | DumpState.DUMP_SERVICE_RESOLVERS
18990                            | DumpState.DUMP_RECEIVER_RESOLVERS
18991                            | DumpState.DUMP_CONTENT_RESOLVERS);
18992                } else {
18993                    while (opti < args.length) {
18994                        String name = args[opti];
18995                        if ("a".equals(name) || "activity".equals(name)) {
18996                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18997                        } else if ("s".equals(name) || "service".equals(name)) {
18998                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18999                        } else if ("r".equals(name) || "receiver".equals(name)) {
19000                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19001                        } else if ("c".equals(name) || "content".equals(name)) {
19002                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19003                        } else {
19004                            pw.println("Error: unknown resolver table type: " + name);
19005                            return;
19006                        }
19007                        opti++;
19008                    }
19009                }
19010            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19011                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19012            } else if ("permission".equals(cmd)) {
19013                if (opti >= args.length) {
19014                    pw.println("Error: permission requires permission name");
19015                    return;
19016                }
19017                permissionNames = new ArraySet<>();
19018                while (opti < args.length) {
19019                    permissionNames.add(args[opti]);
19020                    opti++;
19021                }
19022                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19023                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19024            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19025                dumpState.setDump(DumpState.DUMP_PREFERRED);
19026            } else if ("preferred-xml".equals(cmd)) {
19027                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19028                if (opti < args.length && "--full".equals(args[opti])) {
19029                    fullPreferred = true;
19030                    opti++;
19031                }
19032            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19033                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19034            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19035                dumpState.setDump(DumpState.DUMP_PACKAGES);
19036            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19037                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19038            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19039                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19040            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19041                dumpState.setDump(DumpState.DUMP_MESSAGES);
19042            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19043                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19044            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19045                    || "intent-filter-verifiers".equals(cmd)) {
19046                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19047            } else if ("version".equals(cmd)) {
19048                dumpState.setDump(DumpState.DUMP_VERSION);
19049            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19050                dumpState.setDump(DumpState.DUMP_KEYSETS);
19051            } else if ("installs".equals(cmd)) {
19052                dumpState.setDump(DumpState.DUMP_INSTALLS);
19053            } else if ("frozen".equals(cmd)) {
19054                dumpState.setDump(DumpState.DUMP_FROZEN);
19055            } else if ("dexopt".equals(cmd)) {
19056                dumpState.setDump(DumpState.DUMP_DEXOPT);
19057            } else if ("compiler-stats".equals(cmd)) {
19058                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19059            } else if ("write".equals(cmd)) {
19060                synchronized (mPackages) {
19061                    mSettings.writeLPr();
19062                    pw.println("Settings written.");
19063                    return;
19064                }
19065            }
19066        }
19067
19068        if (checkin) {
19069            pw.println("vers,1");
19070        }
19071
19072        // reader
19073        synchronized (mPackages) {
19074            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19075                if (!checkin) {
19076                    if (dumpState.onTitlePrinted())
19077                        pw.println();
19078                    pw.println("Database versions:");
19079                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19080                }
19081            }
19082
19083            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19084                if (!checkin) {
19085                    if (dumpState.onTitlePrinted())
19086                        pw.println();
19087                    pw.println("Verifiers:");
19088                    pw.print("  Required: ");
19089                    pw.print(mRequiredVerifierPackage);
19090                    pw.print(" (uid=");
19091                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19092                            UserHandle.USER_SYSTEM));
19093                    pw.println(")");
19094                } else if (mRequiredVerifierPackage != null) {
19095                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19096                    pw.print(",");
19097                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19098                            UserHandle.USER_SYSTEM));
19099                }
19100            }
19101
19102            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19103                    packageName == null) {
19104                if (mIntentFilterVerifierComponent != null) {
19105                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19106                    if (!checkin) {
19107                        if (dumpState.onTitlePrinted())
19108                            pw.println();
19109                        pw.println("Intent Filter Verifier:");
19110                        pw.print("  Using: ");
19111                        pw.print(verifierPackageName);
19112                        pw.print(" (uid=");
19113                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19114                                UserHandle.USER_SYSTEM));
19115                        pw.println(")");
19116                    } else if (verifierPackageName != null) {
19117                        pw.print("ifv,"); pw.print(verifierPackageName);
19118                        pw.print(",");
19119                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19120                                UserHandle.USER_SYSTEM));
19121                    }
19122                } else {
19123                    pw.println();
19124                    pw.println("No Intent Filter Verifier available!");
19125                }
19126            }
19127
19128            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19129                boolean printedHeader = false;
19130                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19131                while (it.hasNext()) {
19132                    String name = it.next();
19133                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19134                    if (!checkin) {
19135                        if (!printedHeader) {
19136                            if (dumpState.onTitlePrinted())
19137                                pw.println();
19138                            pw.println("Libraries:");
19139                            printedHeader = true;
19140                        }
19141                        pw.print("  ");
19142                    } else {
19143                        pw.print("lib,");
19144                    }
19145                    pw.print(name);
19146                    if (!checkin) {
19147                        pw.print(" -> ");
19148                    }
19149                    if (ent.path != null) {
19150                        if (!checkin) {
19151                            pw.print("(jar) ");
19152                            pw.print(ent.path);
19153                        } else {
19154                            pw.print(",jar,");
19155                            pw.print(ent.path);
19156                        }
19157                    } else {
19158                        if (!checkin) {
19159                            pw.print("(apk) ");
19160                            pw.print(ent.apk);
19161                        } else {
19162                            pw.print(",apk,");
19163                            pw.print(ent.apk);
19164                        }
19165                    }
19166                    pw.println();
19167                }
19168            }
19169
19170            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19171                if (dumpState.onTitlePrinted())
19172                    pw.println();
19173                if (!checkin) {
19174                    pw.println("Features:");
19175                }
19176
19177                for (FeatureInfo feat : mAvailableFeatures.values()) {
19178                    if (checkin) {
19179                        pw.print("feat,");
19180                        pw.print(feat.name);
19181                        pw.print(",");
19182                        pw.println(feat.version);
19183                    } else {
19184                        pw.print("  ");
19185                        pw.print(feat.name);
19186                        if (feat.version > 0) {
19187                            pw.print(" version=");
19188                            pw.print(feat.version);
19189                        }
19190                        pw.println();
19191                    }
19192                }
19193            }
19194
19195            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19196                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19197                        : "Activity Resolver Table:", "  ", packageName,
19198                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19199                    dumpState.setTitlePrinted(true);
19200                }
19201            }
19202            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19203                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19204                        : "Receiver Resolver Table:", "  ", packageName,
19205                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19206                    dumpState.setTitlePrinted(true);
19207                }
19208            }
19209            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19210                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19211                        : "Service Resolver Table:", "  ", packageName,
19212                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19213                    dumpState.setTitlePrinted(true);
19214                }
19215            }
19216            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19217                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19218                        : "Provider Resolver Table:", "  ", packageName,
19219                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19220                    dumpState.setTitlePrinted(true);
19221                }
19222            }
19223
19224            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19225                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19226                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19227                    int user = mSettings.mPreferredActivities.keyAt(i);
19228                    if (pir.dump(pw,
19229                            dumpState.getTitlePrinted()
19230                                ? "\nPreferred Activities User " + user + ":"
19231                                : "Preferred Activities User " + user + ":", "  ",
19232                            packageName, true, false)) {
19233                        dumpState.setTitlePrinted(true);
19234                    }
19235                }
19236            }
19237
19238            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19239                pw.flush();
19240                FileOutputStream fout = new FileOutputStream(fd);
19241                BufferedOutputStream str = new BufferedOutputStream(fout);
19242                XmlSerializer serializer = new FastXmlSerializer();
19243                try {
19244                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19245                    serializer.startDocument(null, true);
19246                    serializer.setFeature(
19247                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19248                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19249                    serializer.endDocument();
19250                    serializer.flush();
19251                } catch (IllegalArgumentException e) {
19252                    pw.println("Failed writing: " + e);
19253                } catch (IllegalStateException e) {
19254                    pw.println("Failed writing: " + e);
19255                } catch (IOException e) {
19256                    pw.println("Failed writing: " + e);
19257                }
19258            }
19259
19260            if (!checkin
19261                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19262                    && packageName == null) {
19263                pw.println();
19264                int count = mSettings.mPackages.size();
19265                if (count == 0) {
19266                    pw.println("No applications!");
19267                    pw.println();
19268                } else {
19269                    final String prefix = "  ";
19270                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19271                    if (allPackageSettings.size() == 0) {
19272                        pw.println("No domain preferred apps!");
19273                        pw.println();
19274                    } else {
19275                        pw.println("App verification status:");
19276                        pw.println();
19277                        count = 0;
19278                        for (PackageSetting ps : allPackageSettings) {
19279                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19280                            if (ivi == null || ivi.getPackageName() == null) continue;
19281                            pw.println(prefix + "Package: " + ivi.getPackageName());
19282                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19283                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19284                            pw.println();
19285                            count++;
19286                        }
19287                        if (count == 0) {
19288                            pw.println(prefix + "No app verification established.");
19289                            pw.println();
19290                        }
19291                        for (int userId : sUserManager.getUserIds()) {
19292                            pw.println("App linkages for user " + userId + ":");
19293                            pw.println();
19294                            count = 0;
19295                            for (PackageSetting ps : allPackageSettings) {
19296                                final long status = ps.getDomainVerificationStatusForUser(userId);
19297                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19298                                    continue;
19299                                }
19300                                pw.println(prefix + "Package: " + ps.name);
19301                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19302                                String statusStr = IntentFilterVerificationInfo.
19303                                        getStatusStringFromValue(status);
19304                                pw.println(prefix + "Status:  " + statusStr);
19305                                pw.println();
19306                                count++;
19307                            }
19308                            if (count == 0) {
19309                                pw.println(prefix + "No configured app linkages.");
19310                                pw.println();
19311                            }
19312                        }
19313                    }
19314                }
19315            }
19316
19317            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19318                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19319                if (packageName == null && permissionNames == null) {
19320                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19321                        if (iperm == 0) {
19322                            if (dumpState.onTitlePrinted())
19323                                pw.println();
19324                            pw.println("AppOp Permissions:");
19325                        }
19326                        pw.print("  AppOp Permission ");
19327                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19328                        pw.println(":");
19329                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19330                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19331                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19332                        }
19333                    }
19334                }
19335            }
19336
19337            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19338                boolean printedSomething = false;
19339                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19340                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19341                        continue;
19342                    }
19343                    if (!printedSomething) {
19344                        if (dumpState.onTitlePrinted())
19345                            pw.println();
19346                        pw.println("Registered ContentProviders:");
19347                        printedSomething = true;
19348                    }
19349                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19350                    pw.print("    "); pw.println(p.toString());
19351                }
19352                printedSomething = false;
19353                for (Map.Entry<String, PackageParser.Provider> entry :
19354                        mProvidersByAuthority.entrySet()) {
19355                    PackageParser.Provider p = entry.getValue();
19356                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19357                        continue;
19358                    }
19359                    if (!printedSomething) {
19360                        if (dumpState.onTitlePrinted())
19361                            pw.println();
19362                        pw.println("ContentProvider Authorities:");
19363                        printedSomething = true;
19364                    }
19365                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19366                    pw.print("    "); pw.println(p.toString());
19367                    if (p.info != null && p.info.applicationInfo != null) {
19368                        final String appInfo = p.info.applicationInfo.toString();
19369                        pw.print("      applicationInfo="); pw.println(appInfo);
19370                    }
19371                }
19372            }
19373
19374            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19375                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19376            }
19377
19378            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19379                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19380            }
19381
19382            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19383                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19384            }
19385
19386            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19387                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19388            }
19389
19390            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19391                // XXX should handle packageName != null by dumping only install data that
19392                // the given package is involved with.
19393                if (dumpState.onTitlePrinted()) pw.println();
19394                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19395            }
19396
19397            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19398                // XXX should handle packageName != null by dumping only install data that
19399                // the given package is involved with.
19400                if (dumpState.onTitlePrinted()) pw.println();
19401
19402                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19403                ipw.println();
19404                ipw.println("Frozen packages:");
19405                ipw.increaseIndent();
19406                if (mFrozenPackages.size() == 0) {
19407                    ipw.println("(none)");
19408                } else {
19409                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19410                        ipw.println(mFrozenPackages.valueAt(i));
19411                    }
19412                }
19413                ipw.decreaseIndent();
19414            }
19415
19416            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19417                if (dumpState.onTitlePrinted()) pw.println();
19418                dumpDexoptStateLPr(pw, packageName);
19419            }
19420
19421            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19422                if (dumpState.onTitlePrinted()) pw.println();
19423                dumpCompilerStatsLPr(pw, packageName);
19424            }
19425
19426            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19427                if (dumpState.onTitlePrinted()) pw.println();
19428                mSettings.dumpReadMessagesLPr(pw, dumpState);
19429
19430                pw.println();
19431                pw.println("Package warning messages:");
19432                BufferedReader in = null;
19433                String line = null;
19434                try {
19435                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19436                    while ((line = in.readLine()) != null) {
19437                        if (line.contains("ignored: updated version")) continue;
19438                        pw.println(line);
19439                    }
19440                } catch (IOException ignored) {
19441                } finally {
19442                    IoUtils.closeQuietly(in);
19443                }
19444            }
19445
19446            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19447                BufferedReader in = null;
19448                String line = null;
19449                try {
19450                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19451                    while ((line = in.readLine()) != null) {
19452                        if (line.contains("ignored: updated version")) continue;
19453                        pw.print("msg,");
19454                        pw.println(line);
19455                    }
19456                } catch (IOException ignored) {
19457                } finally {
19458                    IoUtils.closeQuietly(in);
19459                }
19460            }
19461        }
19462    }
19463
19464    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19465        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19466        ipw.println();
19467        ipw.println("Dexopt state:");
19468        ipw.increaseIndent();
19469        Collection<PackageParser.Package> packages = null;
19470        if (packageName != null) {
19471            PackageParser.Package targetPackage = mPackages.get(packageName);
19472            if (targetPackage != null) {
19473                packages = Collections.singletonList(targetPackage);
19474            } else {
19475                ipw.println("Unable to find package: " + packageName);
19476                return;
19477            }
19478        } else {
19479            packages = mPackages.values();
19480        }
19481
19482        for (PackageParser.Package pkg : packages) {
19483            ipw.println("[" + pkg.packageName + "]");
19484            ipw.increaseIndent();
19485            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19486            ipw.decreaseIndent();
19487        }
19488    }
19489
19490    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19491        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19492        ipw.println();
19493        ipw.println("Compiler stats:");
19494        ipw.increaseIndent();
19495        Collection<PackageParser.Package> packages = null;
19496        if (packageName != null) {
19497            PackageParser.Package targetPackage = mPackages.get(packageName);
19498            if (targetPackage != null) {
19499                packages = Collections.singletonList(targetPackage);
19500            } else {
19501                ipw.println("Unable to find package: " + packageName);
19502                return;
19503            }
19504        } else {
19505            packages = mPackages.values();
19506        }
19507
19508        for (PackageParser.Package pkg : packages) {
19509            ipw.println("[" + pkg.packageName + "]");
19510            ipw.increaseIndent();
19511
19512            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19513            if (stats == null) {
19514                ipw.println("(No recorded stats)");
19515            } else {
19516                stats.dump(ipw);
19517            }
19518            ipw.decreaseIndent();
19519        }
19520    }
19521
19522    private String dumpDomainString(String packageName) {
19523        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19524                .getList();
19525        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19526
19527        ArraySet<String> result = new ArraySet<>();
19528        if (iviList.size() > 0) {
19529            for (IntentFilterVerificationInfo ivi : iviList) {
19530                for (String host : ivi.getDomains()) {
19531                    result.add(host);
19532                }
19533            }
19534        }
19535        if (filters != null && filters.size() > 0) {
19536            for (IntentFilter filter : filters) {
19537                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19538                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19539                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19540                    result.addAll(filter.getHostsList());
19541                }
19542            }
19543        }
19544
19545        StringBuilder sb = new StringBuilder(result.size() * 16);
19546        for (String domain : result) {
19547            if (sb.length() > 0) sb.append(" ");
19548            sb.append(domain);
19549        }
19550        return sb.toString();
19551    }
19552
19553    // ------- apps on sdcard specific code -------
19554    static final boolean DEBUG_SD_INSTALL = false;
19555
19556    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19557
19558    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19559
19560    private boolean mMediaMounted = false;
19561
19562    static String getEncryptKey() {
19563        try {
19564            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19565                    SD_ENCRYPTION_KEYSTORE_NAME);
19566            if (sdEncKey == null) {
19567                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19568                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19569                if (sdEncKey == null) {
19570                    Slog.e(TAG, "Failed to create encryption keys");
19571                    return null;
19572                }
19573            }
19574            return sdEncKey;
19575        } catch (NoSuchAlgorithmException nsae) {
19576            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19577            return null;
19578        } catch (IOException ioe) {
19579            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19580            return null;
19581        }
19582    }
19583
19584    /*
19585     * Update media status on PackageManager.
19586     */
19587    @Override
19588    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19589        int callingUid = Binder.getCallingUid();
19590        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19591            throw new SecurityException("Media status can only be updated by the system");
19592        }
19593        // reader; this apparently protects mMediaMounted, but should probably
19594        // be a different lock in that case.
19595        synchronized (mPackages) {
19596            Log.i(TAG, "Updating external media status from "
19597                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19598                    + (mediaStatus ? "mounted" : "unmounted"));
19599            if (DEBUG_SD_INSTALL)
19600                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19601                        + ", mMediaMounted=" + mMediaMounted);
19602            if (mediaStatus == mMediaMounted) {
19603                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19604                        : 0, -1);
19605                mHandler.sendMessage(msg);
19606                return;
19607            }
19608            mMediaMounted = mediaStatus;
19609        }
19610        // Queue up an async operation since the package installation may take a
19611        // little while.
19612        mHandler.post(new Runnable() {
19613            public void run() {
19614                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19615            }
19616        });
19617    }
19618
19619    /**
19620     * Called by StorageManagerService when the initial ASECs to scan are available.
19621     * Should block until all the ASEC containers are finished being scanned.
19622     */
19623    public void scanAvailableAsecs() {
19624        updateExternalMediaStatusInner(true, false, false);
19625    }
19626
19627    /*
19628     * Collect information of applications on external media, map them against
19629     * existing containers and update information based on current mount status.
19630     * Please note that we always have to report status if reportStatus has been
19631     * set to true especially when unloading packages.
19632     */
19633    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19634            boolean externalStorage) {
19635        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19636        int[] uidArr = EmptyArray.INT;
19637
19638        final String[] list = PackageHelper.getSecureContainerList();
19639        if (ArrayUtils.isEmpty(list)) {
19640            Log.i(TAG, "No secure containers found");
19641        } else {
19642            // Process list of secure containers and categorize them
19643            // as active or stale based on their package internal state.
19644
19645            // reader
19646            synchronized (mPackages) {
19647                for (String cid : list) {
19648                    // Leave stages untouched for now; installer service owns them
19649                    if (PackageInstallerService.isStageName(cid)) continue;
19650
19651                    if (DEBUG_SD_INSTALL)
19652                        Log.i(TAG, "Processing container " + cid);
19653                    String pkgName = getAsecPackageName(cid);
19654                    if (pkgName == null) {
19655                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19656                        continue;
19657                    }
19658                    if (DEBUG_SD_INSTALL)
19659                        Log.i(TAG, "Looking for pkg : " + pkgName);
19660
19661                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19662                    if (ps == null) {
19663                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19664                        continue;
19665                    }
19666
19667                    /*
19668                     * Skip packages that are not external if we're unmounting
19669                     * external storage.
19670                     */
19671                    if (externalStorage && !isMounted && !isExternal(ps)) {
19672                        continue;
19673                    }
19674
19675                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19676                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19677                    // The package status is changed only if the code path
19678                    // matches between settings and the container id.
19679                    if (ps.codePathString != null
19680                            && ps.codePathString.startsWith(args.getCodePath())) {
19681                        if (DEBUG_SD_INSTALL) {
19682                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19683                                    + " at code path: " + ps.codePathString);
19684                        }
19685
19686                        // We do have a valid package installed on sdcard
19687                        processCids.put(args, ps.codePathString);
19688                        final int uid = ps.appId;
19689                        if (uid != -1) {
19690                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19691                        }
19692                    } else {
19693                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19694                                + ps.codePathString);
19695                    }
19696                }
19697            }
19698
19699            Arrays.sort(uidArr);
19700        }
19701
19702        // Process packages with valid entries.
19703        if (isMounted) {
19704            if (DEBUG_SD_INSTALL)
19705                Log.i(TAG, "Loading packages");
19706            loadMediaPackages(processCids, uidArr, externalStorage);
19707            startCleaningPackages();
19708            mInstallerService.onSecureContainersAvailable();
19709        } else {
19710            if (DEBUG_SD_INSTALL)
19711                Log.i(TAG, "Unloading packages");
19712            unloadMediaPackages(processCids, uidArr, reportStatus);
19713        }
19714    }
19715
19716    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19717            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19718        final int size = infos.size();
19719        final String[] packageNames = new String[size];
19720        final int[] packageUids = new int[size];
19721        for (int i = 0; i < size; i++) {
19722            final ApplicationInfo info = infos.get(i);
19723            packageNames[i] = info.packageName;
19724            packageUids[i] = info.uid;
19725        }
19726        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19727                finishedReceiver);
19728    }
19729
19730    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19731            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19732        sendResourcesChangedBroadcast(mediaStatus, replacing,
19733                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19734    }
19735
19736    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19737            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19738        int size = pkgList.length;
19739        if (size > 0) {
19740            // Send broadcasts here
19741            Bundle extras = new Bundle();
19742            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19743            if (uidArr != null) {
19744                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19745            }
19746            if (replacing) {
19747                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19748            }
19749            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19750                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19751            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19752        }
19753    }
19754
19755   /*
19756     * Look at potentially valid container ids from processCids If package
19757     * information doesn't match the one on record or package scanning fails,
19758     * the cid is added to list of removeCids. We currently don't delete stale
19759     * containers.
19760     */
19761    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19762            boolean externalStorage) {
19763        ArrayList<String> pkgList = new ArrayList<String>();
19764        Set<AsecInstallArgs> keys = processCids.keySet();
19765
19766        for (AsecInstallArgs args : keys) {
19767            String codePath = processCids.get(args);
19768            if (DEBUG_SD_INSTALL)
19769                Log.i(TAG, "Loading container : " + args.cid);
19770            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19771            try {
19772                // Make sure there are no container errors first.
19773                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19774                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19775                            + " when installing from sdcard");
19776                    continue;
19777                }
19778                // Check code path here.
19779                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19780                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19781                            + " does not match one in settings " + codePath);
19782                    continue;
19783                }
19784                // Parse package
19785                int parseFlags = mDefParseFlags;
19786                if (args.isExternalAsec()) {
19787                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19788                }
19789                if (args.isFwdLocked()) {
19790                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19791                }
19792
19793                synchronized (mInstallLock) {
19794                    PackageParser.Package pkg = null;
19795                    try {
19796                        // Sadly we don't know the package name yet to freeze it
19797                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19798                                SCAN_IGNORE_FROZEN, 0, null);
19799                    } catch (PackageManagerException e) {
19800                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19801                    }
19802                    // Scan the package
19803                    if (pkg != null) {
19804                        /*
19805                         * TODO why is the lock being held? doPostInstall is
19806                         * called in other places without the lock. This needs
19807                         * to be straightened out.
19808                         */
19809                        // writer
19810                        synchronized (mPackages) {
19811                            retCode = PackageManager.INSTALL_SUCCEEDED;
19812                            pkgList.add(pkg.packageName);
19813                            // Post process args
19814                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19815                                    pkg.applicationInfo.uid);
19816                        }
19817                    } else {
19818                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19819                    }
19820                }
19821
19822            } finally {
19823                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19824                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19825                }
19826            }
19827        }
19828        // writer
19829        synchronized (mPackages) {
19830            // If the platform SDK has changed since the last time we booted,
19831            // we need to re-grant app permission to catch any new ones that
19832            // appear. This is really a hack, and means that apps can in some
19833            // cases get permissions that the user didn't initially explicitly
19834            // allow... it would be nice to have some better way to handle
19835            // this situation.
19836            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19837                    : mSettings.getInternalVersion();
19838            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19839                    : StorageManager.UUID_PRIVATE_INTERNAL;
19840
19841            int updateFlags = UPDATE_PERMISSIONS_ALL;
19842            if (ver.sdkVersion != mSdkVersion) {
19843                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19844                        + mSdkVersion + "; regranting permissions for external");
19845                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19846            }
19847            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19848
19849            // Yay, everything is now upgraded
19850            ver.forceCurrent();
19851
19852            // can downgrade to reader
19853            // Persist settings
19854            mSettings.writeLPr();
19855        }
19856        // Send a broadcast to let everyone know we are done processing
19857        if (pkgList.size() > 0) {
19858            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19859        }
19860    }
19861
19862   /*
19863     * Utility method to unload a list of specified containers
19864     */
19865    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19866        // Just unmount all valid containers.
19867        for (AsecInstallArgs arg : cidArgs) {
19868            synchronized (mInstallLock) {
19869                arg.doPostDeleteLI(false);
19870           }
19871       }
19872   }
19873
19874    /*
19875     * Unload packages mounted on external media. This involves deleting package
19876     * data from internal structures, sending broadcasts about disabled packages,
19877     * gc'ing to free up references, unmounting all secure containers
19878     * corresponding to packages on external media, and posting a
19879     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19880     * that we always have to post this message if status has been requested no
19881     * matter what.
19882     */
19883    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19884            final boolean reportStatus) {
19885        if (DEBUG_SD_INSTALL)
19886            Log.i(TAG, "unloading media packages");
19887        ArrayList<String> pkgList = new ArrayList<String>();
19888        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19889        final Set<AsecInstallArgs> keys = processCids.keySet();
19890        for (AsecInstallArgs args : keys) {
19891            String pkgName = args.getPackageName();
19892            if (DEBUG_SD_INSTALL)
19893                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19894            // Delete package internally
19895            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19896            synchronized (mInstallLock) {
19897                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19898                final boolean res;
19899                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19900                        "unloadMediaPackages")) {
19901                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19902                            null);
19903                }
19904                if (res) {
19905                    pkgList.add(pkgName);
19906                } else {
19907                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19908                    failedList.add(args);
19909                }
19910            }
19911        }
19912
19913        // reader
19914        synchronized (mPackages) {
19915            // We didn't update the settings after removing each package;
19916            // write them now for all packages.
19917            mSettings.writeLPr();
19918        }
19919
19920        // We have to absolutely send UPDATED_MEDIA_STATUS only
19921        // after confirming that all the receivers processed the ordered
19922        // broadcast when packages get disabled, force a gc to clean things up.
19923        // and unload all the containers.
19924        if (pkgList.size() > 0) {
19925            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19926                    new IIntentReceiver.Stub() {
19927                public void performReceive(Intent intent, int resultCode, String data,
19928                        Bundle extras, boolean ordered, boolean sticky,
19929                        int sendingUser) throws RemoteException {
19930                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19931                            reportStatus ? 1 : 0, 1, keys);
19932                    mHandler.sendMessage(msg);
19933                }
19934            });
19935        } else {
19936            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19937                    keys);
19938            mHandler.sendMessage(msg);
19939        }
19940    }
19941
19942    private void loadPrivatePackages(final VolumeInfo vol) {
19943        mHandler.post(new Runnable() {
19944            @Override
19945            public void run() {
19946                loadPrivatePackagesInner(vol);
19947            }
19948        });
19949    }
19950
19951    private void loadPrivatePackagesInner(VolumeInfo vol) {
19952        final String volumeUuid = vol.fsUuid;
19953        if (TextUtils.isEmpty(volumeUuid)) {
19954            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19955            return;
19956        }
19957
19958        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19959        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19960        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19961
19962        final VersionInfo ver;
19963        final List<PackageSetting> packages;
19964        synchronized (mPackages) {
19965            ver = mSettings.findOrCreateVersion(volumeUuid);
19966            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19967        }
19968
19969        for (PackageSetting ps : packages) {
19970            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19971            synchronized (mInstallLock) {
19972                final PackageParser.Package pkg;
19973                try {
19974                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19975                    loaded.add(pkg.applicationInfo);
19976
19977                } catch (PackageManagerException e) {
19978                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19979                }
19980
19981                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19982                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19983                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19984                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19985                }
19986            }
19987        }
19988
19989        // Reconcile app data for all started/unlocked users
19990        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19991        final UserManager um = mContext.getSystemService(UserManager.class);
19992        UserManagerInternal umInternal = getUserManagerInternal();
19993        for (UserInfo user : um.getUsers()) {
19994            final int flags;
19995            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19996                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19997            } else if (umInternal.isUserRunning(user.id)) {
19998                flags = StorageManager.FLAG_STORAGE_DE;
19999            } else {
20000                continue;
20001            }
20002
20003            try {
20004                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20005                synchronized (mInstallLock) {
20006                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20007                }
20008            } catch (IllegalStateException e) {
20009                // Device was probably ejected, and we'll process that event momentarily
20010                Slog.w(TAG, "Failed to prepare storage: " + e);
20011            }
20012        }
20013
20014        synchronized (mPackages) {
20015            int updateFlags = UPDATE_PERMISSIONS_ALL;
20016            if (ver.sdkVersion != mSdkVersion) {
20017                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20018                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20019                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20020            }
20021            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20022
20023            // Yay, everything is now upgraded
20024            ver.forceCurrent();
20025
20026            mSettings.writeLPr();
20027        }
20028
20029        for (PackageFreezer freezer : freezers) {
20030            freezer.close();
20031        }
20032
20033        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20034        sendResourcesChangedBroadcast(true, false, loaded, null);
20035    }
20036
20037    private void unloadPrivatePackages(final VolumeInfo vol) {
20038        mHandler.post(new Runnable() {
20039            @Override
20040            public void run() {
20041                unloadPrivatePackagesInner(vol);
20042            }
20043        });
20044    }
20045
20046    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20047        final String volumeUuid = vol.fsUuid;
20048        if (TextUtils.isEmpty(volumeUuid)) {
20049            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20050            return;
20051        }
20052
20053        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20054        synchronized (mInstallLock) {
20055        synchronized (mPackages) {
20056            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20057            for (PackageSetting ps : packages) {
20058                if (ps.pkg == null) continue;
20059
20060                final ApplicationInfo info = ps.pkg.applicationInfo;
20061                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20062                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20063
20064                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20065                        "unloadPrivatePackagesInner")) {
20066                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20067                            false, null)) {
20068                        unloaded.add(info);
20069                    } else {
20070                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20071                    }
20072                }
20073
20074                // Try very hard to release any references to this package
20075                // so we don't risk the system server being killed due to
20076                // open FDs
20077                AttributeCache.instance().removePackage(ps.name);
20078            }
20079
20080            mSettings.writeLPr();
20081        }
20082        }
20083
20084        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20085        sendResourcesChangedBroadcast(false, false, unloaded, null);
20086
20087        // Try very hard to release any references to this path so we don't risk
20088        // the system server being killed due to open FDs
20089        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20090
20091        for (int i = 0; i < 3; i++) {
20092            System.gc();
20093            System.runFinalization();
20094        }
20095    }
20096
20097    /**
20098     * Prepare storage areas for given user on all mounted devices.
20099     */
20100    void prepareUserData(int userId, int userSerial, int flags) {
20101        synchronized (mInstallLock) {
20102            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20103            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20104                final String volumeUuid = vol.getFsUuid();
20105                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20106            }
20107        }
20108    }
20109
20110    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20111            boolean allowRecover) {
20112        // Prepare storage and verify that serial numbers are consistent; if
20113        // there's a mismatch we need to destroy to avoid leaking data
20114        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20115        try {
20116            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20117
20118            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20119                UserManagerService.enforceSerialNumber(
20120                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20121                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20122                    UserManagerService.enforceSerialNumber(
20123                            Environment.getDataSystemDeDirectory(userId), userSerial);
20124                }
20125            }
20126            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20127                UserManagerService.enforceSerialNumber(
20128                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20129                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20130                    UserManagerService.enforceSerialNumber(
20131                            Environment.getDataSystemCeDirectory(userId), userSerial);
20132                }
20133            }
20134
20135            synchronized (mInstallLock) {
20136                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20137            }
20138        } catch (Exception e) {
20139            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20140                    + " because we failed to prepare: " + e);
20141            destroyUserDataLI(volumeUuid, userId,
20142                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20143
20144            if (allowRecover) {
20145                // Try one last time; if we fail again we're really in trouble
20146                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20147            }
20148        }
20149    }
20150
20151    /**
20152     * Destroy storage areas for given user on all mounted devices.
20153     */
20154    void destroyUserData(int userId, int flags) {
20155        synchronized (mInstallLock) {
20156            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20157            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20158                final String volumeUuid = vol.getFsUuid();
20159                destroyUserDataLI(volumeUuid, userId, flags);
20160            }
20161        }
20162    }
20163
20164    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20165        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20166        try {
20167            // Clean up app data, profile data, and media data
20168            mInstaller.destroyUserData(volumeUuid, userId, flags);
20169
20170            // Clean up system data
20171            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20172                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20173                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20174                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20175                }
20176                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20177                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20178                }
20179            }
20180
20181            // Data with special labels is now gone, so finish the job
20182            storage.destroyUserStorage(volumeUuid, userId, flags);
20183
20184        } catch (Exception e) {
20185            logCriticalInfo(Log.WARN,
20186                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20187        }
20188    }
20189
20190    /**
20191     * Examine all users present on given mounted volume, and destroy data
20192     * belonging to users that are no longer valid, or whose user ID has been
20193     * recycled.
20194     */
20195    private void reconcileUsers(String volumeUuid) {
20196        final List<File> files = new ArrayList<>();
20197        Collections.addAll(files, FileUtils
20198                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20199        Collections.addAll(files, FileUtils
20200                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20201        Collections.addAll(files, FileUtils
20202                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20203        Collections.addAll(files, FileUtils
20204                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20205        for (File file : files) {
20206            if (!file.isDirectory()) continue;
20207
20208            final int userId;
20209            final UserInfo info;
20210            try {
20211                userId = Integer.parseInt(file.getName());
20212                info = sUserManager.getUserInfo(userId);
20213            } catch (NumberFormatException e) {
20214                Slog.w(TAG, "Invalid user directory " + file);
20215                continue;
20216            }
20217
20218            boolean destroyUser = false;
20219            if (info == null) {
20220                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20221                        + " because no matching user was found");
20222                destroyUser = true;
20223            } else if (!mOnlyCore) {
20224                try {
20225                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20226                } catch (IOException e) {
20227                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20228                            + " because we failed to enforce serial number: " + e);
20229                    destroyUser = true;
20230                }
20231            }
20232
20233            if (destroyUser) {
20234                synchronized (mInstallLock) {
20235                    destroyUserDataLI(volumeUuid, userId,
20236                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20237                }
20238            }
20239        }
20240    }
20241
20242    private void assertPackageKnown(String volumeUuid, String packageName)
20243            throws PackageManagerException {
20244        synchronized (mPackages) {
20245            // Normalize package name to handle renamed packages
20246            packageName = normalizePackageNameLPr(packageName);
20247
20248            final PackageSetting ps = mSettings.mPackages.get(packageName);
20249            if (ps == null) {
20250                throw new PackageManagerException("Package " + packageName + " is unknown");
20251            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20252                throw new PackageManagerException(
20253                        "Package " + packageName + " found on unknown volume " + volumeUuid
20254                                + "; expected volume " + ps.volumeUuid);
20255            }
20256        }
20257    }
20258
20259    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20260            throws PackageManagerException {
20261        synchronized (mPackages) {
20262            // Normalize package name to handle renamed packages
20263            packageName = normalizePackageNameLPr(packageName);
20264
20265            final PackageSetting ps = mSettings.mPackages.get(packageName);
20266            if (ps == null) {
20267                throw new PackageManagerException("Package " + packageName + " is unknown");
20268            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20269                throw new PackageManagerException(
20270                        "Package " + packageName + " found on unknown volume " + volumeUuid
20271                                + "; expected volume " + ps.volumeUuid);
20272            } else if (!ps.getInstalled(userId)) {
20273                throw new PackageManagerException(
20274                        "Package " + packageName + " not installed for user " + userId);
20275            }
20276        }
20277    }
20278
20279    /**
20280     * Examine all apps present on given mounted volume, and destroy apps that
20281     * aren't expected, either due to uninstallation or reinstallation on
20282     * another volume.
20283     */
20284    private void reconcileApps(String volumeUuid) {
20285        final File[] files = FileUtils
20286                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20287        for (File file : files) {
20288            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20289                    && !PackageInstallerService.isStageName(file.getName());
20290            if (!isPackage) {
20291                // Ignore entries which are not packages
20292                continue;
20293            }
20294
20295            try {
20296                final PackageLite pkg = PackageParser.parsePackageLite(file,
20297                        PackageParser.PARSE_MUST_BE_APK);
20298                assertPackageKnown(volumeUuid, pkg.packageName);
20299
20300            } catch (PackageParserException | PackageManagerException e) {
20301                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20302                synchronized (mInstallLock) {
20303                    removeCodePathLI(file);
20304                }
20305            }
20306        }
20307    }
20308
20309    /**
20310     * Reconcile all app data for the given user.
20311     * <p>
20312     * Verifies that directories exist and that ownership and labeling is
20313     * correct for all installed apps on all mounted volumes.
20314     */
20315    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20316        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20317        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20318            final String volumeUuid = vol.getFsUuid();
20319            synchronized (mInstallLock) {
20320                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20321            }
20322        }
20323    }
20324
20325    /**
20326     * Reconcile all app data on given mounted volume.
20327     * <p>
20328     * Destroys app data that isn't expected, either due to uninstallation or
20329     * reinstallation on another volume.
20330     * <p>
20331     * Verifies that directories exist and that ownership and labeling is
20332     * correct for all installed apps.
20333     */
20334    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20335            boolean migrateAppData) {
20336        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20337                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20338
20339        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20340        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20341
20342        // First look for stale data that doesn't belong, and check if things
20343        // have changed since we did our last restorecon
20344        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20345            if (StorageManager.isFileEncryptedNativeOrEmulated()
20346                    && !StorageManager.isUserKeyUnlocked(userId)) {
20347                throw new RuntimeException(
20348                        "Yikes, someone asked us to reconcile CE storage while " + userId
20349                                + " was still locked; this would have caused massive data loss!");
20350            }
20351
20352            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20353            for (File file : files) {
20354                final String packageName = file.getName();
20355                try {
20356                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20357                } catch (PackageManagerException e) {
20358                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20359                    try {
20360                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20361                                StorageManager.FLAG_STORAGE_CE, 0);
20362                    } catch (InstallerException e2) {
20363                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20364                    }
20365                }
20366            }
20367        }
20368        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20369            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20370            for (File file : files) {
20371                final String packageName = file.getName();
20372                try {
20373                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20374                } catch (PackageManagerException e) {
20375                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20376                    try {
20377                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20378                                StorageManager.FLAG_STORAGE_DE, 0);
20379                    } catch (InstallerException e2) {
20380                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20381                    }
20382                }
20383            }
20384        }
20385
20386        // Ensure that data directories are ready to roll for all packages
20387        // installed for this volume and user
20388        final List<PackageSetting> packages;
20389        synchronized (mPackages) {
20390            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20391        }
20392        int preparedCount = 0;
20393        for (PackageSetting ps : packages) {
20394            final String packageName = ps.name;
20395            if (ps.pkg == null) {
20396                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20397                // TODO: might be due to legacy ASEC apps; we should circle back
20398                // and reconcile again once they're scanned
20399                continue;
20400            }
20401
20402            if (ps.getInstalled(userId)) {
20403                prepareAppDataLIF(ps.pkg, userId, flags);
20404
20405                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20406                    // We may have just shuffled around app data directories, so
20407                    // prepare them one more time
20408                    prepareAppDataLIF(ps.pkg, userId, flags);
20409                }
20410
20411                preparedCount++;
20412            }
20413        }
20414
20415        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20416    }
20417
20418    /**
20419     * Prepare app data for the given app just after it was installed or
20420     * upgraded. This method carefully only touches users that it's installed
20421     * for, and it forces a restorecon to handle any seinfo changes.
20422     * <p>
20423     * Verifies that directories exist and that ownership and labeling is
20424     * correct for all installed apps. If there is an ownership mismatch, it
20425     * will try recovering system apps by wiping data; third-party app data is
20426     * left intact.
20427     * <p>
20428     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20429     */
20430    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20431        final PackageSetting ps;
20432        synchronized (mPackages) {
20433            ps = mSettings.mPackages.get(pkg.packageName);
20434            mSettings.writeKernelMappingLPr(ps);
20435        }
20436
20437        final UserManager um = mContext.getSystemService(UserManager.class);
20438        UserManagerInternal umInternal = getUserManagerInternal();
20439        for (UserInfo user : um.getUsers()) {
20440            final int flags;
20441            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20442                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20443            } else if (umInternal.isUserRunning(user.id)) {
20444                flags = StorageManager.FLAG_STORAGE_DE;
20445            } else {
20446                continue;
20447            }
20448
20449            if (ps.getInstalled(user.id)) {
20450                // TODO: when user data is locked, mark that we're still dirty
20451                prepareAppDataLIF(pkg, user.id, flags);
20452            }
20453        }
20454    }
20455
20456    /**
20457     * Prepare app data for the given app.
20458     * <p>
20459     * Verifies that directories exist and that ownership and labeling is
20460     * correct for all installed apps. If there is an ownership mismatch, this
20461     * will try recovering system apps by wiping data; third-party app data is
20462     * left intact.
20463     */
20464    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20465        if (pkg == null) {
20466            Slog.wtf(TAG, "Package was null!", new Throwable());
20467            return;
20468        }
20469        prepareAppDataLeafLIF(pkg, userId, flags);
20470        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20471        for (int i = 0; i < childCount; i++) {
20472            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20473        }
20474    }
20475
20476    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20477        if (DEBUG_APP_DATA) {
20478            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20479                    + Integer.toHexString(flags));
20480        }
20481
20482        final String volumeUuid = pkg.volumeUuid;
20483        final String packageName = pkg.packageName;
20484        final ApplicationInfo app = pkg.applicationInfo;
20485        final int appId = UserHandle.getAppId(app.uid);
20486
20487        Preconditions.checkNotNull(app.seinfo);
20488
20489        try {
20490            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20491                    appId, app.seinfo, app.targetSdkVersion);
20492        } catch (InstallerException e) {
20493            if (app.isSystemApp()) {
20494                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20495                        + ", but trying to recover: " + e);
20496                destroyAppDataLeafLIF(pkg, userId, flags);
20497                try {
20498                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20499                            appId, app.seinfo, app.targetSdkVersion);
20500                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20501                } catch (InstallerException e2) {
20502                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20503                }
20504            } else {
20505                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20506            }
20507        }
20508
20509        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20510            try {
20511                // CE storage is unlocked right now, so read out the inode and
20512                // remember for use later when it's locked
20513                // TODO: mark this structure as dirty so we persist it!
20514                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20515                        StorageManager.FLAG_STORAGE_CE);
20516                synchronized (mPackages) {
20517                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20518                    if (ps != null) {
20519                        ps.setCeDataInode(ceDataInode, userId);
20520                    }
20521                }
20522            } catch (InstallerException e) {
20523                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20524            }
20525        }
20526
20527        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20528    }
20529
20530    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20531        if (pkg == null) {
20532            Slog.wtf(TAG, "Package was null!", new Throwable());
20533            return;
20534        }
20535        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20536        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20537        for (int i = 0; i < childCount; i++) {
20538            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20539        }
20540    }
20541
20542    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20543        final String volumeUuid = pkg.volumeUuid;
20544        final String packageName = pkg.packageName;
20545        final ApplicationInfo app = pkg.applicationInfo;
20546
20547        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20548            // Create a native library symlink only if we have native libraries
20549            // and if the native libraries are 32 bit libraries. We do not provide
20550            // this symlink for 64 bit libraries.
20551            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20552                final String nativeLibPath = app.nativeLibraryDir;
20553                try {
20554                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20555                            nativeLibPath, userId);
20556                } catch (InstallerException e) {
20557                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20558                }
20559            }
20560        }
20561    }
20562
20563    /**
20564     * For system apps on non-FBE devices, this method migrates any existing
20565     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20566     * requested by the app.
20567     */
20568    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20569        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20570                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20571            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20572                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20573            try {
20574                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20575                        storageTarget);
20576            } catch (InstallerException e) {
20577                logCriticalInfo(Log.WARN,
20578                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20579            }
20580            return true;
20581        } else {
20582            return false;
20583        }
20584    }
20585
20586    public PackageFreezer freezePackage(String packageName, String killReason) {
20587        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20588    }
20589
20590    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20591        return new PackageFreezer(packageName, userId, killReason);
20592    }
20593
20594    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20595            String killReason) {
20596        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20597    }
20598
20599    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20600            String killReason) {
20601        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20602            return new PackageFreezer();
20603        } else {
20604            return freezePackage(packageName, userId, killReason);
20605        }
20606    }
20607
20608    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20609            String killReason) {
20610        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20611    }
20612
20613    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20614            String killReason) {
20615        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20616            return new PackageFreezer();
20617        } else {
20618            return freezePackage(packageName, userId, killReason);
20619        }
20620    }
20621
20622    /**
20623     * Class that freezes and kills the given package upon creation, and
20624     * unfreezes it upon closing. This is typically used when doing surgery on
20625     * app code/data to prevent the app from running while you're working.
20626     */
20627    private class PackageFreezer implements AutoCloseable {
20628        private final String mPackageName;
20629        private final PackageFreezer[] mChildren;
20630
20631        private final boolean mWeFroze;
20632
20633        private final AtomicBoolean mClosed = new AtomicBoolean();
20634        private final CloseGuard mCloseGuard = CloseGuard.get();
20635
20636        /**
20637         * Create and return a stub freezer that doesn't actually do anything,
20638         * typically used when someone requested
20639         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20640         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20641         */
20642        public PackageFreezer() {
20643            mPackageName = null;
20644            mChildren = null;
20645            mWeFroze = false;
20646            mCloseGuard.open("close");
20647        }
20648
20649        public PackageFreezer(String packageName, int userId, String killReason) {
20650            synchronized (mPackages) {
20651                mPackageName = packageName;
20652                mWeFroze = mFrozenPackages.add(mPackageName);
20653
20654                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20655                if (ps != null) {
20656                    killApplication(ps.name, ps.appId, userId, killReason);
20657                }
20658
20659                final PackageParser.Package p = mPackages.get(packageName);
20660                if (p != null && p.childPackages != null) {
20661                    final int N = p.childPackages.size();
20662                    mChildren = new PackageFreezer[N];
20663                    for (int i = 0; i < N; i++) {
20664                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20665                                userId, killReason);
20666                    }
20667                } else {
20668                    mChildren = null;
20669                }
20670            }
20671            mCloseGuard.open("close");
20672        }
20673
20674        @Override
20675        protected void finalize() throws Throwable {
20676            try {
20677                mCloseGuard.warnIfOpen();
20678                close();
20679            } finally {
20680                super.finalize();
20681            }
20682        }
20683
20684        @Override
20685        public void close() {
20686            mCloseGuard.close();
20687            if (mClosed.compareAndSet(false, true)) {
20688                synchronized (mPackages) {
20689                    if (mWeFroze) {
20690                        mFrozenPackages.remove(mPackageName);
20691                    }
20692
20693                    if (mChildren != null) {
20694                        for (PackageFreezer freezer : mChildren) {
20695                            freezer.close();
20696                        }
20697                    }
20698                }
20699            }
20700        }
20701    }
20702
20703    /**
20704     * Verify that given package is currently frozen.
20705     */
20706    private void checkPackageFrozen(String packageName) {
20707        synchronized (mPackages) {
20708            if (!mFrozenPackages.contains(packageName)) {
20709                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20710            }
20711        }
20712    }
20713
20714    @Override
20715    public int movePackage(final String packageName, final String volumeUuid) {
20716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20717
20718        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20719        final int moveId = mNextMoveId.getAndIncrement();
20720        mHandler.post(new Runnable() {
20721            @Override
20722            public void run() {
20723                try {
20724                    movePackageInternal(packageName, volumeUuid, moveId, user);
20725                } catch (PackageManagerException e) {
20726                    Slog.w(TAG, "Failed to move " + packageName, e);
20727                    mMoveCallbacks.notifyStatusChanged(moveId,
20728                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20729                }
20730            }
20731        });
20732        return moveId;
20733    }
20734
20735    private void movePackageInternal(final String packageName, final String volumeUuid,
20736            final int moveId, UserHandle user) throws PackageManagerException {
20737        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20738        final PackageManager pm = mContext.getPackageManager();
20739
20740        final boolean currentAsec;
20741        final String currentVolumeUuid;
20742        final File codeFile;
20743        final String installerPackageName;
20744        final String packageAbiOverride;
20745        final int appId;
20746        final String seinfo;
20747        final String label;
20748        final int targetSdkVersion;
20749        final PackageFreezer freezer;
20750        final int[] installedUserIds;
20751
20752        // reader
20753        synchronized (mPackages) {
20754            final PackageParser.Package pkg = mPackages.get(packageName);
20755            final PackageSetting ps = mSettings.mPackages.get(packageName);
20756            if (pkg == null || ps == null) {
20757                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20758            }
20759
20760            if (pkg.applicationInfo.isSystemApp()) {
20761                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20762                        "Cannot move system application");
20763            }
20764
20765            if (pkg.applicationInfo.isExternalAsec()) {
20766                currentAsec = true;
20767                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20768            } else if (pkg.applicationInfo.isForwardLocked()) {
20769                currentAsec = true;
20770                currentVolumeUuid = "forward_locked";
20771            } else {
20772                currentAsec = false;
20773                currentVolumeUuid = ps.volumeUuid;
20774
20775                final File probe = new File(pkg.codePath);
20776                final File probeOat = new File(probe, "oat");
20777                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20778                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20779                            "Move only supported for modern cluster style installs");
20780                }
20781            }
20782
20783            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20784                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20785                        "Package already moved to " + volumeUuid);
20786            }
20787            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20788                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20789                        "Device admin cannot be moved");
20790            }
20791
20792            if (mFrozenPackages.contains(packageName)) {
20793                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20794                        "Failed to move already frozen package");
20795            }
20796
20797            codeFile = new File(pkg.codePath);
20798            installerPackageName = ps.installerPackageName;
20799            packageAbiOverride = ps.cpuAbiOverrideString;
20800            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20801            seinfo = pkg.applicationInfo.seinfo;
20802            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20803            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20804            freezer = freezePackage(packageName, "movePackageInternal");
20805            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20806        }
20807
20808        final Bundle extras = new Bundle();
20809        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20810        extras.putString(Intent.EXTRA_TITLE, label);
20811        mMoveCallbacks.notifyCreated(moveId, extras);
20812
20813        int installFlags;
20814        final boolean moveCompleteApp;
20815        final File measurePath;
20816
20817        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20818            installFlags = INSTALL_INTERNAL;
20819            moveCompleteApp = !currentAsec;
20820            measurePath = Environment.getDataAppDirectory(volumeUuid);
20821        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20822            installFlags = INSTALL_EXTERNAL;
20823            moveCompleteApp = false;
20824            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20825        } else {
20826            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20827            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20828                    || !volume.isMountedWritable()) {
20829                freezer.close();
20830                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20831                        "Move location not mounted private volume");
20832            }
20833
20834            Preconditions.checkState(!currentAsec);
20835
20836            installFlags = INSTALL_INTERNAL;
20837            moveCompleteApp = true;
20838            measurePath = Environment.getDataAppDirectory(volumeUuid);
20839        }
20840
20841        final PackageStats stats = new PackageStats(null, -1);
20842        synchronized (mInstaller) {
20843            for (int userId : installedUserIds) {
20844                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20845                    freezer.close();
20846                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20847                            "Failed to measure package size");
20848                }
20849            }
20850        }
20851
20852        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20853                + stats.dataSize);
20854
20855        final long startFreeBytes = measurePath.getFreeSpace();
20856        final long sizeBytes;
20857        if (moveCompleteApp) {
20858            sizeBytes = stats.codeSize + stats.dataSize;
20859        } else {
20860            sizeBytes = stats.codeSize;
20861        }
20862
20863        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20864            freezer.close();
20865            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20866                    "Not enough free space to move");
20867        }
20868
20869        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20870
20871        final CountDownLatch installedLatch = new CountDownLatch(1);
20872        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20873            @Override
20874            public void onUserActionRequired(Intent intent) throws RemoteException {
20875                throw new IllegalStateException();
20876            }
20877
20878            @Override
20879            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20880                    Bundle extras) throws RemoteException {
20881                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20882                        + PackageManager.installStatusToString(returnCode, msg));
20883
20884                installedLatch.countDown();
20885                freezer.close();
20886
20887                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20888                switch (status) {
20889                    case PackageInstaller.STATUS_SUCCESS:
20890                        mMoveCallbacks.notifyStatusChanged(moveId,
20891                                PackageManager.MOVE_SUCCEEDED);
20892                        break;
20893                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20894                        mMoveCallbacks.notifyStatusChanged(moveId,
20895                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20896                        break;
20897                    default:
20898                        mMoveCallbacks.notifyStatusChanged(moveId,
20899                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20900                        break;
20901                }
20902            }
20903        };
20904
20905        final MoveInfo move;
20906        if (moveCompleteApp) {
20907            // Kick off a thread to report progress estimates
20908            new Thread() {
20909                @Override
20910                public void run() {
20911                    while (true) {
20912                        try {
20913                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20914                                break;
20915                            }
20916                        } catch (InterruptedException ignored) {
20917                        }
20918
20919                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20920                        final int progress = 10 + (int) MathUtils.constrain(
20921                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20922                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20923                    }
20924                }
20925            }.start();
20926
20927            final String dataAppName = codeFile.getName();
20928            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20929                    dataAppName, appId, seinfo, targetSdkVersion);
20930        } else {
20931            move = null;
20932        }
20933
20934        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20935
20936        final Message msg = mHandler.obtainMessage(INIT_COPY);
20937        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20938        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20939                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20940                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20941        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20942        msg.obj = params;
20943
20944        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20945                System.identityHashCode(msg.obj));
20946        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20947                System.identityHashCode(msg.obj));
20948
20949        mHandler.sendMessage(msg);
20950    }
20951
20952    @Override
20953    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20954        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20955
20956        final int realMoveId = mNextMoveId.getAndIncrement();
20957        final Bundle extras = new Bundle();
20958        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20959        mMoveCallbacks.notifyCreated(realMoveId, extras);
20960
20961        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20962            @Override
20963            public void onCreated(int moveId, Bundle extras) {
20964                // Ignored
20965            }
20966
20967            @Override
20968            public void onStatusChanged(int moveId, int status, long estMillis) {
20969                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20970            }
20971        };
20972
20973        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20974        storage.setPrimaryStorageUuid(volumeUuid, callback);
20975        return realMoveId;
20976    }
20977
20978    @Override
20979    public int getMoveStatus(int moveId) {
20980        mContext.enforceCallingOrSelfPermission(
20981                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20982        return mMoveCallbacks.mLastStatus.get(moveId);
20983    }
20984
20985    @Override
20986    public void registerMoveCallback(IPackageMoveObserver callback) {
20987        mContext.enforceCallingOrSelfPermission(
20988                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20989        mMoveCallbacks.register(callback);
20990    }
20991
20992    @Override
20993    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20994        mContext.enforceCallingOrSelfPermission(
20995                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20996        mMoveCallbacks.unregister(callback);
20997    }
20998
20999    @Override
21000    public boolean setInstallLocation(int loc) {
21001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21002                null);
21003        if (getInstallLocation() == loc) {
21004            return true;
21005        }
21006        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21007                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21008            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21009                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21010            return true;
21011        }
21012        return false;
21013   }
21014
21015    @Override
21016    public int getInstallLocation() {
21017        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21018                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21019                PackageHelper.APP_INSTALL_AUTO);
21020    }
21021
21022    /** Called by UserManagerService */
21023    void cleanUpUser(UserManagerService userManager, int userHandle) {
21024        synchronized (mPackages) {
21025            mDirtyUsers.remove(userHandle);
21026            mUserNeedsBadging.delete(userHandle);
21027            mSettings.removeUserLPw(userHandle);
21028            mPendingBroadcasts.remove(userHandle);
21029            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21030            removeUnusedPackagesLPw(userManager, userHandle);
21031        }
21032    }
21033
21034    /**
21035     * We're removing userHandle and would like to remove any downloaded packages
21036     * that are no longer in use by any other user.
21037     * @param userHandle the user being removed
21038     */
21039    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21040        final boolean DEBUG_CLEAN_APKS = false;
21041        int [] users = userManager.getUserIds();
21042        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21043        while (psit.hasNext()) {
21044            PackageSetting ps = psit.next();
21045            if (ps.pkg == null) {
21046                continue;
21047            }
21048            final String packageName = ps.pkg.packageName;
21049            // Skip over if system app
21050            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21051                continue;
21052            }
21053            if (DEBUG_CLEAN_APKS) {
21054                Slog.i(TAG, "Checking package " + packageName);
21055            }
21056            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21057            if (keep) {
21058                if (DEBUG_CLEAN_APKS) {
21059                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21060                }
21061            } else {
21062                for (int i = 0; i < users.length; i++) {
21063                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21064                        keep = true;
21065                        if (DEBUG_CLEAN_APKS) {
21066                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21067                                    + users[i]);
21068                        }
21069                        break;
21070                    }
21071                }
21072            }
21073            if (!keep) {
21074                if (DEBUG_CLEAN_APKS) {
21075                    Slog.i(TAG, "  Removing package " + packageName);
21076                }
21077                mHandler.post(new Runnable() {
21078                    public void run() {
21079                        deletePackageX(packageName, userHandle, 0);
21080                    } //end run
21081                });
21082            }
21083        }
21084    }
21085
21086    /** Called by UserManagerService */
21087    void createNewUser(int userId, String[] disallowedPackages) {
21088        synchronized (mInstallLock) {
21089            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21090        }
21091        synchronized (mPackages) {
21092            scheduleWritePackageRestrictionsLocked(userId);
21093            scheduleWritePackageListLocked(userId);
21094            applyFactoryDefaultBrowserLPw(userId);
21095            primeDomainVerificationsLPw(userId);
21096        }
21097    }
21098
21099    void onNewUserCreated(final int userId) {
21100        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21101        // If permission review for legacy apps is required, we represent
21102        // dagerous permissions for such apps as always granted runtime
21103        // permissions to keep per user flag state whether review is needed.
21104        // Hence, if a new user is added we have to propagate dangerous
21105        // permission grants for these legacy apps.
21106        if (mPermissionReviewRequired) {
21107            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21108                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21109        }
21110    }
21111
21112    @Override
21113    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21114        mContext.enforceCallingOrSelfPermission(
21115                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21116                "Only package verification agents can read the verifier device identity");
21117
21118        synchronized (mPackages) {
21119            return mSettings.getVerifierDeviceIdentityLPw();
21120        }
21121    }
21122
21123    @Override
21124    public void setPermissionEnforced(String permission, boolean enforced) {
21125        // TODO: Now that we no longer change GID for storage, this should to away.
21126        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21127                "setPermissionEnforced");
21128        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21129            synchronized (mPackages) {
21130                if (mSettings.mReadExternalStorageEnforced == null
21131                        || mSettings.mReadExternalStorageEnforced != enforced) {
21132                    mSettings.mReadExternalStorageEnforced = enforced;
21133                    mSettings.writeLPr();
21134                }
21135            }
21136            // kill any non-foreground processes so we restart them and
21137            // grant/revoke the GID.
21138            final IActivityManager am = ActivityManager.getService();
21139            if (am != null) {
21140                final long token = Binder.clearCallingIdentity();
21141                try {
21142                    am.killProcessesBelowForeground("setPermissionEnforcement");
21143                } catch (RemoteException e) {
21144                } finally {
21145                    Binder.restoreCallingIdentity(token);
21146                }
21147            }
21148        } else {
21149            throw new IllegalArgumentException("No selective enforcement for " + permission);
21150        }
21151    }
21152
21153    @Override
21154    @Deprecated
21155    public boolean isPermissionEnforced(String permission) {
21156        return true;
21157    }
21158
21159    @Override
21160    public boolean isStorageLow() {
21161        final long token = Binder.clearCallingIdentity();
21162        try {
21163            final DeviceStorageMonitorInternal
21164                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21165            if (dsm != null) {
21166                return dsm.isMemoryLow();
21167            } else {
21168                return false;
21169            }
21170        } finally {
21171            Binder.restoreCallingIdentity(token);
21172        }
21173    }
21174
21175    @Override
21176    public IPackageInstaller getPackageInstaller() {
21177        return mInstallerService;
21178    }
21179
21180    private boolean userNeedsBadging(int userId) {
21181        int index = mUserNeedsBadging.indexOfKey(userId);
21182        if (index < 0) {
21183            final UserInfo userInfo;
21184            final long token = Binder.clearCallingIdentity();
21185            try {
21186                userInfo = sUserManager.getUserInfo(userId);
21187            } finally {
21188                Binder.restoreCallingIdentity(token);
21189            }
21190            final boolean b;
21191            if (userInfo != null && userInfo.isManagedProfile()) {
21192                b = true;
21193            } else {
21194                b = false;
21195            }
21196            mUserNeedsBadging.put(userId, b);
21197            return b;
21198        }
21199        return mUserNeedsBadging.valueAt(index);
21200    }
21201
21202    @Override
21203    public KeySet getKeySetByAlias(String packageName, String alias) {
21204        if (packageName == null || alias == null) {
21205            return null;
21206        }
21207        synchronized(mPackages) {
21208            final PackageParser.Package pkg = mPackages.get(packageName);
21209            if (pkg == null) {
21210                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21211                throw new IllegalArgumentException("Unknown package: " + packageName);
21212            }
21213            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21214            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21215        }
21216    }
21217
21218    @Override
21219    public KeySet getSigningKeySet(String packageName) {
21220        if (packageName == null) {
21221            return null;
21222        }
21223        synchronized(mPackages) {
21224            final PackageParser.Package pkg = mPackages.get(packageName);
21225            if (pkg == null) {
21226                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21227                throw new IllegalArgumentException("Unknown package: " + packageName);
21228            }
21229            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21230                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21231                throw new SecurityException("May not access signing KeySet of other apps.");
21232            }
21233            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21234            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21235        }
21236    }
21237
21238    @Override
21239    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21240        if (packageName == null || ks == null) {
21241            return false;
21242        }
21243        synchronized(mPackages) {
21244            final PackageParser.Package pkg = mPackages.get(packageName);
21245            if (pkg == null) {
21246                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21247                throw new IllegalArgumentException("Unknown package: " + packageName);
21248            }
21249            IBinder ksh = ks.getToken();
21250            if (ksh instanceof KeySetHandle) {
21251                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21252                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21253            }
21254            return false;
21255        }
21256    }
21257
21258    @Override
21259    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21260        if (packageName == null || ks == null) {
21261            return false;
21262        }
21263        synchronized(mPackages) {
21264            final PackageParser.Package pkg = mPackages.get(packageName);
21265            if (pkg == null) {
21266                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21267                throw new IllegalArgumentException("Unknown package: " + packageName);
21268            }
21269            IBinder ksh = ks.getToken();
21270            if (ksh instanceof KeySetHandle) {
21271                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21272                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21273            }
21274            return false;
21275        }
21276    }
21277
21278    private void deletePackageIfUnusedLPr(final String packageName) {
21279        PackageSetting ps = mSettings.mPackages.get(packageName);
21280        if (ps == null) {
21281            return;
21282        }
21283        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21284            // TODO Implement atomic delete if package is unused
21285            // It is currently possible that the package will be deleted even if it is installed
21286            // after this method returns.
21287            mHandler.post(new Runnable() {
21288                public void run() {
21289                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21290                }
21291            });
21292        }
21293    }
21294
21295    /**
21296     * Check and throw if the given before/after packages would be considered a
21297     * downgrade.
21298     */
21299    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21300            throws PackageManagerException {
21301        if (after.versionCode < before.mVersionCode) {
21302            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21303                    "Update version code " + after.versionCode + " is older than current "
21304                    + before.mVersionCode);
21305        } else if (after.versionCode == before.mVersionCode) {
21306            if (after.baseRevisionCode < before.baseRevisionCode) {
21307                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21308                        "Update base revision code " + after.baseRevisionCode
21309                        + " is older than current " + before.baseRevisionCode);
21310            }
21311
21312            if (!ArrayUtils.isEmpty(after.splitNames)) {
21313                for (int i = 0; i < after.splitNames.length; i++) {
21314                    final String splitName = after.splitNames[i];
21315                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21316                    if (j != -1) {
21317                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21318                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21319                                    "Update split " + splitName + " revision code "
21320                                    + after.splitRevisionCodes[i] + " is older than current "
21321                                    + before.splitRevisionCodes[j]);
21322                        }
21323                    }
21324                }
21325            }
21326        }
21327    }
21328
21329    private static class MoveCallbacks extends Handler {
21330        private static final int MSG_CREATED = 1;
21331        private static final int MSG_STATUS_CHANGED = 2;
21332
21333        private final RemoteCallbackList<IPackageMoveObserver>
21334                mCallbacks = new RemoteCallbackList<>();
21335
21336        private final SparseIntArray mLastStatus = new SparseIntArray();
21337
21338        public MoveCallbacks(Looper looper) {
21339            super(looper);
21340        }
21341
21342        public void register(IPackageMoveObserver callback) {
21343            mCallbacks.register(callback);
21344        }
21345
21346        public void unregister(IPackageMoveObserver callback) {
21347            mCallbacks.unregister(callback);
21348        }
21349
21350        @Override
21351        public void handleMessage(Message msg) {
21352            final SomeArgs args = (SomeArgs) msg.obj;
21353            final int n = mCallbacks.beginBroadcast();
21354            for (int i = 0; i < n; i++) {
21355                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21356                try {
21357                    invokeCallback(callback, msg.what, args);
21358                } catch (RemoteException ignored) {
21359                }
21360            }
21361            mCallbacks.finishBroadcast();
21362            args.recycle();
21363        }
21364
21365        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21366                throws RemoteException {
21367            switch (what) {
21368                case MSG_CREATED: {
21369                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21370                    break;
21371                }
21372                case MSG_STATUS_CHANGED: {
21373                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21374                    break;
21375                }
21376            }
21377        }
21378
21379        private void notifyCreated(int moveId, Bundle extras) {
21380            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21381
21382            final SomeArgs args = SomeArgs.obtain();
21383            args.argi1 = moveId;
21384            args.arg2 = extras;
21385            obtainMessage(MSG_CREATED, args).sendToTarget();
21386        }
21387
21388        private void notifyStatusChanged(int moveId, int status) {
21389            notifyStatusChanged(moveId, status, -1);
21390        }
21391
21392        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21393            Slog.v(TAG, "Move " + moveId + " status " + status);
21394
21395            final SomeArgs args = SomeArgs.obtain();
21396            args.argi1 = moveId;
21397            args.argi2 = status;
21398            args.arg3 = estMillis;
21399            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21400
21401            synchronized (mLastStatus) {
21402                mLastStatus.put(moveId, status);
21403            }
21404        }
21405    }
21406
21407    private final static class OnPermissionChangeListeners extends Handler {
21408        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21409
21410        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21411                new RemoteCallbackList<>();
21412
21413        public OnPermissionChangeListeners(Looper looper) {
21414            super(looper);
21415        }
21416
21417        @Override
21418        public void handleMessage(Message msg) {
21419            switch (msg.what) {
21420                case MSG_ON_PERMISSIONS_CHANGED: {
21421                    final int uid = msg.arg1;
21422                    handleOnPermissionsChanged(uid);
21423                } break;
21424            }
21425        }
21426
21427        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21428            mPermissionListeners.register(listener);
21429
21430        }
21431
21432        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21433            mPermissionListeners.unregister(listener);
21434        }
21435
21436        public void onPermissionsChanged(int uid) {
21437            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21438                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21439            }
21440        }
21441
21442        private void handleOnPermissionsChanged(int uid) {
21443            final int count = mPermissionListeners.beginBroadcast();
21444            try {
21445                for (int i = 0; i < count; i++) {
21446                    IOnPermissionsChangeListener callback = mPermissionListeners
21447                            .getBroadcastItem(i);
21448                    try {
21449                        callback.onPermissionsChanged(uid);
21450                    } catch (RemoteException e) {
21451                        Log.e(TAG, "Permission listener is dead", e);
21452                    }
21453                }
21454            } finally {
21455                mPermissionListeners.finishBroadcast();
21456            }
21457        }
21458    }
21459
21460    private class PackageManagerInternalImpl extends PackageManagerInternal {
21461        @Override
21462        public void setLocationPackagesProvider(PackagesProvider provider) {
21463            synchronized (mPackages) {
21464                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21465            }
21466        }
21467
21468        @Override
21469        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21470            synchronized (mPackages) {
21471                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21472            }
21473        }
21474
21475        @Override
21476        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21477            synchronized (mPackages) {
21478                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21479            }
21480        }
21481
21482        @Override
21483        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21484            synchronized (mPackages) {
21485                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21486            }
21487        }
21488
21489        @Override
21490        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21491            synchronized (mPackages) {
21492                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21493            }
21494        }
21495
21496        @Override
21497        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21498            synchronized (mPackages) {
21499                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21500            }
21501        }
21502
21503        @Override
21504        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21505            synchronized (mPackages) {
21506                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21507                        packageName, userId);
21508            }
21509        }
21510
21511        @Override
21512        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21513            synchronized (mPackages) {
21514                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21515                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21516                        packageName, userId);
21517            }
21518        }
21519
21520        @Override
21521        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21522            synchronized (mPackages) {
21523                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21524                        packageName, userId);
21525            }
21526        }
21527
21528        @Override
21529        public void setKeepUninstalledPackages(final List<String> packageList) {
21530            Preconditions.checkNotNull(packageList);
21531            List<String> removedFromList = null;
21532            synchronized (mPackages) {
21533                if (mKeepUninstalledPackages != null) {
21534                    final int packagesCount = mKeepUninstalledPackages.size();
21535                    for (int i = 0; i < packagesCount; i++) {
21536                        String oldPackage = mKeepUninstalledPackages.get(i);
21537                        if (packageList != null && packageList.contains(oldPackage)) {
21538                            continue;
21539                        }
21540                        if (removedFromList == null) {
21541                            removedFromList = new ArrayList<>();
21542                        }
21543                        removedFromList.add(oldPackage);
21544                    }
21545                }
21546                mKeepUninstalledPackages = new ArrayList<>(packageList);
21547                if (removedFromList != null) {
21548                    final int removedCount = removedFromList.size();
21549                    for (int i = 0; i < removedCount; i++) {
21550                        deletePackageIfUnusedLPr(removedFromList.get(i));
21551                    }
21552                }
21553            }
21554        }
21555
21556        @Override
21557        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21558            synchronized (mPackages) {
21559                // If we do not support permission review, done.
21560                if (!mPermissionReviewRequired) {
21561                    return false;
21562                }
21563
21564                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21565                if (packageSetting == null) {
21566                    return false;
21567                }
21568
21569                // Permission review applies only to apps not supporting the new permission model.
21570                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21571                    return false;
21572                }
21573
21574                // Legacy apps have the permission and get user consent on launch.
21575                PermissionsState permissionsState = packageSetting.getPermissionsState();
21576                return permissionsState.isPermissionReviewRequired(userId);
21577            }
21578        }
21579
21580        @Override
21581        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21582            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21583        }
21584
21585        @Override
21586        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21587                int userId) {
21588            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21589        }
21590
21591        @Override
21592        public void setDeviceAndProfileOwnerPackages(
21593                int deviceOwnerUserId, String deviceOwnerPackage,
21594                SparseArray<String> profileOwnerPackages) {
21595            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21596                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21597        }
21598
21599        @Override
21600        public boolean isPackageDataProtected(int userId, String packageName) {
21601            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21602        }
21603
21604        @Override
21605        public boolean isPackageEphemeral(int userId, String packageName) {
21606            synchronized (mPackages) {
21607                PackageParser.Package p = mPackages.get(packageName);
21608                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21609            }
21610        }
21611
21612        @Override
21613        public boolean wasPackageEverLaunched(String packageName, int userId) {
21614            synchronized (mPackages) {
21615                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21616            }
21617        }
21618
21619        @Override
21620        public void grantRuntimePermission(String packageName, String name, int userId,
21621                boolean overridePolicy) {
21622            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21623                    overridePolicy);
21624        }
21625
21626        @Override
21627        public void revokeRuntimePermission(String packageName, String name, int userId,
21628                boolean overridePolicy) {
21629            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21630                    overridePolicy);
21631        }
21632
21633        @Override
21634        public String getNameForUid(int uid) {
21635            return PackageManagerService.this.getNameForUid(uid);
21636        }
21637
21638        @Override
21639        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21640                Intent origIntent, String resolvedType, Intent launchIntent,
21641                String callingPackage, int userId) {
21642            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21643                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21644        }
21645    }
21646
21647    @Override
21648    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21649        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21650        synchronized (mPackages) {
21651            final long identity = Binder.clearCallingIdentity();
21652            try {
21653                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21654                        packageNames, userId);
21655            } finally {
21656                Binder.restoreCallingIdentity(identity);
21657            }
21658        }
21659    }
21660
21661    private static void enforceSystemOrPhoneCaller(String tag) {
21662        int callingUid = Binder.getCallingUid();
21663        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21664            throw new SecurityException(
21665                    "Cannot call " + tag + " from UID " + callingUid);
21666        }
21667    }
21668
21669    boolean isHistoricalPackageUsageAvailable() {
21670        return mPackageUsage.isHistoricalPackageUsageAvailable();
21671    }
21672
21673    /**
21674     * Return a <b>copy</b> of the collection of packages known to the package manager.
21675     * @return A copy of the values of mPackages.
21676     */
21677    Collection<PackageParser.Package> getPackages() {
21678        synchronized (mPackages) {
21679            return new ArrayList<>(mPackages.values());
21680        }
21681    }
21682
21683    /**
21684     * Logs process start information (including base APK hash) to the security log.
21685     * @hide
21686     */
21687    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21688            String apkFile, int pid) {
21689        if (!SecurityLog.isLoggingEnabled()) {
21690            return;
21691        }
21692        Bundle data = new Bundle();
21693        data.putLong("startTimestamp", System.currentTimeMillis());
21694        data.putString("processName", processName);
21695        data.putInt("uid", uid);
21696        data.putString("seinfo", seinfo);
21697        data.putString("apkFile", apkFile);
21698        data.putInt("pid", pid);
21699        Message msg = mProcessLoggingHandler.obtainMessage(
21700                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21701        msg.setData(data);
21702        mProcessLoggingHandler.sendMessage(msg);
21703    }
21704
21705    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21706        return mCompilerStats.getPackageStats(pkgName);
21707    }
21708
21709    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21710        return getOrCreateCompilerPackageStats(pkg.packageName);
21711    }
21712
21713    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21714        return mCompilerStats.getOrCreatePackageStats(pkgName);
21715    }
21716
21717    public void deleteCompilerPackageStats(String pkgName) {
21718        mCompilerStats.deletePackageStats(pkgName);
21719    }
21720}
21721