PackageManagerService.java revision 2646571a0ef94401938f067de909d9811594df3a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_ANY_USER;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
76import static android.content.pm.PackageManager.PERMISSION_DENIED;
77import static android.content.pm.PackageManager.PERMISSION_GRANTED;
78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
79import static android.content.pm.PackageParser.isApkFile;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.AppOpsManager;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.ContentResolver;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralRequest;
128import android.content.pm.EphemeralResolveInfo;
129import android.content.pm.EphemeralResponse;
130import android.content.pm.FallbackCategoryProvider;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstrumentationInfo;
142import android.content.pm.IntentFilterVerificationInfo;
143import android.content.pm.KeySet;
144import android.content.pm.PackageCleanItem;
145import android.content.pm.PackageInfo;
146import android.content.pm.PackageInfoLite;
147import android.content.pm.PackageInstaller;
148import android.content.pm.PackageManager;
149import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
150import android.content.pm.PackageManagerInternal;
151import android.content.pm.PackageParser;
152import android.content.pm.PackageParser.ActivityIntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.PatternMatcher;
185import android.os.Process;
186import android.os.RemoteCallbackList;
187import android.os.RemoteException;
188import android.os.ResultReceiver;
189import android.os.SELinux;
190import android.os.ServiceManager;
191import android.os.ShellCallback;
192import android.os.SystemClock;
193import android.os.SystemProperties;
194import android.os.Trace;
195import android.os.UserHandle;
196import android.os.UserManager;
197import android.os.UserManagerInternal;
198import android.os.storage.IStorageManager;
199import android.os.storage.StorageManagerInternal;
200import android.os.storage.StorageEventListener;
201import android.os.storage.StorageManager;
202import android.os.storage.VolumeInfo;
203import android.os.storage.VolumeRecord;
204import android.provider.Settings.Global;
205import android.provider.Settings.Secure;
206import android.security.KeyStore;
207import android.security.SystemKeyStore;
208import android.system.ErrnoException;
209import android.system.Os;
210import android.text.TextUtils;
211import android.text.format.DateUtils;
212import android.util.ArrayMap;
213import android.util.ArraySet;
214import android.util.Base64;
215import android.util.DisplayMetrics;
216import android.util.EventLog;
217import android.util.ExceptionUtils;
218import android.util.Log;
219import android.util.LogPrinter;
220import android.util.MathUtils;
221import android.util.Pair;
222import android.util.PrintStreamPrinter;
223import android.util.Slog;
224import android.util.SparseArray;
225import android.util.SparseBooleanArray;
226import android.util.SparseIntArray;
227import android.util.Xml;
228import android.util.jar.StrictJarFile;
229import android.view.Display;
230
231import com.android.internal.R;
232import com.android.internal.annotations.GuardedBy;
233import com.android.internal.app.IMediaContainerService;
234import com.android.internal.app.ResolverActivity;
235import com.android.internal.content.NativeLibraryHelper;
236import com.android.internal.content.PackageHelper;
237import com.android.internal.logging.MetricsLogger;
238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
239import com.android.internal.os.IParcelFileDescriptorFactory;
240import com.android.internal.os.RoSystemProperties;
241import com.android.internal.os.SomeArgs;
242import com.android.internal.os.Zygote;
243import com.android.internal.telephony.CarrierAppUtils;
244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
246import com.android.internal.util.FastXmlSerializer;
247import com.android.internal.util.IndentingPrintWriter;
248import com.android.internal.util.Preconditions;
249import com.android.internal.util.XmlUtils;
250import com.android.server.AttributeCache;
251import com.android.server.EventLogTags;
252import com.android.server.FgThread;
253import com.android.server.IntentResolver;
254import com.android.server.LocalServices;
255import com.android.server.ServiceThread;
256import com.android.server.SystemConfig;
257import com.android.server.Watchdog;
258import com.android.server.net.NetworkPolicyManagerInternal;
259import com.android.server.pm.Installer.InstallerException;
260import com.android.server.pm.PermissionsState.PermissionState;
261import com.android.server.pm.Settings.DatabaseVersion;
262import com.android.server.pm.Settings.VersionInfo;
263import com.android.server.pm.dex.DexManager;
264import com.android.server.storage.DeviceStorageMonitorInternal;
265
266import dalvik.system.CloseGuard;
267import dalvik.system.DexFile;
268import dalvik.system.VMRuntime;
269
270import libcore.io.IoUtils;
271import libcore.util.EmptyArray;
272
273import org.xmlpull.v1.XmlPullParser;
274import org.xmlpull.v1.XmlPullParserException;
275import org.xmlpull.v1.XmlSerializer;
276
277import java.io.BufferedOutputStream;
278import java.io.BufferedReader;
279import java.io.ByteArrayInputStream;
280import java.io.ByteArrayOutputStream;
281import java.io.File;
282import java.io.FileDescriptor;
283import java.io.FileInputStream;
284import java.io.FileNotFoundException;
285import java.io.FileOutputStream;
286import java.io.FileReader;
287import java.io.FilenameFilter;
288import java.io.IOException;
289import java.io.PrintWriter;
290import java.nio.charset.StandardCharsets;
291import java.security.DigestInputStream;
292import java.security.MessageDigest;
293import java.security.NoSuchAlgorithmException;
294import java.security.PublicKey;
295import java.security.SecureRandom;
296import java.security.cert.Certificate;
297import java.security.cert.CertificateEncodingException;
298import java.security.cert.CertificateException;
299import java.text.SimpleDateFormat;
300import java.util.ArrayList;
301import java.util.Arrays;
302import java.util.Collection;
303import java.util.Collections;
304import java.util.Comparator;
305import java.util.Date;
306import java.util.HashSet;
307import java.util.HashMap;
308import java.util.Iterator;
309import java.util.List;
310import java.util.Map;
311import java.util.Objects;
312import java.util.Set;
313import java.util.concurrent.CountDownLatch;
314import java.util.concurrent.TimeUnit;
315import java.util.concurrent.atomic.AtomicBoolean;
316import java.util.concurrent.atomic.AtomicInteger;
317
318/**
319 * Keep track of all those APKs everywhere.
320 * <p>
321 * Internally there are two important locks:
322 * <ul>
323 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
324 * and other related state. It is a fine-grained lock that should only be held
325 * momentarily, as it's one of the most contended locks in the system.
326 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
327 * operations typically involve heavy lifting of application data on disk. Since
328 * {@code installd} is single-threaded, and it's operations can often be slow,
329 * this lock should never be acquired while already holding {@link #mPackages}.
330 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
331 * holding {@link #mInstallLock}.
332 * </ul>
333 * Many internal methods rely on the caller to hold the appropriate locks, and
334 * this contract is expressed through method name suffixes:
335 * <ul>
336 * <li>fooLI(): the caller must hold {@link #mInstallLock}
337 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
338 * being modified must be frozen
339 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
340 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
341 * </ul>
342 * <p>
343 * Because this class is very central to the platform's security; please run all
344 * CTS and unit tests whenever making modifications:
345 *
346 * <pre>
347 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
348 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
349 * </pre>
350 */
351public class PackageManagerService extends IPackageManager.Stub {
352    static final String TAG = "PackageManager";
353    static final boolean DEBUG_SETTINGS = false;
354    static final boolean DEBUG_PREFERRED = false;
355    static final boolean DEBUG_UPGRADE = false;
356    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
357    private static final boolean DEBUG_BACKUP = false;
358    private static final boolean DEBUG_INSTALL = false;
359    private static final boolean DEBUG_REMOVE = false;
360    private static final boolean DEBUG_BROADCASTS = false;
361    private static final boolean DEBUG_SHOW_INFO = false;
362    private static final boolean DEBUG_PACKAGE_INFO = false;
363    private static final boolean DEBUG_INTENT_MATCHING = false;
364    private static final boolean DEBUG_PACKAGE_SCANNING = false;
365    private static final boolean DEBUG_VERIFY = false;
366    private static final boolean DEBUG_FILTERS = false;
367
368    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
369    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
370    // user, but by default initialize to this.
371    static final boolean DEBUG_DEXOPT = false;
372
373    private static final boolean DEBUG_ABI_SELECTION = false;
374    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
375    private static final boolean DEBUG_TRIAGED_MISSING = false;
376    private static final boolean DEBUG_APP_DATA = false;
377
378    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
379    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
380
381    private static final boolean DISABLE_EPHEMERAL_APPS = false;
382    private static final boolean HIDE_EPHEMERAL_APIS = true;
383
384    private static final boolean ENABLE_QUOTA =
385            SystemProperties.getBoolean("persist.fw.quota", false);
386
387    private static final int RADIO_UID = Process.PHONE_UID;
388    private static final int LOG_UID = Process.LOG_UID;
389    private static final int NFC_UID = Process.NFC_UID;
390    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
391    private static final int SHELL_UID = Process.SHELL_UID;
392
393    // Cap the size of permission trees that 3rd party apps can define
394    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
395
396    // Suffix used during package installation when copying/moving
397    // package apks to install directory.
398    private static final String INSTALL_PACKAGE_SUFFIX = "-";
399
400    static final int SCAN_NO_DEX = 1<<1;
401    static final int SCAN_FORCE_DEX = 1<<2;
402    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
403    static final int SCAN_NEW_INSTALL = 1<<4;
404    static final int SCAN_UPDATE_TIME = 1<<5;
405    static final int SCAN_BOOTING = 1<<6;
406    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
407    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
408    static final int SCAN_REPLACING = 1<<9;
409    static final int SCAN_REQUIRE_KNOWN = 1<<10;
410    static final int SCAN_MOVE = 1<<11;
411    static final int SCAN_INITIAL = 1<<12;
412    static final int SCAN_CHECK_ONLY = 1<<13;
413    static final int SCAN_DONT_KILL_APP = 1<<14;
414    static final int SCAN_IGNORE_FROZEN = 1<<15;
415    static final int REMOVE_CHATTY = 1<<16;
416    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
417
418    private static final int[] EMPTY_INT_ARRAY = new int[0];
419
420    /**
421     * Timeout (in milliseconds) after which the watchdog should declare that
422     * our handler thread is wedged.  The usual default for such things is one
423     * minute but we sometimes do very lengthy I/O operations on this thread,
424     * such as installing multi-gigabyte applications, so ours needs to be longer.
425     */
426    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
427
428    /**
429     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
430     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
431     * settings entry if available, otherwise we use the hardcoded default.  If it's been
432     * more than this long since the last fstrim, we force one during the boot sequence.
433     *
434     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
435     * one gets run at the next available charging+idle time.  This final mandatory
436     * no-fstrim check kicks in only of the other scheduling criteria is never met.
437     */
438    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
439
440    /**
441     * Whether verification is enabled by default.
442     */
443    private static final boolean DEFAULT_VERIFY_ENABLE = true;
444
445    /**
446     * The default maximum time to wait for the verification agent to return in
447     * milliseconds.
448     */
449    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
450
451    /**
452     * The default response for package verification timeout.
453     *
454     * This can be either PackageManager.VERIFICATION_ALLOW or
455     * PackageManager.VERIFICATION_REJECT.
456     */
457    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
458
459    static final String PLATFORM_PACKAGE_NAME = "android";
460
461    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
462
463    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
464            DEFAULT_CONTAINER_PACKAGE,
465            "com.android.defcontainer.DefaultContainerService");
466
467    private static final String KILL_APP_REASON_GIDS_CHANGED =
468            "permission grant or revoke changed gids";
469
470    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
471            "permissions revoked";
472
473    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
474
475    private static final String PACKAGE_SCHEME = "package";
476
477    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
478    /**
479     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
480     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
481     * VENDOR_OVERLAY_DIR.
482     */
483    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
484    /**
485     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
486     * is in VENDOR_OVERLAY_THEME_PROPERTY.
487     */
488    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
489            = "persist.vendor.overlay.theme";
490
491    /** Permission grant: not grant the permission. */
492    private static final int GRANT_DENIED = 1;
493
494    /** Permission grant: grant the permission as an install permission. */
495    private static final int GRANT_INSTALL = 2;
496
497    /** Permission grant: grant the permission as a runtime one. */
498    private static final int GRANT_RUNTIME = 3;
499
500    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
501    private static final int GRANT_UPGRADE = 4;
502
503    /** Canonical intent used to identify what counts as a "web browser" app */
504    private static final Intent sBrowserIntent;
505    static {
506        sBrowserIntent = new Intent();
507        sBrowserIntent.setAction(Intent.ACTION_VIEW);
508        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
509        sBrowserIntent.setData(Uri.parse("http:"));
510    }
511
512    /**
513     * The set of all protected actions [i.e. those actions for which a high priority
514     * intent filter is disallowed].
515     */
516    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
517    static {
518        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
519        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
520        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
521        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
522    }
523
524    // Compilation reasons.
525    public static final int REASON_FIRST_BOOT = 0;
526    public static final int REASON_BOOT = 1;
527    public static final int REASON_INSTALL = 2;
528    public static final int REASON_BACKGROUND_DEXOPT = 3;
529    public static final int REASON_AB_OTA = 4;
530    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
531    public static final int REASON_SHARED_APK = 6;
532    public static final int REASON_FORCED_DEXOPT = 7;
533    public static final int REASON_CORE_APP = 8;
534
535    public static final int REASON_LAST = REASON_CORE_APP;
536
537    /** Special library name that skips shared libraries check during compilation. */
538    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
539
540    /** All dangerous permission names in the same order as the events in MetricsEvent */
541    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
542            Manifest.permission.READ_CALENDAR,
543            Manifest.permission.WRITE_CALENDAR,
544            Manifest.permission.CAMERA,
545            Manifest.permission.READ_CONTACTS,
546            Manifest.permission.WRITE_CONTACTS,
547            Manifest.permission.GET_ACCOUNTS,
548            Manifest.permission.ACCESS_FINE_LOCATION,
549            Manifest.permission.ACCESS_COARSE_LOCATION,
550            Manifest.permission.RECORD_AUDIO,
551            Manifest.permission.READ_PHONE_STATE,
552            Manifest.permission.CALL_PHONE,
553            Manifest.permission.READ_CALL_LOG,
554            Manifest.permission.WRITE_CALL_LOG,
555            Manifest.permission.ADD_VOICEMAIL,
556            Manifest.permission.USE_SIP,
557            Manifest.permission.PROCESS_OUTGOING_CALLS,
558            Manifest.permission.READ_CELL_BROADCASTS,
559            Manifest.permission.BODY_SENSORS,
560            Manifest.permission.SEND_SMS,
561            Manifest.permission.RECEIVE_SMS,
562            Manifest.permission.READ_SMS,
563            Manifest.permission.RECEIVE_WAP_PUSH,
564            Manifest.permission.RECEIVE_MMS,
565            Manifest.permission.READ_EXTERNAL_STORAGE,
566            Manifest.permission.WRITE_EXTERNAL_STORAGE,
567            Manifest.permission.READ_PHONE_NUMBER);
568
569
570    /**
571     * Version number for the package parser cache. Increment this whenever the format or
572     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
573     */
574    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
575
576    /**
577     * Whether the package parser cache is enabled.
578     */
579    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
580
581    final ServiceThread mHandlerThread;
582
583    final PackageHandler mHandler;
584
585    private final ProcessLoggingHandler mProcessLoggingHandler;
586
587    /**
588     * Messages for {@link #mHandler} that need to wait for system ready before
589     * being dispatched.
590     */
591    private ArrayList<Message> mPostSystemReadyMessages;
592
593    final int mSdkVersion = Build.VERSION.SDK_INT;
594
595    final Context mContext;
596    final boolean mFactoryTest;
597    final boolean mOnlyCore;
598    final DisplayMetrics mMetrics;
599    final int mDefParseFlags;
600    final String[] mSeparateProcesses;
601    final boolean mIsUpgrade;
602    final boolean mIsPreNUpgrade;
603    final boolean mIsPreNMR1Upgrade;
604
605    @GuardedBy("mPackages")
606    private boolean mDexOptDialogShown;
607
608    /** The location for ASEC container files on internal storage. */
609    final String mAsecInternalPath;
610
611    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
612    // LOCK HELD.  Can be called with mInstallLock held.
613    @GuardedBy("mInstallLock")
614    final Installer mInstaller;
615
616    /** Directory where installed third-party apps stored */
617    final File mAppInstallDir;
618    final File mEphemeralInstallDir;
619
620    /**
621     * Directory to which applications installed internally have their
622     * 32 bit native libraries copied.
623     */
624    private File mAppLib32InstallDir;
625
626    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
627    // apps.
628    final File mDrmAppPrivateInstallDir;
629
630    // ----------------------------------------------------------------
631
632    // Lock for state used when installing and doing other long running
633    // operations.  Methods that must be called with this lock held have
634    // the suffix "LI".
635    final Object mInstallLock = new Object();
636
637    // ----------------------------------------------------------------
638
639    // Keys are String (package name), values are Package.  This also serves
640    // as the lock for the global state.  Methods that must be called with
641    // this lock held have the prefix "LP".
642    @GuardedBy("mPackages")
643    final ArrayMap<String, PackageParser.Package> mPackages =
644            new ArrayMap<String, PackageParser.Package>();
645
646    final ArrayMap<String, Set<String>> mKnownCodebase =
647            new ArrayMap<String, Set<String>>();
648
649    // Tracks available target package names -> overlay package paths.
650    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
651        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
652
653    /**
654     * Tracks new system packages [received in an OTA] that we expect to
655     * find updated user-installed versions. Keys are package name, values
656     * are package location.
657     */
658    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
659    /**
660     * Tracks high priority intent filters for protected actions. During boot, certain
661     * filter actions are protected and should never be allowed to have a high priority
662     * intent filter for them. However, there is one, and only one exception -- the
663     * setup wizard. It must be able to define a high priority intent filter for these
664     * actions to ensure there are no escapes from the wizard. We need to delay processing
665     * of these during boot as we need to look at all of the system packages in order
666     * to know which component is the setup wizard.
667     */
668    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
669    /**
670     * Whether or not processing protected filters should be deferred.
671     */
672    private boolean mDeferProtectedFilters = true;
673
674    /**
675     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
676     */
677    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
678    /**
679     * Whether or not system app permissions should be promoted from install to runtime.
680     */
681    boolean mPromoteSystemApps;
682
683    @GuardedBy("mPackages")
684    final Settings mSettings;
685
686    /**
687     * Set of package names that are currently "frozen", which means active
688     * surgery is being done on the code/data for that package. The platform
689     * will refuse to launch frozen packages to avoid race conditions.
690     *
691     * @see PackageFreezer
692     */
693    @GuardedBy("mPackages")
694    final ArraySet<String> mFrozenPackages = new ArraySet<>();
695
696    final ProtectedPackages mProtectedPackages;
697
698    boolean mFirstBoot;
699
700    // System configuration read by SystemConfig.
701    final int[] mGlobalGids;
702    final SparseArray<ArraySet<String>> mSystemPermissions;
703    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
704
705    // If mac_permissions.xml was found for seinfo labeling.
706    boolean mFoundPolicyFile;
707
708    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
709
710    public static final class SharedLibraryEntry {
711        public final String path;
712        public final String apk;
713
714        SharedLibraryEntry(String _path, String _apk) {
715            path = _path;
716            apk = _apk;
717        }
718    }
719
720    // Currently known shared libraries.
721    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
722            new ArrayMap<String, SharedLibraryEntry>();
723
724    // All available activities, for your resolving pleasure.
725    final ActivityIntentResolver mActivities =
726            new ActivityIntentResolver();
727
728    // All available receivers, for your resolving pleasure.
729    final ActivityIntentResolver mReceivers =
730            new ActivityIntentResolver();
731
732    // All available services, for your resolving pleasure.
733    final ServiceIntentResolver mServices = new ServiceIntentResolver();
734
735    // All available providers, for your resolving pleasure.
736    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
737
738    // Mapping from provider base names (first directory in content URI codePath)
739    // to the provider information.
740    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
741            new ArrayMap<String, PackageParser.Provider>();
742
743    // Mapping from instrumentation class names to info about them.
744    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
745            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
746
747    // Mapping from permission names to info about them.
748    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
749            new ArrayMap<String, PackageParser.PermissionGroup>();
750
751    // Packages whose data we have transfered into another package, thus
752    // should no longer exist.
753    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
754
755    // Broadcast actions that are only available to the system.
756    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
757
758    /** List of packages waiting for verification. */
759    final SparseArray<PackageVerificationState> mPendingVerification
760            = new SparseArray<PackageVerificationState>();
761
762    /** Set of packages associated with each app op permission. */
763    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
764
765    final PackageInstallerService mInstallerService;
766
767    private final PackageDexOptimizer mPackageDexOptimizer;
768    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
769    // is used by other apps).
770    private final DexManager mDexManager;
771
772    private AtomicInteger mNextMoveId = new AtomicInteger();
773    private final MoveCallbacks mMoveCallbacks;
774
775    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
776
777    // Cache of users who need badging.
778    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
779
780    /** Token for keys in mPendingVerification. */
781    private int mPendingVerificationToken = 0;
782
783    volatile boolean mSystemReady;
784    volatile boolean mSafeMode;
785    volatile boolean mHasSystemUidErrors;
786
787    ApplicationInfo mAndroidApplication;
788    final ActivityInfo mResolveActivity = new ActivityInfo();
789    final ResolveInfo mResolveInfo = new ResolveInfo();
790    ComponentName mResolveComponentName;
791    PackageParser.Package mPlatformPackage;
792    ComponentName mCustomResolverComponentName;
793
794    boolean mResolverReplaced = false;
795
796    private final @Nullable ComponentName mIntentFilterVerifierComponent;
797    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
798
799    private int mIntentFilterVerificationToken = 0;
800
801    /** The service connection to the ephemeral resolver */
802    final EphemeralResolverConnection mEphemeralResolverConnection;
803
804    /** Component used to install ephemeral applications */
805    ComponentName mEphemeralInstallerComponent;
806    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
807    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
808
809    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
810            = new SparseArray<IntentFilterVerificationState>();
811
812    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
813
814    // List of packages names to keep cached, even if they are uninstalled for all users
815    private List<String> mKeepUninstalledPackages;
816
817    private UserManagerInternal mUserManagerInternal;
818
819    private File mCacheDir;
820
821    private static class IFVerificationParams {
822        PackageParser.Package pkg;
823        boolean replacing;
824        int userId;
825        int verifierUid;
826
827        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
828                int _userId, int _verifierUid) {
829            pkg = _pkg;
830            replacing = _replacing;
831            userId = _userId;
832            replacing = _replacing;
833            verifierUid = _verifierUid;
834        }
835    }
836
837    private interface IntentFilterVerifier<T extends IntentFilter> {
838        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
839                                               T filter, String packageName);
840        void startVerifications(int userId);
841        void receiveVerificationResponse(int verificationId);
842    }
843
844    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
845        private Context mContext;
846        private ComponentName mIntentFilterVerifierComponent;
847        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
848
849        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
850            mContext = context;
851            mIntentFilterVerifierComponent = verifierComponent;
852        }
853
854        private String getDefaultScheme() {
855            return IntentFilter.SCHEME_HTTPS;
856        }
857
858        @Override
859        public void startVerifications(int userId) {
860            // Launch verifications requests
861            int count = mCurrentIntentFilterVerifications.size();
862            for (int n=0; n<count; n++) {
863                int verificationId = mCurrentIntentFilterVerifications.get(n);
864                final IntentFilterVerificationState ivs =
865                        mIntentFilterVerificationStates.get(verificationId);
866
867                String packageName = ivs.getPackageName();
868
869                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
870                final int filterCount = filters.size();
871                ArraySet<String> domainsSet = new ArraySet<>();
872                for (int m=0; m<filterCount; m++) {
873                    PackageParser.ActivityIntentInfo filter = filters.get(m);
874                    domainsSet.addAll(filter.getHostsList());
875                }
876                synchronized (mPackages) {
877                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
878                            packageName, domainsSet) != null) {
879                        scheduleWriteSettingsLocked();
880                    }
881                }
882                sendVerificationRequest(userId, verificationId, ivs);
883            }
884            mCurrentIntentFilterVerifications.clear();
885        }
886
887        private void sendVerificationRequest(int userId, int verificationId,
888                IntentFilterVerificationState ivs) {
889
890            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
891            verificationIntent.putExtra(
892                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
893                    verificationId);
894            verificationIntent.putExtra(
895                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
896                    getDefaultScheme());
897            verificationIntent.putExtra(
898                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
899                    ivs.getHostsString());
900            verificationIntent.putExtra(
901                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
902                    ivs.getPackageName());
903            verificationIntent.setComponent(mIntentFilterVerifierComponent);
904            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
905
906            UserHandle user = new UserHandle(userId);
907            mContext.sendBroadcastAsUser(verificationIntent, user);
908            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
909                    "Sending IntentFilter verification broadcast");
910        }
911
912        public void receiveVerificationResponse(int verificationId) {
913            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
914
915            final boolean verified = ivs.isVerified();
916
917            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
918            final int count = filters.size();
919            if (DEBUG_DOMAIN_VERIFICATION) {
920                Slog.i(TAG, "Received verification response " + verificationId
921                        + " for " + count + " filters, verified=" + verified);
922            }
923            for (int n=0; n<count; n++) {
924                PackageParser.ActivityIntentInfo filter = filters.get(n);
925                filter.setVerified(verified);
926
927                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
928                        + " verified with result:" + verified + " and hosts:"
929                        + ivs.getHostsString());
930            }
931
932            mIntentFilterVerificationStates.remove(verificationId);
933
934            final String packageName = ivs.getPackageName();
935            IntentFilterVerificationInfo ivi = null;
936
937            synchronized (mPackages) {
938                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
939            }
940            if (ivi == null) {
941                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
942                        + verificationId + " packageName:" + packageName);
943                return;
944            }
945            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
946                    "Updating IntentFilterVerificationInfo for package " + packageName
947                            +" verificationId:" + verificationId);
948
949            synchronized (mPackages) {
950                if (verified) {
951                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
952                } else {
953                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
954                }
955                scheduleWriteSettingsLocked();
956
957                final int userId = ivs.getUserId();
958                if (userId != UserHandle.USER_ALL) {
959                    final int userStatus =
960                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
961
962                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
963                    boolean needUpdate = false;
964
965                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
966                    // already been set by the User thru the Disambiguation dialog
967                    switch (userStatus) {
968                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
969                            if (verified) {
970                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
971                            } else {
972                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
973                            }
974                            needUpdate = true;
975                            break;
976
977                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
978                            if (verified) {
979                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
980                                needUpdate = true;
981                            }
982                            break;
983
984                        default:
985                            // Nothing to do
986                    }
987
988                    if (needUpdate) {
989                        mSettings.updateIntentFilterVerificationStatusLPw(
990                                packageName, updatedStatus, userId);
991                        scheduleWritePackageRestrictionsLocked(userId);
992                    }
993                }
994            }
995        }
996
997        @Override
998        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
999                    ActivityIntentInfo filter, String packageName) {
1000            if (!hasValidDomains(filter)) {
1001                return false;
1002            }
1003            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1004            if (ivs == null) {
1005                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1006                        packageName);
1007            }
1008            if (DEBUG_DOMAIN_VERIFICATION) {
1009                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1010            }
1011            ivs.addFilter(filter);
1012            return true;
1013        }
1014
1015        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1016                int userId, int verificationId, String packageName) {
1017            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1018                    verifierUid, userId, packageName);
1019            ivs.setPendingState();
1020            synchronized (mPackages) {
1021                mIntentFilterVerificationStates.append(verificationId, ivs);
1022                mCurrentIntentFilterVerifications.add(verificationId);
1023            }
1024            return ivs;
1025        }
1026    }
1027
1028    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1029        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1030                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1031                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1032    }
1033
1034    // Set of pending broadcasts for aggregating enable/disable of components.
1035    static class PendingPackageBroadcasts {
1036        // for each user id, a map of <package name -> components within that package>
1037        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1038
1039        public PendingPackageBroadcasts() {
1040            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1041        }
1042
1043        public ArrayList<String> get(int userId, String packageName) {
1044            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1045            return packages.get(packageName);
1046        }
1047
1048        public void put(int userId, String packageName, ArrayList<String> components) {
1049            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1050            packages.put(packageName, components);
1051        }
1052
1053        public void remove(int userId, String packageName) {
1054            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1055            if (packages != null) {
1056                packages.remove(packageName);
1057            }
1058        }
1059
1060        public void remove(int userId) {
1061            mUidMap.remove(userId);
1062        }
1063
1064        public int userIdCount() {
1065            return mUidMap.size();
1066        }
1067
1068        public int userIdAt(int n) {
1069            return mUidMap.keyAt(n);
1070        }
1071
1072        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1073            return mUidMap.get(userId);
1074        }
1075
1076        public int size() {
1077            // total number of pending broadcast entries across all userIds
1078            int num = 0;
1079            for (int i = 0; i< mUidMap.size(); i++) {
1080                num += mUidMap.valueAt(i).size();
1081            }
1082            return num;
1083        }
1084
1085        public void clear() {
1086            mUidMap.clear();
1087        }
1088
1089        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1090            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1091            if (map == null) {
1092                map = new ArrayMap<String, ArrayList<String>>();
1093                mUidMap.put(userId, map);
1094            }
1095            return map;
1096        }
1097    }
1098    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1099
1100    // Service Connection to remote media container service to copy
1101    // package uri's from external media onto secure containers
1102    // or internal storage.
1103    private IMediaContainerService mContainerService = null;
1104
1105    static final int SEND_PENDING_BROADCAST = 1;
1106    static final int MCS_BOUND = 3;
1107    static final int END_COPY = 4;
1108    static final int INIT_COPY = 5;
1109    static final int MCS_UNBIND = 6;
1110    static final int START_CLEANING_PACKAGE = 7;
1111    static final int FIND_INSTALL_LOC = 8;
1112    static final int POST_INSTALL = 9;
1113    static final int MCS_RECONNECT = 10;
1114    static final int MCS_GIVE_UP = 11;
1115    static final int UPDATED_MEDIA_STATUS = 12;
1116    static final int WRITE_SETTINGS = 13;
1117    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1118    static final int PACKAGE_VERIFIED = 15;
1119    static final int CHECK_PENDING_VERIFICATION = 16;
1120    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1121    static final int INTENT_FILTER_VERIFIED = 18;
1122    static final int WRITE_PACKAGE_LIST = 19;
1123    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1124
1125    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1126
1127    // Delay time in millisecs
1128    static final int BROADCAST_DELAY = 10 * 1000;
1129
1130    static UserManagerService sUserManager;
1131
1132    // Stores a list of users whose package restrictions file needs to be updated
1133    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1134
1135    final private DefaultContainerConnection mDefContainerConn =
1136            new DefaultContainerConnection();
1137    class DefaultContainerConnection implements ServiceConnection {
1138        public void onServiceConnected(ComponentName name, IBinder service) {
1139            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1140            final IMediaContainerService imcs = IMediaContainerService.Stub
1141                    .asInterface(Binder.allowBlocking(service));
1142            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1143        }
1144
1145        public void onServiceDisconnected(ComponentName name) {
1146            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1147        }
1148    }
1149
1150    // Recordkeeping of restore-after-install operations that are currently in flight
1151    // between the Package Manager and the Backup Manager
1152    static class PostInstallData {
1153        public InstallArgs args;
1154        public PackageInstalledInfo res;
1155
1156        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1157            args = _a;
1158            res = _r;
1159        }
1160    }
1161
1162    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1163    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1164
1165    // XML tags for backup/restore of various bits of state
1166    private static final String TAG_PREFERRED_BACKUP = "pa";
1167    private static final String TAG_DEFAULT_APPS = "da";
1168    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1169
1170    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1171    private static final String TAG_ALL_GRANTS = "rt-grants";
1172    private static final String TAG_GRANT = "grant";
1173    private static final String ATTR_PACKAGE_NAME = "pkg";
1174
1175    private static final String TAG_PERMISSION = "perm";
1176    private static final String ATTR_PERMISSION_NAME = "name";
1177    private static final String ATTR_IS_GRANTED = "g";
1178    private static final String ATTR_USER_SET = "set";
1179    private static final String ATTR_USER_FIXED = "fixed";
1180    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1181
1182    // System/policy permission grants are not backed up
1183    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1184            FLAG_PERMISSION_POLICY_FIXED
1185            | FLAG_PERMISSION_SYSTEM_FIXED
1186            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1187
1188    // And we back up these user-adjusted states
1189    private static final int USER_RUNTIME_GRANT_MASK =
1190            FLAG_PERMISSION_USER_SET
1191            | FLAG_PERMISSION_USER_FIXED
1192            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1193
1194    final @Nullable String mRequiredVerifierPackage;
1195    final @NonNull String mRequiredInstallerPackage;
1196    final @NonNull String mRequiredUninstallerPackage;
1197    final @Nullable String mSetupWizardPackage;
1198    final @Nullable String mStorageManagerPackage;
1199    final @NonNull String mServicesSystemSharedLibraryPackageName;
1200    final @NonNull String mSharedSystemSharedLibraryPackageName;
1201
1202    final boolean mPermissionReviewRequired;
1203
1204    private final PackageUsage mPackageUsage = new PackageUsage();
1205    private final CompilerStats mCompilerStats = new CompilerStats();
1206
1207    class PackageHandler extends Handler {
1208        private boolean mBound = false;
1209        final ArrayList<HandlerParams> mPendingInstalls =
1210            new ArrayList<HandlerParams>();
1211
1212        private boolean connectToService() {
1213            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1214                    " DefaultContainerService");
1215            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1216            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1217            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1218                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1219                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1220                mBound = true;
1221                return true;
1222            }
1223            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1224            return false;
1225        }
1226
1227        private void disconnectService() {
1228            mContainerService = null;
1229            mBound = false;
1230            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1231            mContext.unbindService(mDefContainerConn);
1232            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1233        }
1234
1235        PackageHandler(Looper looper) {
1236            super(looper);
1237        }
1238
1239        public void handleMessage(Message msg) {
1240            try {
1241                doHandleMessage(msg);
1242            } finally {
1243                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1244            }
1245        }
1246
1247        void doHandleMessage(Message msg) {
1248            switch (msg.what) {
1249                case INIT_COPY: {
1250                    HandlerParams params = (HandlerParams) msg.obj;
1251                    int idx = mPendingInstalls.size();
1252                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1253                    // If a bind was already initiated we dont really
1254                    // need to do anything. The pending install
1255                    // will be processed later on.
1256                    if (!mBound) {
1257                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1258                                System.identityHashCode(mHandler));
1259                        // If this is the only one pending we might
1260                        // have to bind to the service again.
1261                        if (!connectToService()) {
1262                            Slog.e(TAG, "Failed to bind to media container service");
1263                            params.serviceError();
1264                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1265                                    System.identityHashCode(mHandler));
1266                            if (params.traceMethod != null) {
1267                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1268                                        params.traceCookie);
1269                            }
1270                            return;
1271                        } else {
1272                            // Once we bind to the service, the first
1273                            // pending request will be processed.
1274                            mPendingInstalls.add(idx, params);
1275                        }
1276                    } else {
1277                        mPendingInstalls.add(idx, params);
1278                        // Already bound to the service. Just make
1279                        // sure we trigger off processing the first request.
1280                        if (idx == 0) {
1281                            mHandler.sendEmptyMessage(MCS_BOUND);
1282                        }
1283                    }
1284                    break;
1285                }
1286                case MCS_BOUND: {
1287                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1288                    if (msg.obj != null) {
1289                        mContainerService = (IMediaContainerService) msg.obj;
1290                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1291                                System.identityHashCode(mHandler));
1292                    }
1293                    if (mContainerService == null) {
1294                        if (!mBound) {
1295                            // Something seriously wrong since we are not bound and we are not
1296                            // waiting for connection. Bail out.
1297                            Slog.e(TAG, "Cannot bind to media container service");
1298                            for (HandlerParams params : mPendingInstalls) {
1299                                // Indicate service bind error
1300                                params.serviceError();
1301                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1302                                        System.identityHashCode(params));
1303                                if (params.traceMethod != null) {
1304                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1305                                            params.traceMethod, params.traceCookie);
1306                                }
1307                                return;
1308                            }
1309                            mPendingInstalls.clear();
1310                        } else {
1311                            Slog.w(TAG, "Waiting to connect to media container service");
1312                        }
1313                    } else if (mPendingInstalls.size() > 0) {
1314                        HandlerParams params = mPendingInstalls.get(0);
1315                        if (params != null) {
1316                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1317                                    System.identityHashCode(params));
1318                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1319                            if (params.startCopy()) {
1320                                // We are done...  look for more work or to
1321                                // go idle.
1322                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1323                                        "Checking for more work or unbind...");
1324                                // Delete pending install
1325                                if (mPendingInstalls.size() > 0) {
1326                                    mPendingInstalls.remove(0);
1327                                }
1328                                if (mPendingInstalls.size() == 0) {
1329                                    if (mBound) {
1330                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1331                                                "Posting delayed MCS_UNBIND");
1332                                        removeMessages(MCS_UNBIND);
1333                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1334                                        // Unbind after a little delay, to avoid
1335                                        // continual thrashing.
1336                                        sendMessageDelayed(ubmsg, 10000);
1337                                    }
1338                                } else {
1339                                    // There are more pending requests in queue.
1340                                    // Just post MCS_BOUND message to trigger processing
1341                                    // of next pending install.
1342                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1343                                            "Posting MCS_BOUND for next work");
1344                                    mHandler.sendEmptyMessage(MCS_BOUND);
1345                                }
1346                            }
1347                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1348                        }
1349                    } else {
1350                        // Should never happen ideally.
1351                        Slog.w(TAG, "Empty queue");
1352                    }
1353                    break;
1354                }
1355                case MCS_RECONNECT: {
1356                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1357                    if (mPendingInstalls.size() > 0) {
1358                        if (mBound) {
1359                            disconnectService();
1360                        }
1361                        if (!connectToService()) {
1362                            Slog.e(TAG, "Failed to bind to media container service");
1363                            for (HandlerParams params : mPendingInstalls) {
1364                                // Indicate service bind error
1365                                params.serviceError();
1366                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1367                                        System.identityHashCode(params));
1368                            }
1369                            mPendingInstalls.clear();
1370                        }
1371                    }
1372                    break;
1373                }
1374                case MCS_UNBIND: {
1375                    // If there is no actual work left, then time to unbind.
1376                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1377
1378                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1379                        if (mBound) {
1380                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1381
1382                            disconnectService();
1383                        }
1384                    } else if (mPendingInstalls.size() > 0) {
1385                        // There are more pending requests in queue.
1386                        // Just post MCS_BOUND message to trigger processing
1387                        // of next pending install.
1388                        mHandler.sendEmptyMessage(MCS_BOUND);
1389                    }
1390
1391                    break;
1392                }
1393                case MCS_GIVE_UP: {
1394                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1395                    HandlerParams params = mPendingInstalls.remove(0);
1396                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1397                            System.identityHashCode(params));
1398                    break;
1399                }
1400                case SEND_PENDING_BROADCAST: {
1401                    String packages[];
1402                    ArrayList<String> components[];
1403                    int size = 0;
1404                    int uids[];
1405                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406                    synchronized (mPackages) {
1407                        if (mPendingBroadcasts == null) {
1408                            return;
1409                        }
1410                        size = mPendingBroadcasts.size();
1411                        if (size <= 0) {
1412                            // Nothing to be done. Just return
1413                            return;
1414                        }
1415                        packages = new String[size];
1416                        components = new ArrayList[size];
1417                        uids = new int[size];
1418                        int i = 0;  // filling out the above arrays
1419
1420                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1421                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1422                            Iterator<Map.Entry<String, ArrayList<String>>> it
1423                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1424                                            .entrySet().iterator();
1425                            while (it.hasNext() && i < size) {
1426                                Map.Entry<String, ArrayList<String>> ent = it.next();
1427                                packages[i] = ent.getKey();
1428                                components[i] = ent.getValue();
1429                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1430                                uids[i] = (ps != null)
1431                                        ? UserHandle.getUid(packageUserId, ps.appId)
1432                                        : -1;
1433                                i++;
1434                            }
1435                        }
1436                        size = i;
1437                        mPendingBroadcasts.clear();
1438                    }
1439                    // Send broadcasts
1440                    for (int i = 0; i < size; i++) {
1441                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1442                    }
1443                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1444                    break;
1445                }
1446                case START_CLEANING_PACKAGE: {
1447                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1448                    final String packageName = (String)msg.obj;
1449                    final int userId = msg.arg1;
1450                    final boolean andCode = msg.arg2 != 0;
1451                    synchronized (mPackages) {
1452                        if (userId == UserHandle.USER_ALL) {
1453                            int[] users = sUserManager.getUserIds();
1454                            for (int user : users) {
1455                                mSettings.addPackageToCleanLPw(
1456                                        new PackageCleanItem(user, packageName, andCode));
1457                            }
1458                        } else {
1459                            mSettings.addPackageToCleanLPw(
1460                                    new PackageCleanItem(userId, packageName, andCode));
1461                        }
1462                    }
1463                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1464                    startCleaningPackages();
1465                } break;
1466                case POST_INSTALL: {
1467                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1468
1469                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1470                    final boolean didRestore = (msg.arg2 != 0);
1471                    mRunningInstalls.delete(msg.arg1);
1472
1473                    if (data != null) {
1474                        InstallArgs args = data.args;
1475                        PackageInstalledInfo parentRes = data.res;
1476
1477                        final boolean grantPermissions = (args.installFlags
1478                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1479                        final boolean killApp = (args.installFlags
1480                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1481                        final String[] grantedPermissions = args.installGrantPermissions;
1482
1483                        // Handle the parent package
1484                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1485                                grantedPermissions, didRestore, args.installerPackageName,
1486                                args.observer);
1487
1488                        // Handle the child packages
1489                        final int childCount = (parentRes.addedChildPackages != null)
1490                                ? parentRes.addedChildPackages.size() : 0;
1491                        for (int i = 0; i < childCount; i++) {
1492                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1493                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1494                                    grantedPermissions, false, args.installerPackageName,
1495                                    args.observer);
1496                        }
1497
1498                        // Log tracing if needed
1499                        if (args.traceMethod != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1501                                    args.traceCookie);
1502                        }
1503                    } else {
1504                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1505                    }
1506
1507                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1508                } break;
1509                case UPDATED_MEDIA_STATUS: {
1510                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1511                    boolean reportStatus = msg.arg1 == 1;
1512                    boolean doGc = msg.arg2 == 1;
1513                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1514                    if (doGc) {
1515                        // Force a gc to clear up stale containers.
1516                        Runtime.getRuntime().gc();
1517                    }
1518                    if (msg.obj != null) {
1519                        @SuppressWarnings("unchecked")
1520                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1521                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1522                        // Unload containers
1523                        unloadAllContainers(args);
1524                    }
1525                    if (reportStatus) {
1526                        try {
1527                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                    "Invoking StorageManagerService call back");
1529                            PackageHelper.getStorageManager().finishMediaUpdate();
1530                        } catch (RemoteException e) {
1531                            Log.e(TAG, "StorageManagerService not running?");
1532                        }
1533                    }
1534                } break;
1535                case WRITE_SETTINGS: {
1536                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1537                    synchronized (mPackages) {
1538                        removeMessages(WRITE_SETTINGS);
1539                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1540                        mSettings.writeLPr();
1541                        mDirtyUsers.clear();
1542                    }
1543                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1544                } break;
1545                case WRITE_PACKAGE_RESTRICTIONS: {
1546                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1547                    synchronized (mPackages) {
1548                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1549                        for (int userId : mDirtyUsers) {
1550                            mSettings.writePackageRestrictionsLPr(userId);
1551                        }
1552                        mDirtyUsers.clear();
1553                    }
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1555                } break;
1556                case WRITE_PACKAGE_LIST: {
1557                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1558                    synchronized (mPackages) {
1559                        removeMessages(WRITE_PACKAGE_LIST);
1560                        mSettings.writePackageListLPr(msg.arg1);
1561                    }
1562                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1563                } break;
1564                case CHECK_PENDING_VERIFICATION: {
1565                    final int verificationId = msg.arg1;
1566                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1567
1568                    if ((state != null) && !state.timeoutExtended()) {
1569                        final InstallArgs args = state.getInstallArgs();
1570                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1571
1572                        Slog.i(TAG, "Verification timed out for " + originUri);
1573                        mPendingVerification.remove(verificationId);
1574
1575                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1576
1577                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1578                            Slog.i(TAG, "Continuing with installation of " + originUri);
1579                            state.setVerifierResponse(Binder.getCallingUid(),
1580                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1581                            broadcastPackageVerified(verificationId, originUri,
1582                                    PackageManager.VERIFICATION_ALLOW,
1583                                    state.getInstallArgs().getUser());
1584                            try {
1585                                ret = args.copyApk(mContainerService, true);
1586                            } catch (RemoteException e) {
1587                                Slog.e(TAG, "Could not contact the ContainerService");
1588                            }
1589                        } else {
1590                            broadcastPackageVerified(verificationId, originUri,
1591                                    PackageManager.VERIFICATION_REJECT,
1592                                    state.getInstallArgs().getUser());
1593                        }
1594
1595                        Trace.asyncTraceEnd(
1596                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1597
1598                        processPendingInstall(args, ret);
1599                        mHandler.sendEmptyMessage(MCS_UNBIND);
1600                    }
1601                    break;
1602                }
1603                case PACKAGE_VERIFIED: {
1604                    final int verificationId = msg.arg1;
1605
1606                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1607                    if (state == null) {
1608                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1609                        break;
1610                    }
1611
1612                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1613
1614                    state.setVerifierResponse(response.callerUid, response.code);
1615
1616                    if (state.isVerificationComplete()) {
1617                        mPendingVerification.remove(verificationId);
1618
1619                        final InstallArgs args = state.getInstallArgs();
1620                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1621
1622                        int ret;
1623                        if (state.isInstallAllowed()) {
1624                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1625                            broadcastPackageVerified(verificationId, originUri,
1626                                    response.code, state.getInstallArgs().getUser());
1627                            try {
1628                                ret = args.copyApk(mContainerService, true);
1629                            } catch (RemoteException e) {
1630                                Slog.e(TAG, "Could not contact the ContainerService");
1631                            }
1632                        } else {
1633                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1634                        }
1635
1636                        Trace.asyncTraceEnd(
1637                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1638
1639                        processPendingInstall(args, ret);
1640                        mHandler.sendEmptyMessage(MCS_UNBIND);
1641                    }
1642
1643                    break;
1644                }
1645                case START_INTENT_FILTER_VERIFICATIONS: {
1646                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1647                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1648                            params.replacing, params.pkg);
1649                    break;
1650                }
1651                case INTENT_FILTER_VERIFIED: {
1652                    final int verificationId = msg.arg1;
1653
1654                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1655                            verificationId);
1656                    if (state == null) {
1657                        Slog.w(TAG, "Invalid IntentFilter verification token "
1658                                + verificationId + " received");
1659                        break;
1660                    }
1661
1662                    final int userId = state.getUserId();
1663
1664                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1665                            "Processing IntentFilter verification with token:"
1666                            + verificationId + " and userId:" + userId);
1667
1668                    final IntentFilterVerificationResponse response =
1669                            (IntentFilterVerificationResponse) msg.obj;
1670
1671                    state.setVerifierResponse(response.callerUid, response.code);
1672
1673                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1674                            "IntentFilter verification with token:" + verificationId
1675                            + " and userId:" + userId
1676                            + " is settings verifier response with response code:"
1677                            + response.code);
1678
1679                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1680                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1681                                + response.getFailedDomainsString());
1682                    }
1683
1684                    if (state.isVerificationComplete()) {
1685                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1686                    } else {
1687                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1688                                "IntentFilter verification with token:" + verificationId
1689                                + " was not said to be complete");
1690                    }
1691
1692                    break;
1693                }
1694                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1695                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1696                            mEphemeralResolverConnection,
1697                            (EphemeralRequest) msg.obj,
1698                            mEphemeralInstallerActivity,
1699                            mHandler);
1700                }
1701            }
1702        }
1703    }
1704
1705    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1706            boolean killApp, String[] grantedPermissions,
1707            boolean launchedForRestore, String installerPackage,
1708            IPackageInstallObserver2 installObserver) {
1709        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1710            // Send the removed broadcasts
1711            if (res.removedInfo != null) {
1712                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1713            }
1714
1715            // Now that we successfully installed the package, grant runtime
1716            // permissions if requested before broadcasting the install. Also
1717            // for legacy apps in permission review mode we clear the permission
1718            // review flag which is used to emulate runtime permissions for
1719            // legacy apps.
1720            if (grantPermissions) {
1721                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1722            }
1723
1724            final boolean update = res.removedInfo != null
1725                    && res.removedInfo.removedPackage != null;
1726
1727            // If this is the first time we have child packages for a disabled privileged
1728            // app that had no children, we grant requested runtime permissions to the new
1729            // children if the parent on the system image had them already granted.
1730            if (res.pkg.parentPackage != null) {
1731                synchronized (mPackages) {
1732                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1733                }
1734            }
1735
1736            synchronized (mPackages) {
1737                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1738            }
1739
1740            final String packageName = res.pkg.applicationInfo.packageName;
1741
1742            // Determine the set of users who are adding this package for
1743            // the first time vs. those who are seeing an update.
1744            int[] firstUsers = EMPTY_INT_ARRAY;
1745            int[] updateUsers = EMPTY_INT_ARRAY;
1746            if (res.origUsers == null || res.origUsers.length == 0) {
1747                firstUsers = res.newUsers;
1748            } else {
1749                for (int newUser : res.newUsers) {
1750                    boolean isNew = true;
1751                    for (int origUser : res.origUsers) {
1752                        if (origUser == newUser) {
1753                            isNew = false;
1754                            break;
1755                        }
1756                    }
1757                    if (isNew) {
1758                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1759                    } else {
1760                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1761                    }
1762                }
1763            }
1764
1765            // Send installed broadcasts if the install/update is not ephemeral
1766            if (!isEphemeral(res.pkg)) {
1767                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1768
1769                // Send added for users that see the package for the first time
1770                // sendPackageAddedForNewUsers also deals with system apps
1771                int appId = UserHandle.getAppId(res.uid);
1772                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1773                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1774
1775                // Send added for users that don't see the package for the first time
1776                Bundle extras = new Bundle(1);
1777                extras.putInt(Intent.EXTRA_UID, res.uid);
1778                if (update) {
1779                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1780                }
1781                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1782                        extras, 0 /*flags*/, null /*targetPackage*/,
1783                        null /*finishedReceiver*/, updateUsers);
1784
1785                // Send replaced for users that don't see the package for the first time
1786                if (update) {
1787                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1788                            packageName, extras, 0 /*flags*/,
1789                            null /*targetPackage*/, null /*finishedReceiver*/,
1790                            updateUsers);
1791                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1792                            null /*package*/, null /*extras*/, 0 /*flags*/,
1793                            packageName /*targetPackage*/,
1794                            null /*finishedReceiver*/, updateUsers);
1795                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1796                    // First-install and we did a restore, so we're responsible for the
1797                    // first-launch broadcast.
1798                    if (DEBUG_BACKUP) {
1799                        Slog.i(TAG, "Post-restore of " + packageName
1800                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1801                    }
1802                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1803                }
1804
1805                // Send broadcast package appeared if forward locked/external for all users
1806                // treat asec-hosted packages like removable media on upgrade
1807                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1808                    if (DEBUG_INSTALL) {
1809                        Slog.i(TAG, "upgrading pkg " + res.pkg
1810                                + " is ASEC-hosted -> AVAILABLE");
1811                    }
1812                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1813                    ArrayList<String> pkgList = new ArrayList<>(1);
1814                    pkgList.add(packageName);
1815                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1816                }
1817            }
1818
1819            // Work that needs to happen on first install within each user
1820            if (firstUsers != null && firstUsers.length > 0) {
1821                synchronized (mPackages) {
1822                    for (int userId : firstUsers) {
1823                        // If this app is a browser and it's newly-installed for some
1824                        // users, clear any default-browser state in those users. The
1825                        // app's nature doesn't depend on the user, so we can just check
1826                        // its browser nature in any user and generalize.
1827                        if (packageIsBrowser(packageName, userId)) {
1828                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1829                        }
1830
1831                        // We may also need to apply pending (restored) runtime
1832                        // permission grants within these users.
1833                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1834                    }
1835                }
1836            }
1837
1838            // Log current value of "unknown sources" setting
1839            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1840                    getUnknownSourcesSettings());
1841
1842            // Force a gc to clear up things
1843            Runtime.getRuntime().gc();
1844
1845            // Remove the replaced package's older resources safely now
1846            // We delete after a gc for applications  on sdcard.
1847            if (res.removedInfo != null && res.removedInfo.args != null) {
1848                synchronized (mInstallLock) {
1849                    res.removedInfo.args.doPostDeleteLI(true);
1850                }
1851            }
1852        }
1853
1854        // If someone is watching installs - notify them
1855        if (installObserver != null) {
1856            try {
1857                Bundle extras = extrasForInstallResult(res);
1858                installObserver.onPackageInstalled(res.name, res.returnCode,
1859                        res.returnMsg, extras);
1860            } catch (RemoteException e) {
1861                Slog.i(TAG, "Observer no longer exists.");
1862            }
1863        }
1864    }
1865
1866    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1867            PackageParser.Package pkg) {
1868        if (pkg.parentPackage == null) {
1869            return;
1870        }
1871        if (pkg.requestedPermissions == null) {
1872            return;
1873        }
1874        final PackageSetting disabledSysParentPs = mSettings
1875                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1876        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1877                || !disabledSysParentPs.isPrivileged()
1878                || (disabledSysParentPs.childPackageNames != null
1879                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1880            return;
1881        }
1882        final int[] allUserIds = sUserManager.getUserIds();
1883        final int permCount = pkg.requestedPermissions.size();
1884        for (int i = 0; i < permCount; i++) {
1885            String permission = pkg.requestedPermissions.get(i);
1886            BasePermission bp = mSettings.mPermissions.get(permission);
1887            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1888                continue;
1889            }
1890            for (int userId : allUserIds) {
1891                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1892                        permission, userId)) {
1893                    grantRuntimePermission(pkg.packageName, permission, userId);
1894                }
1895            }
1896        }
1897    }
1898
1899    private StorageEventListener mStorageListener = new StorageEventListener() {
1900        @Override
1901        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1902            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1903                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1904                    final String volumeUuid = vol.getFsUuid();
1905
1906                    // Clean up any users or apps that were removed or recreated
1907                    // while this volume was missing
1908                    reconcileUsers(volumeUuid);
1909                    reconcileApps(volumeUuid);
1910
1911                    // Clean up any install sessions that expired or were
1912                    // cancelled while this volume was missing
1913                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1914
1915                    loadPrivatePackages(vol);
1916
1917                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1918                    unloadPrivatePackages(vol);
1919                }
1920            }
1921
1922            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1923                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1924                    updateExternalMediaStatus(true, false);
1925                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1926                    updateExternalMediaStatus(false, false);
1927                }
1928            }
1929        }
1930
1931        @Override
1932        public void onVolumeForgotten(String fsUuid) {
1933            if (TextUtils.isEmpty(fsUuid)) {
1934                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1935                return;
1936            }
1937
1938            // Remove any apps installed on the forgotten volume
1939            synchronized (mPackages) {
1940                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1941                for (PackageSetting ps : packages) {
1942                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1943                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1944                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1945
1946                    // Try very hard to release any references to this package
1947                    // so we don't risk the system server being killed due to
1948                    // open FDs
1949                    AttributeCache.instance().removePackage(ps.name);
1950                }
1951
1952                mSettings.onVolumeForgotten(fsUuid);
1953                mSettings.writeLPr();
1954            }
1955        }
1956    };
1957
1958    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1959            String[] grantedPermissions) {
1960        for (int userId : userIds) {
1961            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1962        }
1963    }
1964
1965    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1966            String[] grantedPermissions) {
1967        SettingBase sb = (SettingBase) pkg.mExtras;
1968        if (sb == null) {
1969            return;
1970        }
1971
1972        PermissionsState permissionsState = sb.getPermissionsState();
1973
1974        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1975                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1976
1977        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1978                >= Build.VERSION_CODES.M;
1979
1980        for (String permission : pkg.requestedPermissions) {
1981            final BasePermission bp;
1982            synchronized (mPackages) {
1983                bp = mSettings.mPermissions.get(permission);
1984            }
1985            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1986                    && (grantedPermissions == null
1987                           || ArrayUtils.contains(grantedPermissions, permission))) {
1988                final int flags = permissionsState.getPermissionFlags(permission, userId);
1989                if (supportsRuntimePermissions) {
1990                    // Installer cannot change immutable permissions.
1991                    if ((flags & immutableFlags) == 0) {
1992                        grantRuntimePermission(pkg.packageName, permission, userId);
1993                    }
1994                } else if (mPermissionReviewRequired) {
1995                    // In permission review mode we clear the review flag when we
1996                    // are asked to install the app with all permissions granted.
1997                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
1998                        updatePermissionFlags(permission, pkg.packageName,
1999                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2000                    }
2001                }
2002            }
2003        }
2004    }
2005
2006    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2007        Bundle extras = null;
2008        switch (res.returnCode) {
2009            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2010                extras = new Bundle();
2011                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2012                        res.origPermission);
2013                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2014                        res.origPackage);
2015                break;
2016            }
2017            case PackageManager.INSTALL_SUCCEEDED: {
2018                extras = new Bundle();
2019                extras.putBoolean(Intent.EXTRA_REPLACING,
2020                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2021                break;
2022            }
2023        }
2024        return extras;
2025    }
2026
2027    void scheduleWriteSettingsLocked() {
2028        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2029            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2030        }
2031    }
2032
2033    void scheduleWritePackageListLocked(int userId) {
2034        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2035            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2036            msg.arg1 = userId;
2037            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2038        }
2039    }
2040
2041    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2042        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2043        scheduleWritePackageRestrictionsLocked(userId);
2044    }
2045
2046    void scheduleWritePackageRestrictionsLocked(int userId) {
2047        final int[] userIds = (userId == UserHandle.USER_ALL)
2048                ? sUserManager.getUserIds() : new int[]{userId};
2049        for (int nextUserId : userIds) {
2050            if (!sUserManager.exists(nextUserId)) return;
2051            mDirtyUsers.add(nextUserId);
2052            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2053                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2054            }
2055        }
2056    }
2057
2058    public static PackageManagerService main(Context context, Installer installer,
2059            boolean factoryTest, boolean onlyCore) {
2060        // Self-check for initial settings.
2061        PackageManagerServiceCompilerMapping.checkProperties();
2062
2063        PackageManagerService m = new PackageManagerService(context, installer,
2064                factoryTest, onlyCore);
2065        m.enableSystemUserPackages();
2066        ServiceManager.addService("package", m);
2067        return m;
2068    }
2069
2070    private void enableSystemUserPackages() {
2071        if (!UserManager.isSplitSystemUser()) {
2072            return;
2073        }
2074        // For system user, enable apps based on the following conditions:
2075        // - app is whitelisted or belong to one of these groups:
2076        //   -- system app which has no launcher icons
2077        //   -- system app which has INTERACT_ACROSS_USERS permission
2078        //   -- system IME app
2079        // - app is not in the blacklist
2080        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2081        Set<String> enableApps = new ArraySet<>();
2082        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2083                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2084                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2085        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2086        enableApps.addAll(wlApps);
2087        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2088                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2089        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2090        enableApps.removeAll(blApps);
2091        Log.i(TAG, "Applications installed for system user: " + enableApps);
2092        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2093                UserHandle.SYSTEM);
2094        final int allAppsSize = allAps.size();
2095        synchronized (mPackages) {
2096            for (int i = 0; i < allAppsSize; i++) {
2097                String pName = allAps.get(i);
2098                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2099                // Should not happen, but we shouldn't be failing if it does
2100                if (pkgSetting == null) {
2101                    continue;
2102                }
2103                boolean install = enableApps.contains(pName);
2104                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2105                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2106                            + " for system user");
2107                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2108                }
2109            }
2110        }
2111    }
2112
2113    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2114        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2115                Context.DISPLAY_SERVICE);
2116        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2117    }
2118
2119    /**
2120     * Requests that files preopted on a secondary system partition be copied to the data partition
2121     * if possible.  Note that the actual copying of the files is accomplished by init for security
2122     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2123     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2124     */
2125    private static void requestCopyPreoptedFiles() {
2126        final int WAIT_TIME_MS = 100;
2127        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2128        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2129            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2130            // We will wait for up to 100 seconds.
2131            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2132            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2133                try {
2134                    Thread.sleep(WAIT_TIME_MS);
2135                } catch (InterruptedException e) {
2136                    // Do nothing
2137                }
2138                if (SystemClock.uptimeMillis() > timeEnd) {
2139                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2140                    Slog.wtf(TAG, "cppreopt did not finish!");
2141                    break;
2142                }
2143            }
2144        }
2145    }
2146
2147    public PackageManagerService(Context context, Installer installer,
2148            boolean factoryTest, boolean onlyCore) {
2149        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2150        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2151                SystemClock.uptimeMillis());
2152
2153        if (mSdkVersion <= 0) {
2154            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2155        }
2156
2157        mContext = context;
2158
2159        mPermissionReviewRequired = context.getResources().getBoolean(
2160                R.bool.config_permissionReviewRequired);
2161
2162        mFactoryTest = factoryTest;
2163        mOnlyCore = onlyCore;
2164        mMetrics = new DisplayMetrics();
2165        mSettings = new Settings(mPackages);
2166        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2167                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2168        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2169                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2170        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2171                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2172        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2173                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2174        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2175                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2176        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2177                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2178
2179        String separateProcesses = SystemProperties.get("debug.separate_processes");
2180        if (separateProcesses != null && separateProcesses.length() > 0) {
2181            if ("*".equals(separateProcesses)) {
2182                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2183                mSeparateProcesses = null;
2184                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2185            } else {
2186                mDefParseFlags = 0;
2187                mSeparateProcesses = separateProcesses.split(",");
2188                Slog.w(TAG, "Running with debug.separate_processes: "
2189                        + separateProcesses);
2190            }
2191        } else {
2192            mDefParseFlags = 0;
2193            mSeparateProcesses = null;
2194        }
2195
2196        mInstaller = installer;
2197        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2198                "*dexopt*");
2199        mDexManager = new DexManager();
2200        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2201
2202        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2203                FgThread.get().getLooper());
2204
2205        getDefaultDisplayMetrics(context, mMetrics);
2206
2207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2208        SystemConfig systemConfig = SystemConfig.getInstance();
2209        mGlobalGids = systemConfig.getGlobalGids();
2210        mSystemPermissions = systemConfig.getSystemPermissions();
2211        mAvailableFeatures = systemConfig.getAvailableFeatures();
2212        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2213
2214        mProtectedPackages = new ProtectedPackages(mContext);
2215
2216        synchronized (mInstallLock) {
2217        // writer
2218        synchronized (mPackages) {
2219            mHandlerThread = new ServiceThread(TAG,
2220                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2221            mHandlerThread.start();
2222            mHandler = new PackageHandler(mHandlerThread.getLooper());
2223            mProcessLoggingHandler = new ProcessLoggingHandler();
2224            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2225
2226            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2227
2228            File dataDir = Environment.getDataDirectory();
2229            mAppInstallDir = new File(dataDir, "app");
2230            mAppLib32InstallDir = new File(dataDir, "app-lib");
2231            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2232            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2233            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2234
2235            sUserManager = new UserManagerService(context, this, mPackages);
2236
2237            // Propagate permission configuration in to package manager.
2238            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2239                    = systemConfig.getPermissions();
2240            for (int i=0; i<permConfig.size(); i++) {
2241                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2242                BasePermission bp = mSettings.mPermissions.get(perm.name);
2243                if (bp == null) {
2244                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2245                    mSettings.mPermissions.put(perm.name, bp);
2246                }
2247                if (perm.gids != null) {
2248                    bp.setGids(perm.gids, perm.perUser);
2249                }
2250            }
2251
2252            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2253            for (int i=0; i<libConfig.size(); i++) {
2254                mSharedLibraries.put(libConfig.keyAt(i),
2255                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2256            }
2257
2258            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2259
2260            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2261            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2262            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2263
2264            // Clean up orphaned packages for which the code path doesn't exist
2265            // and they are an update to a system app - caused by bug/32321269
2266            final int packageSettingCount = mSettings.mPackages.size();
2267            for (int i = packageSettingCount - 1; i >= 0; i--) {
2268                PackageSetting ps = mSettings.mPackages.valueAt(i);
2269                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2270                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2271                    mSettings.mPackages.removeAt(i);
2272                    mSettings.enableSystemPackageLPw(ps.name);
2273                }
2274            }
2275
2276            if (mFirstBoot) {
2277                requestCopyPreoptedFiles();
2278            }
2279
2280            String customResolverActivity = Resources.getSystem().getString(
2281                    R.string.config_customResolverActivity);
2282            if (TextUtils.isEmpty(customResolverActivity)) {
2283                customResolverActivity = null;
2284            } else {
2285                mCustomResolverComponentName = ComponentName.unflattenFromString(
2286                        customResolverActivity);
2287            }
2288
2289            long startTime = SystemClock.uptimeMillis();
2290
2291            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2292                    startTime);
2293
2294            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2295            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2296
2297            if (bootClassPath == null) {
2298                Slog.w(TAG, "No BOOTCLASSPATH found!");
2299            }
2300
2301            if (systemServerClassPath == null) {
2302                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2303            }
2304
2305            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2306            final String[] dexCodeInstructionSets =
2307                    getDexCodeInstructionSets(
2308                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2309
2310            /**
2311             * Ensure all external libraries have had dexopt run on them.
2312             */
2313            if (mSharedLibraries.size() > 0) {
2314                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2315                // NOTE: For now, we're compiling these system "shared libraries"
2316                // (and framework jars) into all available architectures. It's possible
2317                // to compile them only when we come across an app that uses them (there's
2318                // already logic for that in scanPackageLI) but that adds some complexity.
2319                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2320                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2321                        final String lib = libEntry.path;
2322                        if (lib == null) {
2323                            continue;
2324                        }
2325
2326                        try {
2327                            // Shared libraries do not have profiles so we perform a full
2328                            // AOT compilation (if needed).
2329                            int dexoptNeeded = DexFile.getDexOptNeeded(
2330                                    lib, dexCodeInstructionSet,
2331                                    getCompilerFilterForReason(REASON_SHARED_APK),
2332                                    false /* newProfile */);
2333                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2334                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2335                                        dexCodeInstructionSet, dexoptNeeded, null,
2336                                        DEXOPT_PUBLIC,
2337                                        getCompilerFilterForReason(REASON_SHARED_APK),
2338                                        StorageManager.UUID_PRIVATE_INTERNAL,
2339                                        SKIP_SHARED_LIBRARY_CHECK);
2340                            }
2341                        } catch (FileNotFoundException e) {
2342                            Slog.w(TAG, "Library not found: " + lib);
2343                        } catch (IOException | InstallerException e) {
2344                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2345                                    + e.getMessage());
2346                        }
2347                    }
2348                }
2349                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2350            }
2351
2352            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2353
2354            final VersionInfo ver = mSettings.getInternalVersion();
2355            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2356
2357            // when upgrading from pre-M, promote system app permissions from install to runtime
2358            mPromoteSystemApps =
2359                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2360
2361            // When upgrading from pre-N, we need to handle package extraction like first boot,
2362            // as there is no profiling data available.
2363            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2364
2365            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2366
2367            // save off the names of pre-existing system packages prior to scanning; we don't
2368            // want to automatically grant runtime permissions for new system apps
2369            if (mPromoteSystemApps) {
2370                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2371                while (pkgSettingIter.hasNext()) {
2372                    PackageSetting ps = pkgSettingIter.next();
2373                    if (isSystemApp(ps)) {
2374                        mExistingSystemPackages.add(ps.name);
2375                    }
2376                }
2377            }
2378
2379            mCacheDir = preparePackageParserCache(mIsUpgrade);
2380
2381            // Set flag to monitor and not change apk file paths when
2382            // scanning install directories.
2383            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2384
2385            if (mIsUpgrade || mFirstBoot) {
2386                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2387            }
2388
2389            // Collect vendor overlay packages. (Do this before scanning any apps.)
2390            // For security and version matching reason, only consider
2391            // overlay packages if they reside in the right directory.
2392            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2393            if (overlayThemeDir.isEmpty()) {
2394                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2395            }
2396            if (!overlayThemeDir.isEmpty()) {
2397                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2398                        | PackageParser.PARSE_IS_SYSTEM
2399                        | PackageParser.PARSE_IS_SYSTEM_DIR
2400                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2401            }
2402            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2403                    | PackageParser.PARSE_IS_SYSTEM
2404                    | PackageParser.PARSE_IS_SYSTEM_DIR
2405                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2406
2407            // Find base frameworks (resource packages without code).
2408            scanDirTracedLI(frameworkDir, mDefParseFlags
2409                    | PackageParser.PARSE_IS_SYSTEM
2410                    | PackageParser.PARSE_IS_SYSTEM_DIR
2411                    | PackageParser.PARSE_IS_PRIVILEGED,
2412                    scanFlags | SCAN_NO_DEX, 0);
2413
2414            // Collected privileged system packages.
2415            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2416            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2417                    | PackageParser.PARSE_IS_SYSTEM
2418                    | PackageParser.PARSE_IS_SYSTEM_DIR
2419                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2420
2421            // Collect ordinary system packages.
2422            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2423            scanDirTracedLI(systemAppDir, mDefParseFlags
2424                    | PackageParser.PARSE_IS_SYSTEM
2425                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2426
2427            // Collect all vendor packages.
2428            File vendorAppDir = new File("/vendor/app");
2429            try {
2430                vendorAppDir = vendorAppDir.getCanonicalFile();
2431            } catch (IOException e) {
2432                // failed to look up canonical path, continue with original one
2433            }
2434            scanDirTracedLI(vendorAppDir, mDefParseFlags
2435                    | PackageParser.PARSE_IS_SYSTEM
2436                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2437
2438            // Collect all OEM packages.
2439            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2440            scanDirTracedLI(oemAppDir, mDefParseFlags
2441                    | PackageParser.PARSE_IS_SYSTEM
2442                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2443
2444            // Prune any system packages that no longer exist.
2445            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2446            if (!mOnlyCore) {
2447                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2448                while (psit.hasNext()) {
2449                    PackageSetting ps = psit.next();
2450
2451                    /*
2452                     * If this is not a system app, it can't be a
2453                     * disable system app.
2454                     */
2455                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2456                        continue;
2457                    }
2458
2459                    /*
2460                     * If the package is scanned, it's not erased.
2461                     */
2462                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2463                    if (scannedPkg != null) {
2464                        /*
2465                         * If the system app is both scanned and in the
2466                         * disabled packages list, then it must have been
2467                         * added via OTA. Remove it from the currently
2468                         * scanned package so the previously user-installed
2469                         * application can be scanned.
2470                         */
2471                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2472                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2473                                    + ps.name + "; removing system app.  Last known codePath="
2474                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2475                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2476                                    + scannedPkg.mVersionCode);
2477                            removePackageLI(scannedPkg, true);
2478                            mExpectingBetter.put(ps.name, ps.codePath);
2479                        }
2480
2481                        continue;
2482                    }
2483
2484                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2485                        psit.remove();
2486                        logCriticalInfo(Log.WARN, "System package " + ps.name
2487                                + " no longer exists; it's data will be wiped");
2488                        // Actual deletion of code and data will be handled by later
2489                        // reconciliation step
2490                    } else {
2491                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2492                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2493                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2494                        }
2495                    }
2496                }
2497            }
2498
2499            //look for any incomplete package installations
2500            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2501            for (int i = 0; i < deletePkgsList.size(); i++) {
2502                // Actual deletion of code and data will be handled by later
2503                // reconciliation step
2504                final String packageName = deletePkgsList.get(i).name;
2505                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2506                synchronized (mPackages) {
2507                    mSettings.removePackageLPw(packageName);
2508                }
2509            }
2510
2511            //delete tmp files
2512            deleteTempPackageFiles();
2513
2514            // Remove any shared userIDs that have no associated packages
2515            mSettings.pruneSharedUsersLPw();
2516
2517            if (!mOnlyCore) {
2518                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2519                        SystemClock.uptimeMillis());
2520                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2521
2522                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2523                        | PackageParser.PARSE_FORWARD_LOCK,
2524                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2525
2526                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2527                        | PackageParser.PARSE_IS_EPHEMERAL,
2528                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2529
2530                /**
2531                 * Remove disable package settings for any updated system
2532                 * apps that were removed via an OTA. If they're not a
2533                 * previously-updated app, remove them completely.
2534                 * Otherwise, just revoke their system-level permissions.
2535                 */
2536                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2537                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2538                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2539
2540                    String msg;
2541                    if (deletedPkg == null) {
2542                        msg = "Updated system package " + deletedAppName
2543                                + " no longer exists; it's data will be wiped";
2544                        // Actual deletion of code and data will be handled by later
2545                        // reconciliation step
2546                    } else {
2547                        msg = "Updated system app + " + deletedAppName
2548                                + " no longer present; removing system privileges for "
2549                                + deletedAppName;
2550
2551                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2552
2553                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2554                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2555                    }
2556                    logCriticalInfo(Log.WARN, msg);
2557                }
2558
2559                /**
2560                 * Make sure all system apps that we expected to appear on
2561                 * the userdata partition actually showed up. If they never
2562                 * appeared, crawl back and revive the system version.
2563                 */
2564                for (int i = 0; i < mExpectingBetter.size(); i++) {
2565                    final String packageName = mExpectingBetter.keyAt(i);
2566                    if (!mPackages.containsKey(packageName)) {
2567                        final File scanFile = mExpectingBetter.valueAt(i);
2568
2569                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2570                                + " but never showed up; reverting to system");
2571
2572                        int reparseFlags = mDefParseFlags;
2573                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2574                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2575                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2576                                    | PackageParser.PARSE_IS_PRIVILEGED;
2577                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2578                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2579                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2580                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2581                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2582                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2583                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2584                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2585                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2586                        } else {
2587                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2588                            continue;
2589                        }
2590
2591                        mSettings.enableSystemPackageLPw(packageName);
2592
2593                        try {
2594                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2595                        } catch (PackageManagerException e) {
2596                            Slog.e(TAG, "Failed to parse original system package: "
2597                                    + e.getMessage());
2598                        }
2599                    }
2600                }
2601            }
2602            mExpectingBetter.clear();
2603
2604            // Resolve the storage manager.
2605            mStorageManagerPackage = getStorageManagerPackageName();
2606
2607            // Resolve protected action filters. Only the setup wizard is allowed to
2608            // have a high priority filter for these actions.
2609            mSetupWizardPackage = getSetupWizardPackageName();
2610            if (mProtectedFilters.size() > 0) {
2611                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2612                    Slog.i(TAG, "No setup wizard;"
2613                        + " All protected intents capped to priority 0");
2614                }
2615                for (ActivityIntentInfo filter : mProtectedFilters) {
2616                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2617                        if (DEBUG_FILTERS) {
2618                            Slog.i(TAG, "Found setup wizard;"
2619                                + " allow priority " + filter.getPriority() + ";"
2620                                + " package: " + filter.activity.info.packageName
2621                                + " activity: " + filter.activity.className
2622                                + " priority: " + filter.getPriority());
2623                        }
2624                        // skip setup wizard; allow it to keep the high priority filter
2625                        continue;
2626                    }
2627                    Slog.w(TAG, "Protected action; cap priority to 0;"
2628                            + " package: " + filter.activity.info.packageName
2629                            + " activity: " + filter.activity.className
2630                            + " origPrio: " + filter.getPriority());
2631                    filter.setPriority(0);
2632                }
2633            }
2634            mDeferProtectedFilters = false;
2635            mProtectedFilters.clear();
2636
2637            // Now that we know all of the shared libraries, update all clients to have
2638            // the correct library paths.
2639            updateAllSharedLibrariesLPw();
2640
2641            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2642                // NOTE: We ignore potential failures here during a system scan (like
2643                // the rest of the commands above) because there's precious little we
2644                // can do about it. A settings error is reported, though.
2645                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2646            }
2647
2648            // Now that we know all the packages we are keeping,
2649            // read and update their last usage times.
2650            mPackageUsage.read(mPackages);
2651            mCompilerStats.read();
2652
2653            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2654                    SystemClock.uptimeMillis());
2655            Slog.i(TAG, "Time to scan packages: "
2656                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2657                    + " seconds");
2658
2659            // If the platform SDK has changed since the last time we booted,
2660            // we need to re-grant app permission to catch any new ones that
2661            // appear.  This is really a hack, and means that apps can in some
2662            // cases get permissions that the user didn't initially explicitly
2663            // allow...  it would be nice to have some better way to handle
2664            // this situation.
2665            int updateFlags = UPDATE_PERMISSIONS_ALL;
2666            if (ver.sdkVersion != mSdkVersion) {
2667                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2668                        + mSdkVersion + "; regranting permissions for internal storage");
2669                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2670            }
2671            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2672            ver.sdkVersion = mSdkVersion;
2673
2674            // If this is the first boot or an update from pre-M, and it is a normal
2675            // boot, then we need to initialize the default preferred apps across
2676            // all defined users.
2677            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2678                for (UserInfo user : sUserManager.getUsers(true)) {
2679                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2680                    applyFactoryDefaultBrowserLPw(user.id);
2681                    primeDomainVerificationsLPw(user.id);
2682                }
2683            }
2684
2685            // Prepare storage for system user really early during boot,
2686            // since core system apps like SettingsProvider and SystemUI
2687            // can't wait for user to start
2688            final int storageFlags;
2689            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2690                storageFlags = StorageManager.FLAG_STORAGE_DE;
2691            } else {
2692                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2693            }
2694            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2695                    storageFlags, true /* migrateAppData */);
2696
2697            // If this is first boot after an OTA, and a normal boot, then
2698            // we need to clear code cache directories.
2699            // Note that we do *not* clear the application profiles. These remain valid
2700            // across OTAs and are used to drive profile verification (post OTA) and
2701            // profile compilation (without waiting to collect a fresh set of profiles).
2702            if (mIsUpgrade && !onlyCore) {
2703                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2704                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2705                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2706                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2707                        // No apps are running this early, so no need to freeze
2708                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2709                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2710                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2711                    }
2712                }
2713                ver.fingerprint = Build.FINGERPRINT;
2714            }
2715
2716            checkDefaultBrowser();
2717
2718            // clear only after permissions and other defaults have been updated
2719            mExistingSystemPackages.clear();
2720            mPromoteSystemApps = false;
2721
2722            // All the changes are done during package scanning.
2723            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2724
2725            // can downgrade to reader
2726            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2727            mSettings.writeLPr();
2728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2729
2730            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2731            // early on (before the package manager declares itself as early) because other
2732            // components in the system server might ask for package contexts for these apps.
2733            //
2734            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2735            // (i.e, that the data partition is unavailable).
2736            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2737                long start = System.nanoTime();
2738                List<PackageParser.Package> coreApps = new ArrayList<>();
2739                for (PackageParser.Package pkg : mPackages.values()) {
2740                    if (pkg.coreApp) {
2741                        coreApps.add(pkg);
2742                    }
2743                }
2744
2745                int[] stats = performDexOptUpgrade(coreApps, false,
2746                        getCompilerFilterForReason(REASON_CORE_APP));
2747
2748                final int elapsedTimeSeconds =
2749                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2750                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2751
2752                if (DEBUG_DEXOPT) {
2753                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2754                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2755                }
2756
2757
2758                // TODO: Should we log these stats to tron too ?
2759                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2760                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2761                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2762                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2763            }
2764
2765            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2766                    SystemClock.uptimeMillis());
2767
2768            if (!mOnlyCore) {
2769                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2770                mRequiredInstallerPackage = getRequiredInstallerLPr();
2771                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2772                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2773                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2774                        mIntentFilterVerifierComponent);
2775                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2776                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2777                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2778                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2779            } else {
2780                mRequiredVerifierPackage = null;
2781                mRequiredInstallerPackage = null;
2782                mRequiredUninstallerPackage = null;
2783                mIntentFilterVerifierComponent = null;
2784                mIntentFilterVerifier = null;
2785                mServicesSystemSharedLibraryPackageName = null;
2786                mSharedSystemSharedLibraryPackageName = null;
2787            }
2788
2789            mInstallerService = new PackageInstallerService(context, this);
2790
2791            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2792            if (ephemeralResolverComponent != null) {
2793                if (DEBUG_EPHEMERAL) {
2794                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2795                }
2796                mEphemeralResolverConnection =
2797                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2798            } else {
2799                mEphemeralResolverConnection = null;
2800            }
2801            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2802            if (mEphemeralInstallerComponent != null) {
2803                if (DEBUG_EPHEMERAL) {
2804                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2805                }
2806                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2807            }
2808
2809            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2810
2811            // Read and update the usage of dex files.
2812            // Do this at the end of PM init so that all the packages have their
2813            // data directory reconciled.
2814            // At this point we know the code paths of the packages, so we can validate
2815            // the disk file and build the internal cache.
2816            // The usage file is expected to be small so loading and verifying it
2817            // should take a fairly small time compare to the other activities (e.g. package
2818            // scanning).
2819            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2820            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2821            for (int userId : currentUserIds) {
2822                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2823            }
2824            mDexManager.load(userPackages);
2825        } // synchronized (mPackages)
2826        } // synchronized (mInstallLock)
2827
2828        // Now after opening every single application zip, make sure they
2829        // are all flushed.  Not really needed, but keeps things nice and
2830        // tidy.
2831        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2832        Runtime.getRuntime().gc();
2833        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2834
2835        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2836        FallbackCategoryProvider.loadFallbacks();
2837        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2838
2839        // The initial scanning above does many calls into installd while
2840        // holding the mPackages lock, but we're mostly interested in yelling
2841        // once we have a booted system.
2842        mInstaller.setWarnIfHeld(mPackages);
2843
2844        // Expose private service for system components to use.
2845        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2846        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2847    }
2848
2849    private static File preparePackageParserCache(boolean isUpgrade) {
2850        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2851            return null;
2852        }
2853
2854        // Disable package parsing on eng builds to allow for faster incremental development.
2855        if ("eng".equals(Build.TYPE)) {
2856            return null;
2857        }
2858
2859        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2860            Slog.i(TAG, "Disabling package parser cache due to system property.");
2861            return null;
2862        }
2863
2864        // The base directory for the package parser cache lives under /data/system/.
2865        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2866                "package_cache");
2867        if (cacheBaseDir == null) {
2868            return null;
2869        }
2870
2871        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2872        // This also serves to "GC" unused entries when the package cache version changes (which
2873        // can only happen during upgrades).
2874        if (isUpgrade) {
2875            FileUtils.deleteContents(cacheBaseDir);
2876        }
2877
2878
2879        // Return the versioned package cache directory. This is something like
2880        // "/data/system/package_cache/1"
2881        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2882
2883        // The following is a workaround to aid development on non-numbered userdebug
2884        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2885        // the system partition is newer.
2886        //
2887        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2888        // that starts with "eng." to signify that this is an engineering build and not
2889        // destined for release.
2890        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2891            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2892
2893            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2894            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2895            // in general and should not be used for production changes. In this specific case,
2896            // we know that they will work.
2897            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2898            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2899                FileUtils.deleteContents(cacheBaseDir);
2900                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2901            }
2902        }
2903
2904        return cacheDir;
2905    }
2906
2907    @Override
2908    public boolean isFirstBoot() {
2909        return mFirstBoot;
2910    }
2911
2912    @Override
2913    public boolean isOnlyCoreApps() {
2914        return mOnlyCore;
2915    }
2916
2917    @Override
2918    public boolean isUpgrade() {
2919        return mIsUpgrade;
2920    }
2921
2922    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2923        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2924
2925        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2926                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2927                UserHandle.USER_SYSTEM);
2928        if (matches.size() == 1) {
2929            return matches.get(0).getComponentInfo().packageName;
2930        } else if (matches.size() == 0) {
2931            Log.e(TAG, "There should probably be a verifier, but, none were found");
2932            return null;
2933        }
2934        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2935    }
2936
2937    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2938        synchronized (mPackages) {
2939            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2940            if (libraryEntry == null) {
2941                throw new IllegalStateException("Missing required shared library:" + libraryName);
2942            }
2943            return libraryEntry.apk;
2944        }
2945    }
2946
2947    private @NonNull String getRequiredInstallerLPr() {
2948        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2949        intent.addCategory(Intent.CATEGORY_DEFAULT);
2950        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2951
2952        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2953                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2954                UserHandle.USER_SYSTEM);
2955        if (matches.size() == 1) {
2956            ResolveInfo resolveInfo = matches.get(0);
2957            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2958                throw new RuntimeException("The installer must be a privileged app");
2959            }
2960            return matches.get(0).getComponentInfo().packageName;
2961        } else {
2962            throw new RuntimeException("There must be exactly one installer; found " + matches);
2963        }
2964    }
2965
2966    private @NonNull String getRequiredUninstallerLPr() {
2967        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2968        intent.addCategory(Intent.CATEGORY_DEFAULT);
2969        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2970
2971        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2972                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2973                UserHandle.USER_SYSTEM);
2974        if (resolveInfo == null ||
2975                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2976            throw new RuntimeException("There must be exactly one uninstaller; found "
2977                    + resolveInfo);
2978        }
2979        return resolveInfo.getComponentInfo().packageName;
2980    }
2981
2982    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2983        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2984
2985        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2986                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2987                UserHandle.USER_SYSTEM);
2988        ResolveInfo best = null;
2989        final int N = matches.size();
2990        for (int i = 0; i < N; i++) {
2991            final ResolveInfo cur = matches.get(i);
2992            final String packageName = cur.getComponentInfo().packageName;
2993            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2994                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2995                continue;
2996            }
2997
2998            if (best == null || cur.priority > best.priority) {
2999                best = cur;
3000            }
3001        }
3002
3003        if (best != null) {
3004            return best.getComponentInfo().getComponentName();
3005        } else {
3006            throw new RuntimeException("There must be at least one intent filter verifier");
3007        }
3008    }
3009
3010    private @Nullable ComponentName getEphemeralResolverLPr() {
3011        final String[] packageArray =
3012                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3013        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3014            if (DEBUG_EPHEMERAL) {
3015                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3016            }
3017            return null;
3018        }
3019
3020        final int resolveFlags =
3021                MATCH_DIRECT_BOOT_AWARE
3022                | MATCH_DIRECT_BOOT_UNAWARE
3023                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3024        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3025        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3026                resolveFlags, UserHandle.USER_SYSTEM);
3027
3028        final int N = resolvers.size();
3029        if (N == 0) {
3030            if (DEBUG_EPHEMERAL) {
3031                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3032            }
3033            return null;
3034        }
3035
3036        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3037        for (int i = 0; i < N; i++) {
3038            final ResolveInfo info = resolvers.get(i);
3039
3040            if (info.serviceInfo == null) {
3041                continue;
3042            }
3043
3044            final String packageName = info.serviceInfo.packageName;
3045            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3046                if (DEBUG_EPHEMERAL) {
3047                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3048                            + " pkg: " + packageName + ", info:" + info);
3049                }
3050                continue;
3051            }
3052
3053            if (DEBUG_EPHEMERAL) {
3054                Slog.v(TAG, "Ephemeral resolver found;"
3055                        + " pkg: " + packageName + ", info:" + info);
3056            }
3057            return new ComponentName(packageName, info.serviceInfo.name);
3058        }
3059        if (DEBUG_EPHEMERAL) {
3060            Slog.v(TAG, "Ephemeral resolver NOT found");
3061        }
3062        return null;
3063    }
3064
3065    private @Nullable ComponentName getEphemeralInstallerLPr() {
3066        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3067        intent.addCategory(Intent.CATEGORY_DEFAULT);
3068        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3069
3070        final int resolveFlags =
3071                MATCH_DIRECT_BOOT_AWARE
3072                | MATCH_DIRECT_BOOT_UNAWARE
3073                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3074        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3075                resolveFlags, UserHandle.USER_SYSTEM);
3076        Iterator<ResolveInfo> iter = matches.iterator();
3077        while (iter.hasNext()) {
3078            final ResolveInfo rInfo = iter.next();
3079            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3080            if (ps != null) {
3081                final PermissionsState permissionsState = ps.getPermissionsState();
3082                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3083                    continue;
3084                }
3085            }
3086            iter.remove();
3087        }
3088        if (matches.size() == 0) {
3089            return null;
3090        } else if (matches.size() == 1) {
3091            return matches.get(0).getComponentInfo().getComponentName();
3092        } else {
3093            throw new RuntimeException(
3094                    "There must be at most one ephemeral installer; found " + matches);
3095        }
3096    }
3097
3098    private void primeDomainVerificationsLPw(int userId) {
3099        if (DEBUG_DOMAIN_VERIFICATION) {
3100            Slog.d(TAG, "Priming domain verifications in user " + userId);
3101        }
3102
3103        SystemConfig systemConfig = SystemConfig.getInstance();
3104        ArraySet<String> packages = systemConfig.getLinkedApps();
3105
3106        for (String packageName : packages) {
3107            PackageParser.Package pkg = mPackages.get(packageName);
3108            if (pkg != null) {
3109                if (!pkg.isSystemApp()) {
3110                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3111                    continue;
3112                }
3113
3114                ArraySet<String> domains = null;
3115                for (PackageParser.Activity a : pkg.activities) {
3116                    for (ActivityIntentInfo filter : a.intents) {
3117                        if (hasValidDomains(filter)) {
3118                            if (domains == null) {
3119                                domains = new ArraySet<String>();
3120                            }
3121                            domains.addAll(filter.getHostsList());
3122                        }
3123                    }
3124                }
3125
3126                if (domains != null && domains.size() > 0) {
3127                    if (DEBUG_DOMAIN_VERIFICATION) {
3128                        Slog.v(TAG, "      + " + packageName);
3129                    }
3130                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3131                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3132                    // and then 'always' in the per-user state actually used for intent resolution.
3133                    final IntentFilterVerificationInfo ivi;
3134                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3135                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3136                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3137                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3138                } else {
3139                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3140                            + "' does not handle web links");
3141                }
3142            } else {
3143                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3144            }
3145        }
3146
3147        scheduleWritePackageRestrictionsLocked(userId);
3148        scheduleWriteSettingsLocked();
3149    }
3150
3151    private void applyFactoryDefaultBrowserLPw(int userId) {
3152        // The default browser app's package name is stored in a string resource,
3153        // with a product-specific overlay used for vendor customization.
3154        String browserPkg = mContext.getResources().getString(
3155                com.android.internal.R.string.default_browser);
3156        if (!TextUtils.isEmpty(browserPkg)) {
3157            // non-empty string => required to be a known package
3158            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3159            if (ps == null) {
3160                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3161                browserPkg = null;
3162            } else {
3163                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3164            }
3165        }
3166
3167        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3168        // default.  If there's more than one, just leave everything alone.
3169        if (browserPkg == null) {
3170            calculateDefaultBrowserLPw(userId);
3171        }
3172    }
3173
3174    private void calculateDefaultBrowserLPw(int userId) {
3175        List<String> allBrowsers = resolveAllBrowserApps(userId);
3176        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3177        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3178    }
3179
3180    private List<String> resolveAllBrowserApps(int userId) {
3181        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3182        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3183                PackageManager.MATCH_ALL, userId);
3184
3185        final int count = list.size();
3186        List<String> result = new ArrayList<String>(count);
3187        for (int i=0; i<count; i++) {
3188            ResolveInfo info = list.get(i);
3189            if (info.activityInfo == null
3190                    || !info.handleAllWebDataURI
3191                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3192                    || result.contains(info.activityInfo.packageName)) {
3193                continue;
3194            }
3195            result.add(info.activityInfo.packageName);
3196        }
3197
3198        return result;
3199    }
3200
3201    private boolean packageIsBrowser(String packageName, int userId) {
3202        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3203                PackageManager.MATCH_ALL, userId);
3204        final int N = list.size();
3205        for (int i = 0; i < N; i++) {
3206            ResolveInfo info = list.get(i);
3207            if (packageName.equals(info.activityInfo.packageName)) {
3208                return true;
3209            }
3210        }
3211        return false;
3212    }
3213
3214    private void checkDefaultBrowser() {
3215        final int myUserId = UserHandle.myUserId();
3216        final String packageName = getDefaultBrowserPackageName(myUserId);
3217        if (packageName != null) {
3218            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3219            if (info == null) {
3220                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3221                synchronized (mPackages) {
3222                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3223                }
3224            }
3225        }
3226    }
3227
3228    @Override
3229    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3230            throws RemoteException {
3231        try {
3232            return super.onTransact(code, data, reply, flags);
3233        } catch (RuntimeException e) {
3234            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3235                Slog.wtf(TAG, "Package Manager Crash", e);
3236            }
3237            throw e;
3238        }
3239    }
3240
3241    static int[] appendInts(int[] cur, int[] add) {
3242        if (add == null) return cur;
3243        if (cur == null) return add;
3244        final int N = add.length;
3245        for (int i=0; i<N; i++) {
3246            cur = appendInt(cur, add[i]);
3247        }
3248        return cur;
3249    }
3250
3251    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3252        if (!sUserManager.exists(userId)) return null;
3253        if (ps == null) {
3254            return null;
3255        }
3256        final PackageParser.Package p = ps.pkg;
3257        if (p == null) {
3258            return null;
3259        }
3260
3261        final PermissionsState permissionsState = ps.getPermissionsState();
3262
3263        // Compute GIDs only if requested
3264        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3265                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3266        // Compute granted permissions only if package has requested permissions
3267        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3268                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3269        final PackageUserState state = ps.readUserState(userId);
3270
3271        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3272                && ps.isSystem()) {
3273            flags |= MATCH_ANY_USER;
3274        }
3275
3276        return PackageParser.generatePackageInfo(p, gids, flags,
3277                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3278    }
3279
3280    @Override
3281    public void checkPackageStartable(String packageName, int userId) {
3282        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3283
3284        synchronized (mPackages) {
3285            final PackageSetting ps = mSettings.mPackages.get(packageName);
3286            if (ps == null) {
3287                throw new SecurityException("Package " + packageName + " was not found!");
3288            }
3289
3290            if (!ps.getInstalled(userId)) {
3291                throw new SecurityException(
3292                        "Package " + packageName + " was not installed for user " + userId + "!");
3293            }
3294
3295            if (mSafeMode && !ps.isSystem()) {
3296                throw new SecurityException("Package " + packageName + " not a system app!");
3297            }
3298
3299            if (mFrozenPackages.contains(packageName)) {
3300                throw new SecurityException("Package " + packageName + " is currently frozen!");
3301            }
3302
3303            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3304                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3305                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3306            }
3307        }
3308    }
3309
3310    @Override
3311    public boolean isPackageAvailable(String packageName, int userId) {
3312        if (!sUserManager.exists(userId)) return false;
3313        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3314                false /* requireFullPermission */, false /* checkShell */, "is package available");
3315        synchronized (mPackages) {
3316            PackageParser.Package p = mPackages.get(packageName);
3317            if (p != null) {
3318                final PackageSetting ps = (PackageSetting) p.mExtras;
3319                if (ps != null) {
3320                    final PackageUserState state = ps.readUserState(userId);
3321                    if (state != null) {
3322                        return PackageParser.isAvailable(state);
3323                    }
3324                }
3325            }
3326        }
3327        return false;
3328    }
3329
3330    @Override
3331    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3332        if (!sUserManager.exists(userId)) return null;
3333        flags = updateFlagsForPackage(flags, userId, packageName);
3334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3335                false /* requireFullPermission */, false /* checkShell */, "get package info");
3336
3337        // reader
3338        synchronized (mPackages) {
3339            // Normalize package name to hanlde renamed packages
3340            packageName = normalizePackageNameLPr(packageName);
3341
3342            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3343            PackageParser.Package p = null;
3344            if (matchFactoryOnly) {
3345                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3346                if (ps != null) {
3347                    return generatePackageInfo(ps, flags, userId);
3348                }
3349            }
3350            if (p == null) {
3351                p = mPackages.get(packageName);
3352                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3353                    return null;
3354                }
3355            }
3356            if (DEBUG_PACKAGE_INFO)
3357                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3358            if (p != null) {
3359                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3360            }
3361            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3362                final PackageSetting ps = mSettings.mPackages.get(packageName);
3363                return generatePackageInfo(ps, flags, userId);
3364            }
3365        }
3366        return null;
3367    }
3368
3369    @Override
3370    public String[] currentToCanonicalPackageNames(String[] names) {
3371        String[] out = new String[names.length];
3372        // reader
3373        synchronized (mPackages) {
3374            for (int i=names.length-1; i>=0; i--) {
3375                PackageSetting ps = mSettings.mPackages.get(names[i]);
3376                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3377            }
3378        }
3379        return out;
3380    }
3381
3382    @Override
3383    public String[] canonicalToCurrentPackageNames(String[] names) {
3384        String[] out = new String[names.length];
3385        // reader
3386        synchronized (mPackages) {
3387            for (int i=names.length-1; i>=0; i--) {
3388                String cur = mSettings.getRenamedPackageLPr(names[i]);
3389                out[i] = cur != null ? cur : names[i];
3390            }
3391        }
3392        return out;
3393    }
3394
3395    @Override
3396    public int getPackageUid(String packageName, int flags, int userId) {
3397        if (!sUserManager.exists(userId)) return -1;
3398        flags = updateFlagsForPackage(flags, userId, packageName);
3399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3400                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3401
3402        // reader
3403        synchronized (mPackages) {
3404            final PackageParser.Package p = mPackages.get(packageName);
3405            if (p != null && p.isMatch(flags)) {
3406                return UserHandle.getUid(userId, p.applicationInfo.uid);
3407            }
3408            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3409                final PackageSetting ps = mSettings.mPackages.get(packageName);
3410                if (ps != null && ps.isMatch(flags)) {
3411                    return UserHandle.getUid(userId, ps.appId);
3412                }
3413            }
3414        }
3415
3416        return -1;
3417    }
3418
3419    @Override
3420    public int[] getPackageGids(String packageName, int flags, int userId) {
3421        if (!sUserManager.exists(userId)) return null;
3422        flags = updateFlagsForPackage(flags, userId, packageName);
3423        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3424                false /* requireFullPermission */, false /* checkShell */,
3425                "getPackageGids");
3426
3427        // reader
3428        synchronized (mPackages) {
3429            final PackageParser.Package p = mPackages.get(packageName);
3430            if (p != null && p.isMatch(flags)) {
3431                PackageSetting ps = (PackageSetting) p.mExtras;
3432                // TODO: Shouldn't this be checking for package installed state for userId and
3433                // return null?
3434                return ps.getPermissionsState().computeGids(userId);
3435            }
3436            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3437                final PackageSetting ps = mSettings.mPackages.get(packageName);
3438                if (ps != null && ps.isMatch(flags)) {
3439                    return ps.getPermissionsState().computeGids(userId);
3440                }
3441            }
3442        }
3443
3444        return null;
3445    }
3446
3447    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3448        if (bp.perm != null) {
3449            return PackageParser.generatePermissionInfo(bp.perm, flags);
3450        }
3451        PermissionInfo pi = new PermissionInfo();
3452        pi.name = bp.name;
3453        pi.packageName = bp.sourcePackage;
3454        pi.nonLocalizedLabel = bp.name;
3455        pi.protectionLevel = bp.protectionLevel;
3456        return pi;
3457    }
3458
3459    @Override
3460    public PermissionInfo getPermissionInfo(String name, int flags) {
3461        // reader
3462        synchronized (mPackages) {
3463            final BasePermission p = mSettings.mPermissions.get(name);
3464            if (p != null) {
3465                return generatePermissionInfo(p, flags);
3466            }
3467            return null;
3468        }
3469    }
3470
3471    @Override
3472    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3473            int flags) {
3474        // reader
3475        synchronized (mPackages) {
3476            if (group != null && !mPermissionGroups.containsKey(group)) {
3477                // This is thrown as NameNotFoundException
3478                return null;
3479            }
3480
3481            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3482            for (BasePermission p : mSettings.mPermissions.values()) {
3483                if (group == null) {
3484                    if (p.perm == null || p.perm.info.group == null) {
3485                        out.add(generatePermissionInfo(p, flags));
3486                    }
3487                } else {
3488                    if (p.perm != null && group.equals(p.perm.info.group)) {
3489                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3490                    }
3491                }
3492            }
3493            return new ParceledListSlice<>(out);
3494        }
3495    }
3496
3497    @Override
3498    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3499        // reader
3500        synchronized (mPackages) {
3501            return PackageParser.generatePermissionGroupInfo(
3502                    mPermissionGroups.get(name), flags);
3503        }
3504    }
3505
3506    @Override
3507    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3508        // reader
3509        synchronized (mPackages) {
3510            final int N = mPermissionGroups.size();
3511            ArrayList<PermissionGroupInfo> out
3512                    = new ArrayList<PermissionGroupInfo>(N);
3513            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3514                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3515            }
3516            return new ParceledListSlice<>(out);
3517        }
3518    }
3519
3520    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3521            int userId) {
3522        if (!sUserManager.exists(userId)) return null;
3523        PackageSetting ps = mSettings.mPackages.get(packageName);
3524        if (ps != null) {
3525            if (ps.pkg == null) {
3526                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3527                if (pInfo != null) {
3528                    return pInfo.applicationInfo;
3529                }
3530                return null;
3531            }
3532            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3533                    ps.readUserState(userId), userId);
3534        }
3535        return null;
3536    }
3537
3538    @Override
3539    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3540        if (!sUserManager.exists(userId)) return null;
3541        flags = updateFlagsForApplication(flags, userId, packageName);
3542        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3543                false /* requireFullPermission */, false /* checkShell */, "get application info");
3544
3545        // writer
3546        synchronized (mPackages) {
3547            // Normalize package name to hanlde renamed packages
3548            packageName = normalizePackageNameLPr(packageName);
3549
3550            PackageParser.Package p = mPackages.get(packageName);
3551            if (DEBUG_PACKAGE_INFO) Log.v(
3552                    TAG, "getApplicationInfo " + packageName
3553                    + ": " + p);
3554            if (p != null) {
3555                PackageSetting ps = mSettings.mPackages.get(packageName);
3556                if (ps == null) return null;
3557                // Note: isEnabledLP() does not apply here - always return info
3558                return PackageParser.generateApplicationInfo(
3559                        p, flags, ps.readUserState(userId), userId);
3560            }
3561            if ("android".equals(packageName)||"system".equals(packageName)) {
3562                return mAndroidApplication;
3563            }
3564            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3565                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3566            }
3567        }
3568        return null;
3569    }
3570
3571    private String normalizePackageNameLPr(String packageName) {
3572        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3573        return normalizedPackageName != null ? normalizedPackageName : packageName;
3574    }
3575
3576    @Override
3577    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3578            final IPackageDataObserver observer) {
3579        mContext.enforceCallingOrSelfPermission(
3580                android.Manifest.permission.CLEAR_APP_CACHE, null);
3581        // Queue up an async operation since clearing cache may take a little while.
3582        mHandler.post(new Runnable() {
3583            public void run() {
3584                mHandler.removeCallbacks(this);
3585                boolean success = true;
3586                synchronized (mInstallLock) {
3587                    try {
3588                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3589                    } catch (InstallerException e) {
3590                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3591                        success = false;
3592                    }
3593                }
3594                if (observer != null) {
3595                    try {
3596                        observer.onRemoveCompleted(null, success);
3597                    } catch (RemoteException e) {
3598                        Slog.w(TAG, "RemoveException when invoking call back");
3599                    }
3600                }
3601            }
3602        });
3603    }
3604
3605    @Override
3606    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3607            final IntentSender pi) {
3608        mContext.enforceCallingOrSelfPermission(
3609                android.Manifest.permission.CLEAR_APP_CACHE, null);
3610        // Queue up an async operation since clearing cache may take a little while.
3611        mHandler.post(new Runnable() {
3612            public void run() {
3613                mHandler.removeCallbacks(this);
3614                boolean success = true;
3615                synchronized (mInstallLock) {
3616                    try {
3617                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3618                    } catch (InstallerException e) {
3619                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3620                        success = false;
3621                    }
3622                }
3623                if(pi != null) {
3624                    try {
3625                        // Callback via pending intent
3626                        int code = success ? 1 : 0;
3627                        pi.sendIntent(null, code, null,
3628                                null, null);
3629                    } catch (SendIntentException e1) {
3630                        Slog.i(TAG, "Failed to send pending intent");
3631                    }
3632                }
3633            }
3634        });
3635    }
3636
3637    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3638        synchronized (mInstallLock) {
3639            try {
3640                mInstaller.freeCache(volumeUuid, freeStorageSize);
3641            } catch (InstallerException e) {
3642                throw new IOException("Failed to free enough space", e);
3643            }
3644        }
3645    }
3646
3647    /**
3648     * Update given flags based on encryption status of current user.
3649     */
3650    private int updateFlags(int flags, int userId) {
3651        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3652                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3653            // Caller expressed an explicit opinion about what encryption
3654            // aware/unaware components they want to see, so fall through and
3655            // give them what they want
3656        } else {
3657            // Caller expressed no opinion, so match based on user state
3658            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3659                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3660            } else {
3661                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3662            }
3663        }
3664        return flags;
3665    }
3666
3667    private UserManagerInternal getUserManagerInternal() {
3668        if (mUserManagerInternal == null) {
3669            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3670        }
3671        return mUserManagerInternal;
3672    }
3673
3674    /**
3675     * Update given flags when being used to request {@link PackageInfo}.
3676     */
3677    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3678        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3679        boolean triaged = true;
3680        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3681                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3682            // Caller is asking for component details, so they'd better be
3683            // asking for specific encryption matching behavior, or be triaged
3684            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3685                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3686                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3687                triaged = false;
3688            }
3689        }
3690        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3691                | PackageManager.MATCH_SYSTEM_ONLY
3692                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3693            triaged = false;
3694        }
3695        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3696            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3697                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3698                    + Debug.getCallers(5));
3699        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3700                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3701            // If the caller wants all packages and has a restricted profile associated with it,
3702            // then match all users. This is to make sure that launchers that need to access work
3703            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3704            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3705            flags |= PackageManager.MATCH_ANY_USER;
3706        }
3707        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3708            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3709                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3710        }
3711        return updateFlags(flags, userId);
3712    }
3713
3714    /**
3715     * Update given flags when being used to request {@link ApplicationInfo}.
3716     */
3717    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3718        return updateFlagsForPackage(flags, userId, cookie);
3719    }
3720
3721    /**
3722     * Update given flags when being used to request {@link ComponentInfo}.
3723     */
3724    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3725        if (cookie instanceof Intent) {
3726            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3727                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3728            }
3729        }
3730
3731        boolean triaged = true;
3732        // Caller is asking for component details, so they'd better be
3733        // asking for specific encryption matching behavior, or be triaged
3734        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3735                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3736                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3737            triaged = false;
3738        }
3739        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3740            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3741                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3742        }
3743
3744        return updateFlags(flags, userId);
3745    }
3746
3747    /**
3748     * Update given flags when being used to request {@link ResolveInfo}.
3749     */
3750    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3751        // Safe mode means we shouldn't match any third-party components
3752        if (mSafeMode) {
3753            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3754        }
3755        final int callingUid = Binder.getCallingUid();
3756        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3757            // The system sees all components
3758            flags |= PackageManager.MATCH_EPHEMERAL;
3759        } else if (getEphemeralPackageName(callingUid) != null) {
3760            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3761            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3762            flags |= PackageManager.MATCH_EPHEMERAL;
3763        } else {
3764            // Otherwise, prevent leaking ephemeral components
3765            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3766            flags &= ~PackageManager.MATCH_EPHEMERAL;
3767        }
3768        return updateFlagsForComponent(flags, userId, cookie);
3769    }
3770
3771    @Override
3772    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3773        if (!sUserManager.exists(userId)) return null;
3774        flags = updateFlagsForComponent(flags, userId, component);
3775        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3776                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3777        synchronized (mPackages) {
3778            PackageParser.Activity a = mActivities.mActivities.get(component);
3779
3780            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3781            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3783                if (ps == null) return null;
3784                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3785                        userId);
3786            }
3787            if (mResolveComponentName.equals(component)) {
3788                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3789                        new PackageUserState(), userId);
3790            }
3791        }
3792        return null;
3793    }
3794
3795    @Override
3796    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3797            String resolvedType) {
3798        synchronized (mPackages) {
3799            if (component.equals(mResolveComponentName)) {
3800                // The resolver supports EVERYTHING!
3801                return true;
3802            }
3803            PackageParser.Activity a = mActivities.mActivities.get(component);
3804            if (a == null) {
3805                return false;
3806            }
3807            for (int i=0; i<a.intents.size(); i++) {
3808                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3809                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3810                    return true;
3811                }
3812            }
3813            return false;
3814        }
3815    }
3816
3817    @Override
3818    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3819        if (!sUserManager.exists(userId)) return null;
3820        flags = updateFlagsForComponent(flags, userId, component);
3821        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3822                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3823        synchronized (mPackages) {
3824            PackageParser.Activity a = mReceivers.mActivities.get(component);
3825            if (DEBUG_PACKAGE_INFO) Log.v(
3826                TAG, "getReceiverInfo " + component + ": " + a);
3827            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3828                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3829                if (ps == null) return null;
3830                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3831                        userId);
3832            }
3833        }
3834        return null;
3835    }
3836
3837    @Override
3838    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3839        if (!sUserManager.exists(userId)) return null;
3840        flags = updateFlagsForComponent(flags, userId, component);
3841        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3842                false /* requireFullPermission */, false /* checkShell */, "get service info");
3843        synchronized (mPackages) {
3844            PackageParser.Service s = mServices.mServices.get(component);
3845            if (DEBUG_PACKAGE_INFO) Log.v(
3846                TAG, "getServiceInfo " + component + ": " + s);
3847            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3848                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3849                if (ps == null) return null;
3850                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3851                        userId);
3852            }
3853        }
3854        return null;
3855    }
3856
3857    @Override
3858    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3859        if (!sUserManager.exists(userId)) return null;
3860        flags = updateFlagsForComponent(flags, userId, component);
3861        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3862                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3863        synchronized (mPackages) {
3864            PackageParser.Provider p = mProviders.mProviders.get(component);
3865            if (DEBUG_PACKAGE_INFO) Log.v(
3866                TAG, "getProviderInfo " + component + ": " + p);
3867            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3868                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3869                if (ps == null) return null;
3870                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3871                        userId);
3872            }
3873        }
3874        return null;
3875    }
3876
3877    @Override
3878    public String[] getSystemSharedLibraryNames() {
3879        Set<String> libSet;
3880        synchronized (mPackages) {
3881            libSet = mSharedLibraries.keySet();
3882            int size = libSet.size();
3883            if (size > 0) {
3884                String[] libs = new String[size];
3885                libSet.toArray(libs);
3886                return libs;
3887            }
3888        }
3889        return null;
3890    }
3891
3892    @Override
3893    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3894        synchronized (mPackages) {
3895            return mServicesSystemSharedLibraryPackageName;
3896        }
3897    }
3898
3899    @Override
3900    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3901        synchronized (mPackages) {
3902            return mSharedSystemSharedLibraryPackageName;
3903        }
3904    }
3905
3906    @Override
3907    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3908        synchronized (mPackages) {
3909            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3910
3911            final FeatureInfo fi = new FeatureInfo();
3912            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3913                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3914            res.add(fi);
3915
3916            return new ParceledListSlice<>(res);
3917        }
3918    }
3919
3920    @Override
3921    public boolean hasSystemFeature(String name, int version) {
3922        synchronized (mPackages) {
3923            final FeatureInfo feat = mAvailableFeatures.get(name);
3924            if (feat == null) {
3925                return false;
3926            } else {
3927                return feat.version >= version;
3928            }
3929        }
3930    }
3931
3932    @Override
3933    public int checkPermission(String permName, String pkgName, int userId) {
3934        if (!sUserManager.exists(userId)) {
3935            return PackageManager.PERMISSION_DENIED;
3936        }
3937
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(pkgName);
3940            if (p != null && p.mExtras != null) {
3941                final PackageSetting ps = (PackageSetting) p.mExtras;
3942                final PermissionsState permissionsState = ps.getPermissionsState();
3943                if (permissionsState.hasPermission(permName, userId)) {
3944                    return PackageManager.PERMISSION_GRANTED;
3945                }
3946                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3947                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3948                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3949                    return PackageManager.PERMISSION_GRANTED;
3950                }
3951            }
3952        }
3953
3954        return PackageManager.PERMISSION_DENIED;
3955    }
3956
3957    @Override
3958    public int checkUidPermission(String permName, int uid) {
3959        final int userId = UserHandle.getUserId(uid);
3960
3961        if (!sUserManager.exists(userId)) {
3962            return PackageManager.PERMISSION_DENIED;
3963        }
3964
3965        synchronized (mPackages) {
3966            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3967            if (obj != null) {
3968                final SettingBase ps = (SettingBase) obj;
3969                final PermissionsState permissionsState = ps.getPermissionsState();
3970                if (permissionsState.hasPermission(permName, userId)) {
3971                    return PackageManager.PERMISSION_GRANTED;
3972                }
3973                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3974                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3975                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3976                    return PackageManager.PERMISSION_GRANTED;
3977                }
3978            } else {
3979                ArraySet<String> perms = mSystemPermissions.get(uid);
3980                if (perms != null) {
3981                    if (perms.contains(permName)) {
3982                        return PackageManager.PERMISSION_GRANTED;
3983                    }
3984                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3985                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3986                        return PackageManager.PERMISSION_GRANTED;
3987                    }
3988                }
3989            }
3990        }
3991
3992        return PackageManager.PERMISSION_DENIED;
3993    }
3994
3995    @Override
3996    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3997        if (UserHandle.getCallingUserId() != userId) {
3998            mContext.enforceCallingPermission(
3999                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4000                    "isPermissionRevokedByPolicy for user " + userId);
4001        }
4002
4003        if (checkPermission(permission, packageName, userId)
4004                == PackageManager.PERMISSION_GRANTED) {
4005            return false;
4006        }
4007
4008        final long identity = Binder.clearCallingIdentity();
4009        try {
4010            final int flags = getPermissionFlags(permission, packageName, userId);
4011            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4012        } finally {
4013            Binder.restoreCallingIdentity(identity);
4014        }
4015    }
4016
4017    @Override
4018    public String getPermissionControllerPackageName() {
4019        synchronized (mPackages) {
4020            return mRequiredInstallerPackage;
4021        }
4022    }
4023
4024    /**
4025     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4026     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4027     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4028     * @param message the message to log on security exception
4029     */
4030    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4031            boolean checkShell, String message) {
4032        if (userId < 0) {
4033            throw new IllegalArgumentException("Invalid userId " + userId);
4034        }
4035        if (checkShell) {
4036            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4037        }
4038        if (userId == UserHandle.getUserId(callingUid)) return;
4039        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4040            if (requireFullPermission) {
4041                mContext.enforceCallingOrSelfPermission(
4042                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4043            } else {
4044                try {
4045                    mContext.enforceCallingOrSelfPermission(
4046                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4047                } catch (SecurityException se) {
4048                    mContext.enforceCallingOrSelfPermission(
4049                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4050                }
4051            }
4052        }
4053    }
4054
4055    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4056        if (callingUid == Process.SHELL_UID) {
4057            if (userHandle >= 0
4058                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4059                throw new SecurityException("Shell does not have permission to access user "
4060                        + userHandle);
4061            } else if (userHandle < 0) {
4062                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4063                        + Debug.getCallers(3));
4064            }
4065        }
4066    }
4067
4068    private BasePermission findPermissionTreeLP(String permName) {
4069        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4070            if (permName.startsWith(bp.name) &&
4071                    permName.length() > bp.name.length() &&
4072                    permName.charAt(bp.name.length()) == '.') {
4073                return bp;
4074            }
4075        }
4076        return null;
4077    }
4078
4079    private BasePermission checkPermissionTreeLP(String permName) {
4080        if (permName != null) {
4081            BasePermission bp = findPermissionTreeLP(permName);
4082            if (bp != null) {
4083                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4084                    return bp;
4085                }
4086                throw new SecurityException("Calling uid "
4087                        + Binder.getCallingUid()
4088                        + " is not allowed to add to permission tree "
4089                        + bp.name + " owned by uid " + bp.uid);
4090            }
4091        }
4092        throw new SecurityException("No permission tree found for " + permName);
4093    }
4094
4095    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4096        if (s1 == null) {
4097            return s2 == null;
4098        }
4099        if (s2 == null) {
4100            return false;
4101        }
4102        if (s1.getClass() != s2.getClass()) {
4103            return false;
4104        }
4105        return s1.equals(s2);
4106    }
4107
4108    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4109        if (pi1.icon != pi2.icon) return false;
4110        if (pi1.logo != pi2.logo) return false;
4111        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4112        if (!compareStrings(pi1.name, pi2.name)) return false;
4113        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4114        // We'll take care of setting this one.
4115        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4116        // These are not currently stored in settings.
4117        //if (!compareStrings(pi1.group, pi2.group)) return false;
4118        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4119        //if (pi1.labelRes != pi2.labelRes) return false;
4120        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4121        return true;
4122    }
4123
4124    int permissionInfoFootprint(PermissionInfo info) {
4125        int size = info.name.length();
4126        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4127        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4128        return size;
4129    }
4130
4131    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4132        int size = 0;
4133        for (BasePermission perm : mSettings.mPermissions.values()) {
4134            if (perm.uid == tree.uid) {
4135                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4136            }
4137        }
4138        return size;
4139    }
4140
4141    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4142        // We calculate the max size of permissions defined by this uid and throw
4143        // if that plus the size of 'info' would exceed our stated maximum.
4144        if (tree.uid != Process.SYSTEM_UID) {
4145            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4146            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4147                throw new SecurityException("Permission tree size cap exceeded");
4148            }
4149        }
4150    }
4151
4152    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4153        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4154            throw new SecurityException("Label must be specified in permission");
4155        }
4156        BasePermission tree = checkPermissionTreeLP(info.name);
4157        BasePermission bp = mSettings.mPermissions.get(info.name);
4158        boolean added = bp == null;
4159        boolean changed = true;
4160        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4161        if (added) {
4162            enforcePermissionCapLocked(info, tree);
4163            bp = new BasePermission(info.name, tree.sourcePackage,
4164                    BasePermission.TYPE_DYNAMIC);
4165        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4166            throw new SecurityException(
4167                    "Not allowed to modify non-dynamic permission "
4168                    + info.name);
4169        } else {
4170            if (bp.protectionLevel == fixedLevel
4171                    && bp.perm.owner.equals(tree.perm.owner)
4172                    && bp.uid == tree.uid
4173                    && comparePermissionInfos(bp.perm.info, info)) {
4174                changed = false;
4175            }
4176        }
4177        bp.protectionLevel = fixedLevel;
4178        info = new PermissionInfo(info);
4179        info.protectionLevel = fixedLevel;
4180        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4181        bp.perm.info.packageName = tree.perm.info.packageName;
4182        bp.uid = tree.uid;
4183        if (added) {
4184            mSettings.mPermissions.put(info.name, bp);
4185        }
4186        if (changed) {
4187            if (!async) {
4188                mSettings.writeLPr();
4189            } else {
4190                scheduleWriteSettingsLocked();
4191            }
4192        }
4193        return added;
4194    }
4195
4196    @Override
4197    public boolean addPermission(PermissionInfo info) {
4198        synchronized (mPackages) {
4199            return addPermissionLocked(info, false);
4200        }
4201    }
4202
4203    @Override
4204    public boolean addPermissionAsync(PermissionInfo info) {
4205        synchronized (mPackages) {
4206            return addPermissionLocked(info, true);
4207        }
4208    }
4209
4210    @Override
4211    public void removePermission(String name) {
4212        synchronized (mPackages) {
4213            checkPermissionTreeLP(name);
4214            BasePermission bp = mSettings.mPermissions.get(name);
4215            if (bp != null) {
4216                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4217                    throw new SecurityException(
4218                            "Not allowed to modify non-dynamic permission "
4219                            + name);
4220                }
4221                mSettings.mPermissions.remove(name);
4222                mSettings.writeLPr();
4223            }
4224        }
4225    }
4226
4227    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4228            BasePermission bp) {
4229        int index = pkg.requestedPermissions.indexOf(bp.name);
4230        if (index == -1) {
4231            throw new SecurityException("Package " + pkg.packageName
4232                    + " has not requested permission " + bp.name);
4233        }
4234        if (!bp.isRuntime() && !bp.isDevelopment()) {
4235            throw new SecurityException("Permission " + bp.name
4236                    + " is not a changeable permission type");
4237        }
4238    }
4239
4240    @Override
4241    public void grantRuntimePermission(String packageName, String name, final int userId) {
4242        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4243    }
4244
4245    private void grantRuntimePermission(String packageName, String name, final int userId,
4246            boolean overridePolicy) {
4247        if (!sUserManager.exists(userId)) {
4248            Log.e(TAG, "No such user:" + userId);
4249            return;
4250        }
4251
4252        mContext.enforceCallingOrSelfPermission(
4253                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4254                "grantRuntimePermission");
4255
4256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4257                true /* requireFullPermission */, true /* checkShell */,
4258                "grantRuntimePermission");
4259
4260        final int uid;
4261        final SettingBase sb;
4262
4263        synchronized (mPackages) {
4264            final PackageParser.Package pkg = mPackages.get(packageName);
4265            if (pkg == null) {
4266                throw new IllegalArgumentException("Unknown package: " + packageName);
4267            }
4268
4269            final BasePermission bp = mSettings.mPermissions.get(name);
4270            if (bp == null) {
4271                throw new IllegalArgumentException("Unknown permission: " + name);
4272            }
4273
4274            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4275
4276            // If a permission review is required for legacy apps we represent
4277            // their permissions as always granted runtime ones since we need
4278            // to keep the review required permission flag per user while an
4279            // install permission's state is shared across all users.
4280            if (mPermissionReviewRequired
4281                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4282                    && bp.isRuntime()) {
4283                return;
4284            }
4285
4286            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4287            sb = (SettingBase) pkg.mExtras;
4288            if (sb == null) {
4289                throw new IllegalArgumentException("Unknown package: " + packageName);
4290            }
4291
4292            final PermissionsState permissionsState = sb.getPermissionsState();
4293
4294            final int flags = permissionsState.getPermissionFlags(name, userId);
4295            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4296                throw new SecurityException("Cannot grant system fixed permission "
4297                        + name + " for package " + packageName);
4298            }
4299            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4300                throw new SecurityException("Cannot grant policy fixed permission "
4301                        + name + " for package " + packageName);
4302            }
4303
4304            if (bp.isDevelopment()) {
4305                // Development permissions must be handled specially, since they are not
4306                // normal runtime permissions.  For now they apply to all users.
4307                if (permissionsState.grantInstallPermission(bp) !=
4308                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4309                    scheduleWriteSettingsLocked();
4310                }
4311                return;
4312            }
4313
4314            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4315                throw new SecurityException("Cannot grant non-ephemeral permission"
4316                        + name + " for package " + packageName);
4317            }
4318
4319            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4320                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4321                return;
4322            }
4323
4324            final int result = permissionsState.grantRuntimePermission(bp, userId);
4325            switch (result) {
4326                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4327                    return;
4328                }
4329
4330                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4331                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4332                    mHandler.post(new Runnable() {
4333                        @Override
4334                        public void run() {
4335                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4336                        }
4337                    });
4338                }
4339                break;
4340            }
4341
4342            if (bp.isRuntime()) {
4343                logPermissionGranted(mContext, name, packageName);
4344            }
4345
4346            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4347
4348            // Not critical if that is lost - app has to request again.
4349            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4350        }
4351
4352        // Only need to do this if user is initialized. Otherwise it's a new user
4353        // and there are no processes running as the user yet and there's no need
4354        // to make an expensive call to remount processes for the changed permissions.
4355        if (READ_EXTERNAL_STORAGE.equals(name)
4356                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4357            final long token = Binder.clearCallingIdentity();
4358            try {
4359                if (sUserManager.isInitialized(userId)) {
4360                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4361                            StorageManagerInternal.class);
4362                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4363                }
4364            } finally {
4365                Binder.restoreCallingIdentity(token);
4366            }
4367        }
4368    }
4369
4370    @Override
4371    public void revokeRuntimePermission(String packageName, String name, int userId) {
4372        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4373    }
4374
4375    private void revokeRuntimePermission(String packageName, String name, int userId,
4376            boolean overridePolicy) {
4377        if (!sUserManager.exists(userId)) {
4378            Log.e(TAG, "No such user:" + userId);
4379            return;
4380        }
4381
4382        mContext.enforceCallingOrSelfPermission(
4383                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4384                "revokeRuntimePermission");
4385
4386        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4387                true /* requireFullPermission */, true /* checkShell */,
4388                "revokeRuntimePermission");
4389
4390        final int appId;
4391
4392        synchronized (mPackages) {
4393            final PackageParser.Package pkg = mPackages.get(packageName);
4394            if (pkg == null) {
4395                throw new IllegalArgumentException("Unknown package: " + packageName);
4396            }
4397
4398            final BasePermission bp = mSettings.mPermissions.get(name);
4399            if (bp == null) {
4400                throw new IllegalArgumentException("Unknown permission: " + name);
4401            }
4402
4403            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4404
4405            // If a permission review is required for legacy apps we represent
4406            // their permissions as always granted runtime ones since we need
4407            // to keep the review required permission flag per user while an
4408            // install permission's state is shared across all users.
4409            if (mPermissionReviewRequired
4410                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4411                    && bp.isRuntime()) {
4412                return;
4413            }
4414
4415            SettingBase sb = (SettingBase) pkg.mExtras;
4416            if (sb == null) {
4417                throw new IllegalArgumentException("Unknown package: " + packageName);
4418            }
4419
4420            final PermissionsState permissionsState = sb.getPermissionsState();
4421
4422            final int flags = permissionsState.getPermissionFlags(name, userId);
4423            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4424                throw new SecurityException("Cannot revoke system fixed permission "
4425                        + name + " for package " + packageName);
4426            }
4427            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4428                throw new SecurityException("Cannot revoke policy fixed permission "
4429                        + name + " for package " + packageName);
4430            }
4431
4432            if (bp.isDevelopment()) {
4433                // Development permissions must be handled specially, since they are not
4434                // normal runtime permissions.  For now they apply to all users.
4435                if (permissionsState.revokeInstallPermission(bp) !=
4436                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4437                    scheduleWriteSettingsLocked();
4438                }
4439                return;
4440            }
4441
4442            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4443                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4444                return;
4445            }
4446
4447            if (bp.isRuntime()) {
4448                logPermissionRevoked(mContext, name, packageName);
4449            }
4450
4451            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4452
4453            // Critical, after this call app should never have the permission.
4454            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4455
4456            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4457        }
4458
4459        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4460    }
4461
4462    /**
4463     * Get the first event id for the permission.
4464     *
4465     * <p>There are four events for each permission: <ul>
4466     *     <li>Request permission: first id + 0</li>
4467     *     <li>Grant permission: first id + 1</li>
4468     *     <li>Request for permission denied: first id + 2</li>
4469     *     <li>Revoke permission: first id + 3</li>
4470     * </ul></p>
4471     *
4472     * @param name name of the permission
4473     *
4474     * @return The first event id for the permission
4475     */
4476    private static int getBaseEventId(@NonNull String name) {
4477        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4478
4479        if (eventIdIndex == -1) {
4480            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4481                    || "user".equals(Build.TYPE)) {
4482                Log.i(TAG, "Unknown permission " + name);
4483
4484                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4485            } else {
4486                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4487                //
4488                // Also update
4489                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4490                // - metrics_constants.proto
4491                throw new IllegalStateException("Unknown permission " + name);
4492            }
4493        }
4494
4495        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4496    }
4497
4498    /**
4499     * Log that a permission was revoked.
4500     *
4501     * @param context Context of the caller
4502     * @param name name of the permission
4503     * @param packageName package permission if for
4504     */
4505    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4506            @NonNull String packageName) {
4507        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4508    }
4509
4510    /**
4511     * Log that a permission request was granted.
4512     *
4513     * @param context Context of the caller
4514     * @param name name of the permission
4515     * @param packageName package permission if for
4516     */
4517    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4518            @NonNull String packageName) {
4519        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4520    }
4521
4522    @Override
4523    public void resetRuntimePermissions() {
4524        mContext.enforceCallingOrSelfPermission(
4525                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4526                "revokeRuntimePermission");
4527
4528        int callingUid = Binder.getCallingUid();
4529        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4530            mContext.enforceCallingOrSelfPermission(
4531                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4532                    "resetRuntimePermissions");
4533        }
4534
4535        synchronized (mPackages) {
4536            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4537            for (int userId : UserManagerService.getInstance().getUserIds()) {
4538                final int packageCount = mPackages.size();
4539                for (int i = 0; i < packageCount; i++) {
4540                    PackageParser.Package pkg = mPackages.valueAt(i);
4541                    if (!(pkg.mExtras instanceof PackageSetting)) {
4542                        continue;
4543                    }
4544                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4545                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4546                }
4547            }
4548        }
4549    }
4550
4551    @Override
4552    public int getPermissionFlags(String name, String packageName, int userId) {
4553        if (!sUserManager.exists(userId)) {
4554            return 0;
4555        }
4556
4557        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4558
4559        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4560                true /* requireFullPermission */, false /* checkShell */,
4561                "getPermissionFlags");
4562
4563        synchronized (mPackages) {
4564            final PackageParser.Package pkg = mPackages.get(packageName);
4565            if (pkg == null) {
4566                return 0;
4567            }
4568
4569            final BasePermission bp = mSettings.mPermissions.get(name);
4570            if (bp == null) {
4571                return 0;
4572            }
4573
4574            SettingBase sb = (SettingBase) pkg.mExtras;
4575            if (sb == null) {
4576                return 0;
4577            }
4578
4579            PermissionsState permissionsState = sb.getPermissionsState();
4580            return permissionsState.getPermissionFlags(name, userId);
4581        }
4582    }
4583
4584    @Override
4585    public void updatePermissionFlags(String name, String packageName, int flagMask,
4586            int flagValues, int userId) {
4587        if (!sUserManager.exists(userId)) {
4588            return;
4589        }
4590
4591        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4592
4593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4594                true /* requireFullPermission */, true /* checkShell */,
4595                "updatePermissionFlags");
4596
4597        // Only the system can change these flags and nothing else.
4598        if (getCallingUid() != Process.SYSTEM_UID) {
4599            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4600            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4601            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4602            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4603            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4604        }
4605
4606        synchronized (mPackages) {
4607            final PackageParser.Package pkg = mPackages.get(packageName);
4608            if (pkg == null) {
4609                throw new IllegalArgumentException("Unknown package: " + packageName);
4610            }
4611
4612            final BasePermission bp = mSettings.mPermissions.get(name);
4613            if (bp == null) {
4614                throw new IllegalArgumentException("Unknown permission: " + name);
4615            }
4616
4617            SettingBase sb = (SettingBase) pkg.mExtras;
4618            if (sb == null) {
4619                throw new IllegalArgumentException("Unknown package: " + packageName);
4620            }
4621
4622            PermissionsState permissionsState = sb.getPermissionsState();
4623
4624            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4625
4626            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4627                // Install and runtime permissions are stored in different places,
4628                // so figure out what permission changed and persist the change.
4629                if (permissionsState.getInstallPermissionState(name) != null) {
4630                    scheduleWriteSettingsLocked();
4631                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4632                        || hadState) {
4633                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4634                }
4635            }
4636        }
4637    }
4638
4639    /**
4640     * Update the permission flags for all packages and runtime permissions of a user in order
4641     * to allow device or profile owner to remove POLICY_FIXED.
4642     */
4643    @Override
4644    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4645        if (!sUserManager.exists(userId)) {
4646            return;
4647        }
4648
4649        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4650
4651        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4652                true /* requireFullPermission */, true /* checkShell */,
4653                "updatePermissionFlagsForAllApps");
4654
4655        // Only the system can change system fixed flags.
4656        if (getCallingUid() != Process.SYSTEM_UID) {
4657            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4658            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4659        }
4660
4661        synchronized (mPackages) {
4662            boolean changed = false;
4663            final int packageCount = mPackages.size();
4664            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4665                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4666                SettingBase sb = (SettingBase) pkg.mExtras;
4667                if (sb == null) {
4668                    continue;
4669                }
4670                PermissionsState permissionsState = sb.getPermissionsState();
4671                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4672                        userId, flagMask, flagValues);
4673            }
4674            if (changed) {
4675                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4676            }
4677        }
4678    }
4679
4680    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4681        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4682                != PackageManager.PERMISSION_GRANTED
4683            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4684                != PackageManager.PERMISSION_GRANTED) {
4685            throw new SecurityException(message + " requires "
4686                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4687                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4688        }
4689    }
4690
4691    @Override
4692    public boolean shouldShowRequestPermissionRationale(String permissionName,
4693            String packageName, int userId) {
4694        if (UserHandle.getCallingUserId() != userId) {
4695            mContext.enforceCallingPermission(
4696                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4697                    "canShowRequestPermissionRationale for user " + userId);
4698        }
4699
4700        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4701        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4702            return false;
4703        }
4704
4705        if (checkPermission(permissionName, packageName, userId)
4706                == PackageManager.PERMISSION_GRANTED) {
4707            return false;
4708        }
4709
4710        final int flags;
4711
4712        final long identity = Binder.clearCallingIdentity();
4713        try {
4714            flags = getPermissionFlags(permissionName,
4715                    packageName, userId);
4716        } finally {
4717            Binder.restoreCallingIdentity(identity);
4718        }
4719
4720        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4721                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4722                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4723
4724        if ((flags & fixedFlags) != 0) {
4725            return false;
4726        }
4727
4728        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4729    }
4730
4731    @Override
4732    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4733        mContext.enforceCallingOrSelfPermission(
4734                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4735                "addOnPermissionsChangeListener");
4736
4737        synchronized (mPackages) {
4738            mOnPermissionChangeListeners.addListenerLocked(listener);
4739        }
4740    }
4741
4742    @Override
4743    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4744        synchronized (mPackages) {
4745            mOnPermissionChangeListeners.removeListenerLocked(listener);
4746        }
4747    }
4748
4749    @Override
4750    public boolean isProtectedBroadcast(String actionName) {
4751        synchronized (mPackages) {
4752            if (mProtectedBroadcasts.contains(actionName)) {
4753                return true;
4754            } else if (actionName != null) {
4755                // TODO: remove these terrible hacks
4756                if (actionName.startsWith("android.net.netmon.lingerExpired")
4757                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4758                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4759                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4760                    return true;
4761                }
4762            }
4763        }
4764        return false;
4765    }
4766
4767    @Override
4768    public int checkSignatures(String pkg1, String pkg2) {
4769        synchronized (mPackages) {
4770            final PackageParser.Package p1 = mPackages.get(pkg1);
4771            final PackageParser.Package p2 = mPackages.get(pkg2);
4772            if (p1 == null || p1.mExtras == null
4773                    || p2 == null || p2.mExtras == null) {
4774                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4775            }
4776            return compareSignatures(p1.mSignatures, p2.mSignatures);
4777        }
4778    }
4779
4780    @Override
4781    public int checkUidSignatures(int uid1, int uid2) {
4782        // Map to base uids.
4783        uid1 = UserHandle.getAppId(uid1);
4784        uid2 = UserHandle.getAppId(uid2);
4785        // reader
4786        synchronized (mPackages) {
4787            Signature[] s1;
4788            Signature[] s2;
4789            Object obj = mSettings.getUserIdLPr(uid1);
4790            if (obj != null) {
4791                if (obj instanceof SharedUserSetting) {
4792                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4793                } else if (obj instanceof PackageSetting) {
4794                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4795                } else {
4796                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4797                }
4798            } else {
4799                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4800            }
4801            obj = mSettings.getUserIdLPr(uid2);
4802            if (obj != null) {
4803                if (obj instanceof SharedUserSetting) {
4804                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4805                } else if (obj instanceof PackageSetting) {
4806                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4807                } else {
4808                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4809                }
4810            } else {
4811                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4812            }
4813            return compareSignatures(s1, s2);
4814        }
4815    }
4816
4817    /**
4818     * This method should typically only be used when granting or revoking
4819     * permissions, since the app may immediately restart after this call.
4820     * <p>
4821     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4822     * guard your work against the app being relaunched.
4823     */
4824    private void killUid(int appId, int userId, String reason) {
4825        final long identity = Binder.clearCallingIdentity();
4826        try {
4827            IActivityManager am = ActivityManager.getService();
4828            if (am != null) {
4829                try {
4830                    am.killUid(appId, userId, reason);
4831                } catch (RemoteException e) {
4832                    /* ignore - same process */
4833                }
4834            }
4835        } finally {
4836            Binder.restoreCallingIdentity(identity);
4837        }
4838    }
4839
4840    /**
4841     * Compares two sets of signatures. Returns:
4842     * <br />
4843     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4844     * <br />
4845     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4846     * <br />
4847     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4848     * <br />
4849     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4850     * <br />
4851     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4852     */
4853    static int compareSignatures(Signature[] s1, Signature[] s2) {
4854        if (s1 == null) {
4855            return s2 == null
4856                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4857                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4858        }
4859
4860        if (s2 == null) {
4861            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4862        }
4863
4864        if (s1.length != s2.length) {
4865            return PackageManager.SIGNATURE_NO_MATCH;
4866        }
4867
4868        // Since both signature sets are of size 1, we can compare without HashSets.
4869        if (s1.length == 1) {
4870            return s1[0].equals(s2[0]) ?
4871                    PackageManager.SIGNATURE_MATCH :
4872                    PackageManager.SIGNATURE_NO_MATCH;
4873        }
4874
4875        ArraySet<Signature> set1 = new ArraySet<Signature>();
4876        for (Signature sig : s1) {
4877            set1.add(sig);
4878        }
4879        ArraySet<Signature> set2 = new ArraySet<Signature>();
4880        for (Signature sig : s2) {
4881            set2.add(sig);
4882        }
4883        // Make sure s2 contains all signatures in s1.
4884        if (set1.equals(set2)) {
4885            return PackageManager.SIGNATURE_MATCH;
4886        }
4887        return PackageManager.SIGNATURE_NO_MATCH;
4888    }
4889
4890    /**
4891     * If the database version for this type of package (internal storage or
4892     * external storage) is less than the version where package signatures
4893     * were updated, return true.
4894     */
4895    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4896        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4897        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4898    }
4899
4900    /**
4901     * Used for backward compatibility to make sure any packages with
4902     * certificate chains get upgraded to the new style. {@code existingSigs}
4903     * will be in the old format (since they were stored on disk from before the
4904     * system upgrade) and {@code scannedSigs} will be in the newer format.
4905     */
4906    private int compareSignaturesCompat(PackageSignatures existingSigs,
4907            PackageParser.Package scannedPkg) {
4908        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4909            return PackageManager.SIGNATURE_NO_MATCH;
4910        }
4911
4912        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4913        for (Signature sig : existingSigs.mSignatures) {
4914            existingSet.add(sig);
4915        }
4916        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4917        for (Signature sig : scannedPkg.mSignatures) {
4918            try {
4919                Signature[] chainSignatures = sig.getChainSignatures();
4920                for (Signature chainSig : chainSignatures) {
4921                    scannedCompatSet.add(chainSig);
4922                }
4923            } catch (CertificateEncodingException e) {
4924                scannedCompatSet.add(sig);
4925            }
4926        }
4927        /*
4928         * Make sure the expanded scanned set contains all signatures in the
4929         * existing one.
4930         */
4931        if (scannedCompatSet.equals(existingSet)) {
4932            // Migrate the old signatures to the new scheme.
4933            existingSigs.assignSignatures(scannedPkg.mSignatures);
4934            // The new KeySets will be re-added later in the scanning process.
4935            synchronized (mPackages) {
4936                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4937            }
4938            return PackageManager.SIGNATURE_MATCH;
4939        }
4940        return PackageManager.SIGNATURE_NO_MATCH;
4941    }
4942
4943    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4944        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4945        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4946    }
4947
4948    private int compareSignaturesRecover(PackageSignatures existingSigs,
4949            PackageParser.Package scannedPkg) {
4950        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4951            return PackageManager.SIGNATURE_NO_MATCH;
4952        }
4953
4954        String msg = null;
4955        try {
4956            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4957                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4958                        + scannedPkg.packageName);
4959                return PackageManager.SIGNATURE_MATCH;
4960            }
4961        } catch (CertificateException e) {
4962            msg = e.getMessage();
4963        }
4964
4965        logCriticalInfo(Log.INFO,
4966                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4967        return PackageManager.SIGNATURE_NO_MATCH;
4968    }
4969
4970    @Override
4971    public List<String> getAllPackages() {
4972        synchronized (mPackages) {
4973            return new ArrayList<String>(mPackages.keySet());
4974        }
4975    }
4976
4977    @Override
4978    public String[] getPackagesForUid(int uid) {
4979        final int userId = UserHandle.getUserId(uid);
4980        uid = UserHandle.getAppId(uid);
4981        // reader
4982        synchronized (mPackages) {
4983            Object obj = mSettings.getUserIdLPr(uid);
4984            if (obj instanceof SharedUserSetting) {
4985                final SharedUserSetting sus = (SharedUserSetting) obj;
4986                final int N = sus.packages.size();
4987                String[] res = new String[N];
4988                final Iterator<PackageSetting> it = sus.packages.iterator();
4989                int i = 0;
4990                while (it.hasNext()) {
4991                    PackageSetting ps = it.next();
4992                    if (ps.getInstalled(userId)) {
4993                        res[i++] = ps.name;
4994                    } else {
4995                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4996                    }
4997                }
4998                return res;
4999            } else if (obj instanceof PackageSetting) {
5000                final PackageSetting ps = (PackageSetting) obj;
5001                return new String[] { ps.name };
5002            }
5003        }
5004        return null;
5005    }
5006
5007    @Override
5008    public String getNameForUid(int uid) {
5009        // reader
5010        synchronized (mPackages) {
5011            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5012            if (obj instanceof SharedUserSetting) {
5013                final SharedUserSetting sus = (SharedUserSetting) obj;
5014                return sus.name + ":" + sus.userId;
5015            } else if (obj instanceof PackageSetting) {
5016                final PackageSetting ps = (PackageSetting) obj;
5017                return ps.name;
5018            }
5019        }
5020        return null;
5021    }
5022
5023    @Override
5024    public int getUidForSharedUser(String sharedUserName) {
5025        if(sharedUserName == null) {
5026            return -1;
5027        }
5028        // reader
5029        synchronized (mPackages) {
5030            SharedUserSetting suid;
5031            try {
5032                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5033                if (suid != null) {
5034                    return suid.userId;
5035                }
5036            } catch (PackageManagerException ignore) {
5037                // can't happen, but, still need to catch it
5038            }
5039            return -1;
5040        }
5041    }
5042
5043    @Override
5044    public int getFlagsForUid(int uid) {
5045        synchronized (mPackages) {
5046            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5047            if (obj instanceof SharedUserSetting) {
5048                final SharedUserSetting sus = (SharedUserSetting) obj;
5049                return sus.pkgFlags;
5050            } else if (obj instanceof PackageSetting) {
5051                final PackageSetting ps = (PackageSetting) obj;
5052                return ps.pkgFlags;
5053            }
5054        }
5055        return 0;
5056    }
5057
5058    @Override
5059    public int getPrivateFlagsForUid(int uid) {
5060        synchronized (mPackages) {
5061            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5062            if (obj instanceof SharedUserSetting) {
5063                final SharedUserSetting sus = (SharedUserSetting) obj;
5064                return sus.pkgPrivateFlags;
5065            } else if (obj instanceof PackageSetting) {
5066                final PackageSetting ps = (PackageSetting) obj;
5067                return ps.pkgPrivateFlags;
5068            }
5069        }
5070        return 0;
5071    }
5072
5073    @Override
5074    public boolean isUidPrivileged(int uid) {
5075        uid = UserHandle.getAppId(uid);
5076        // reader
5077        synchronized (mPackages) {
5078            Object obj = mSettings.getUserIdLPr(uid);
5079            if (obj instanceof SharedUserSetting) {
5080                final SharedUserSetting sus = (SharedUserSetting) obj;
5081                final Iterator<PackageSetting> it = sus.packages.iterator();
5082                while (it.hasNext()) {
5083                    if (it.next().isPrivileged()) {
5084                        return true;
5085                    }
5086                }
5087            } else if (obj instanceof PackageSetting) {
5088                final PackageSetting ps = (PackageSetting) obj;
5089                return ps.isPrivileged();
5090            }
5091        }
5092        return false;
5093    }
5094
5095    @Override
5096    public String[] getAppOpPermissionPackages(String permissionName) {
5097        synchronized (mPackages) {
5098            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5099            if (pkgs == null) {
5100                return null;
5101            }
5102            return pkgs.toArray(new String[pkgs.size()]);
5103        }
5104    }
5105
5106    @Override
5107    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5108            int flags, int userId) {
5109        try {
5110            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5111
5112            if (!sUserManager.exists(userId)) return null;
5113            flags = updateFlagsForResolve(flags, userId, intent);
5114            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5115                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5116
5117            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5118            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5119                    flags, userId);
5120            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5121
5122            final ResolveInfo bestChoice =
5123                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5124            return bestChoice;
5125        } finally {
5126            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5127        }
5128    }
5129
5130    @Override
5131    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5132            IntentFilter filter, int match, ComponentName activity) {
5133        final int userId = UserHandle.getCallingUserId();
5134        if (DEBUG_PREFERRED) {
5135            Log.v(TAG, "setLastChosenActivity intent=" + intent
5136                + " resolvedType=" + resolvedType
5137                + " flags=" + flags
5138                + " filter=" + filter
5139                + " match=" + match
5140                + " activity=" + activity);
5141            filter.dump(new PrintStreamPrinter(System.out), "    ");
5142        }
5143        intent.setComponent(null);
5144        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5145                userId);
5146        // Find any earlier preferred or last chosen entries and nuke them
5147        findPreferredActivity(intent, resolvedType,
5148                flags, query, 0, false, true, false, userId);
5149        // Add the new activity as the last chosen for this filter
5150        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5151                "Setting last chosen");
5152    }
5153
5154    @Override
5155    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5156        final int userId = UserHandle.getCallingUserId();
5157        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5158        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5159                userId);
5160        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5161                false, false, false, userId);
5162    }
5163
5164    private boolean isEphemeralDisabled() {
5165        // ephemeral apps have been disabled across the board
5166        if (DISABLE_EPHEMERAL_APPS) {
5167            return true;
5168        }
5169        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5170        if (!mSystemReady) {
5171            return true;
5172        }
5173        // we can't get a content resolver until the system is ready; these checks must happen last
5174        final ContentResolver resolver = mContext.getContentResolver();
5175        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5176            return true;
5177        }
5178        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5179    }
5180
5181    private boolean isEphemeralAllowed(
5182            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5183            boolean skipPackageCheck) {
5184        // Short circuit and return early if possible.
5185        if (isEphemeralDisabled()) {
5186            return false;
5187        }
5188        final int callingUser = UserHandle.getCallingUserId();
5189        if (callingUser != UserHandle.USER_SYSTEM) {
5190            return false;
5191        }
5192        if (mEphemeralResolverConnection == null) {
5193            return false;
5194        }
5195        if (mEphemeralInstallerComponent == null) {
5196            return false;
5197        }
5198        if (intent.getComponent() != null) {
5199            return false;
5200        }
5201        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5202            return false;
5203        }
5204        if (!skipPackageCheck && intent.getPackage() != null) {
5205            return false;
5206        }
5207        final boolean isWebUri = hasWebURI(intent);
5208        if (!isWebUri || intent.getData().getHost() == null) {
5209            return false;
5210        }
5211        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5212        synchronized (mPackages) {
5213            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5214            for (int n = 0; n < count; n++) {
5215                ResolveInfo info = resolvedActivities.get(n);
5216                String packageName = info.activityInfo.packageName;
5217                PackageSetting ps = mSettings.mPackages.get(packageName);
5218                if (ps != null) {
5219                    // Try to get the status from User settings first
5220                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5221                    int status = (int) (packedStatus >> 32);
5222                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5223                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5224                        if (DEBUG_EPHEMERAL) {
5225                            Slog.v(TAG, "DENY ephemeral apps;"
5226                                + " pkg: " + packageName + ", status: " + status);
5227                        }
5228                        return false;
5229                    }
5230                }
5231            }
5232        }
5233        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5234        return true;
5235    }
5236
5237    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5238            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5239            int userId) {
5240        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5241                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5242                        callingPackage, userId));
5243        mHandler.sendMessage(msg);
5244    }
5245
5246    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5247            int flags, List<ResolveInfo> query, int userId) {
5248        if (query != null) {
5249            final int N = query.size();
5250            if (N == 1) {
5251                return query.get(0);
5252            } else if (N > 1) {
5253                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5254                // If there is more than one activity with the same priority,
5255                // then let the user decide between them.
5256                ResolveInfo r0 = query.get(0);
5257                ResolveInfo r1 = query.get(1);
5258                if (DEBUG_INTENT_MATCHING || debug) {
5259                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5260                            + r1.activityInfo.name + "=" + r1.priority);
5261                }
5262                // If the first activity has a higher priority, or a different
5263                // default, then it is always desirable to pick it.
5264                if (r0.priority != r1.priority
5265                        || r0.preferredOrder != r1.preferredOrder
5266                        || r0.isDefault != r1.isDefault) {
5267                    return query.get(0);
5268                }
5269                // If we have saved a preference for a preferred activity for
5270                // this Intent, use that.
5271                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5272                        flags, query, r0.priority, true, false, debug, userId);
5273                if (ri != null) {
5274                    return ri;
5275                }
5276                ri = new ResolveInfo(mResolveInfo);
5277                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5278                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5279                // If all of the options come from the same package, show the application's
5280                // label and icon instead of the generic resolver's.
5281                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5282                // and then throw away the ResolveInfo itself, meaning that the caller loses
5283                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5284                // a fallback for this case; we only set the target package's resources on
5285                // the ResolveInfo, not the ActivityInfo.
5286                final String intentPackage = intent.getPackage();
5287                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5288                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5289                    ri.resolvePackageName = intentPackage;
5290                    if (userNeedsBadging(userId)) {
5291                        ri.noResourceId = true;
5292                    } else {
5293                        ri.icon = appi.icon;
5294                    }
5295                    ri.iconResourceId = appi.icon;
5296                    ri.labelRes = appi.labelRes;
5297                }
5298                ri.activityInfo.applicationInfo = new ApplicationInfo(
5299                        ri.activityInfo.applicationInfo);
5300                if (userId != 0) {
5301                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5302                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5303                }
5304                // Make sure that the resolver is displayable in car mode
5305                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5306                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5307                return ri;
5308            }
5309        }
5310        return null;
5311    }
5312
5313    /**
5314     * Return true if the given list is not empty and all of its contents have
5315     * an activityInfo with the given package name.
5316     */
5317    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5318        if (ArrayUtils.isEmpty(list)) {
5319            return false;
5320        }
5321        for (int i = 0, N = list.size(); i < N; i++) {
5322            final ResolveInfo ri = list.get(i);
5323            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5324            if (ai == null || !packageName.equals(ai.packageName)) {
5325                return false;
5326            }
5327        }
5328        return true;
5329    }
5330
5331    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5332            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5333        final int N = query.size();
5334        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5335                .get(userId);
5336        // Get the list of persistent preferred activities that handle the intent
5337        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5338        List<PersistentPreferredActivity> pprefs = ppir != null
5339                ? ppir.queryIntent(intent, resolvedType,
5340                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5341                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5342                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5343                : null;
5344        if (pprefs != null && pprefs.size() > 0) {
5345            final int M = pprefs.size();
5346            for (int i=0; i<M; i++) {
5347                final PersistentPreferredActivity ppa = pprefs.get(i);
5348                if (DEBUG_PREFERRED || debug) {
5349                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5350                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5351                            + "\n  component=" + ppa.mComponent);
5352                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5353                }
5354                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5355                        flags | MATCH_DISABLED_COMPONENTS, userId);
5356                if (DEBUG_PREFERRED || debug) {
5357                    Slog.v(TAG, "Found persistent preferred activity:");
5358                    if (ai != null) {
5359                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5360                    } else {
5361                        Slog.v(TAG, "  null");
5362                    }
5363                }
5364                if (ai == null) {
5365                    // This previously registered persistent preferred activity
5366                    // component is no longer known. Ignore it and do NOT remove it.
5367                    continue;
5368                }
5369                for (int j=0; j<N; j++) {
5370                    final ResolveInfo ri = query.get(j);
5371                    if (!ri.activityInfo.applicationInfo.packageName
5372                            .equals(ai.applicationInfo.packageName)) {
5373                        continue;
5374                    }
5375                    if (!ri.activityInfo.name.equals(ai.name)) {
5376                        continue;
5377                    }
5378                    //  Found a persistent preference that can handle the intent.
5379                    if (DEBUG_PREFERRED || debug) {
5380                        Slog.v(TAG, "Returning persistent preferred activity: " +
5381                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5382                    }
5383                    return ri;
5384                }
5385            }
5386        }
5387        return null;
5388    }
5389
5390    // TODO: handle preferred activities missing while user has amnesia
5391    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5392            List<ResolveInfo> query, int priority, boolean always,
5393            boolean removeMatches, boolean debug, int userId) {
5394        if (!sUserManager.exists(userId)) return null;
5395        flags = updateFlagsForResolve(flags, userId, intent);
5396        // writer
5397        synchronized (mPackages) {
5398            if (intent.getSelector() != null) {
5399                intent = intent.getSelector();
5400            }
5401            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5402
5403            // Try to find a matching persistent preferred activity.
5404            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5405                    debug, userId);
5406
5407            // If a persistent preferred activity matched, use it.
5408            if (pri != null) {
5409                return pri;
5410            }
5411
5412            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5413            // Get the list of preferred activities that handle the intent
5414            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5415            List<PreferredActivity> prefs = pir != null
5416                    ? pir.queryIntent(intent, resolvedType,
5417                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5418                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5419                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5420                    : null;
5421            if (prefs != null && prefs.size() > 0) {
5422                boolean changed = false;
5423                try {
5424                    // First figure out how good the original match set is.
5425                    // We will only allow preferred activities that came
5426                    // from the same match quality.
5427                    int match = 0;
5428
5429                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5430
5431                    final int N = query.size();
5432                    for (int j=0; j<N; j++) {
5433                        final ResolveInfo ri = query.get(j);
5434                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5435                                + ": 0x" + Integer.toHexString(match));
5436                        if (ri.match > match) {
5437                            match = ri.match;
5438                        }
5439                    }
5440
5441                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5442                            + Integer.toHexString(match));
5443
5444                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5445                    final int M = prefs.size();
5446                    for (int i=0; i<M; i++) {
5447                        final PreferredActivity pa = prefs.get(i);
5448                        if (DEBUG_PREFERRED || debug) {
5449                            Slog.v(TAG, "Checking PreferredActivity ds="
5450                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5451                                    + "\n  component=" + pa.mPref.mComponent);
5452                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5453                        }
5454                        if (pa.mPref.mMatch != match) {
5455                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5456                                    + Integer.toHexString(pa.mPref.mMatch));
5457                            continue;
5458                        }
5459                        // If it's not an "always" type preferred activity and that's what we're
5460                        // looking for, skip it.
5461                        if (always && !pa.mPref.mAlways) {
5462                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5463                            continue;
5464                        }
5465                        final ActivityInfo ai = getActivityInfo(
5466                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5467                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5468                                userId);
5469                        if (DEBUG_PREFERRED || debug) {
5470                            Slog.v(TAG, "Found preferred activity:");
5471                            if (ai != null) {
5472                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5473                            } else {
5474                                Slog.v(TAG, "  null");
5475                            }
5476                        }
5477                        if (ai == null) {
5478                            // This previously registered preferred activity
5479                            // component is no longer known.  Most likely an update
5480                            // to the app was installed and in the new version this
5481                            // component no longer exists.  Clean it up by removing
5482                            // it from the preferred activities list, and skip it.
5483                            Slog.w(TAG, "Removing dangling preferred activity: "
5484                                    + pa.mPref.mComponent);
5485                            pir.removeFilter(pa);
5486                            changed = true;
5487                            continue;
5488                        }
5489                        for (int j=0; j<N; j++) {
5490                            final ResolveInfo ri = query.get(j);
5491                            if (!ri.activityInfo.applicationInfo.packageName
5492                                    .equals(ai.applicationInfo.packageName)) {
5493                                continue;
5494                            }
5495                            if (!ri.activityInfo.name.equals(ai.name)) {
5496                                continue;
5497                            }
5498
5499                            if (removeMatches) {
5500                                pir.removeFilter(pa);
5501                                changed = true;
5502                                if (DEBUG_PREFERRED) {
5503                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5504                                }
5505                                break;
5506                            }
5507
5508                            // Okay we found a previously set preferred or last chosen app.
5509                            // If the result set is different from when this
5510                            // was created, we need to clear it and re-ask the
5511                            // user their preference, if we're looking for an "always" type entry.
5512                            if (always && !pa.mPref.sameSet(query)) {
5513                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5514                                        + intent + " type " + resolvedType);
5515                                if (DEBUG_PREFERRED) {
5516                                    Slog.v(TAG, "Removing preferred activity since set changed "
5517                                            + pa.mPref.mComponent);
5518                                }
5519                                pir.removeFilter(pa);
5520                                // Re-add the filter as a "last chosen" entry (!always)
5521                                PreferredActivity lastChosen = new PreferredActivity(
5522                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5523                                pir.addFilter(lastChosen);
5524                                changed = true;
5525                                return null;
5526                            }
5527
5528                            // Yay! Either the set matched or we're looking for the last chosen
5529                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5530                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5531                            return ri;
5532                        }
5533                    }
5534                } finally {
5535                    if (changed) {
5536                        if (DEBUG_PREFERRED) {
5537                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5538                        }
5539                        scheduleWritePackageRestrictionsLocked(userId);
5540                    }
5541                }
5542            }
5543        }
5544        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5545        return null;
5546    }
5547
5548    /*
5549     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5550     */
5551    @Override
5552    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5553            int targetUserId) {
5554        mContext.enforceCallingOrSelfPermission(
5555                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5556        List<CrossProfileIntentFilter> matches =
5557                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5558        if (matches != null) {
5559            int size = matches.size();
5560            for (int i = 0; i < size; i++) {
5561                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5562            }
5563        }
5564        if (hasWebURI(intent)) {
5565            // cross-profile app linking works only towards the parent.
5566            final UserInfo parent = getProfileParent(sourceUserId);
5567            synchronized(mPackages) {
5568                int flags = updateFlagsForResolve(0, parent.id, intent);
5569                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5570                        intent, resolvedType, flags, sourceUserId, parent.id);
5571                return xpDomainInfo != null;
5572            }
5573        }
5574        return false;
5575    }
5576
5577    private UserInfo getProfileParent(int userId) {
5578        final long identity = Binder.clearCallingIdentity();
5579        try {
5580            return sUserManager.getProfileParent(userId);
5581        } finally {
5582            Binder.restoreCallingIdentity(identity);
5583        }
5584    }
5585
5586    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5587            String resolvedType, int userId) {
5588        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5589        if (resolver != null) {
5590            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5591                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5592        }
5593        return null;
5594    }
5595
5596    @Override
5597    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5598            String resolvedType, int flags, int userId) {
5599        try {
5600            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5601
5602            return new ParceledListSlice<>(
5603                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5604        } finally {
5605            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5606        }
5607    }
5608
5609    /**
5610     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5611     * ephemeral, returns {@code null}.
5612     */
5613    private String getEphemeralPackageName(int callingUid) {
5614        final int appId = UserHandle.getAppId(callingUid);
5615        synchronized (mPackages) {
5616            final Object obj = mSettings.getUserIdLPr(appId);
5617            if (obj instanceof PackageSetting) {
5618                final PackageSetting ps = (PackageSetting) obj;
5619                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5620            }
5621        }
5622        return null;
5623    }
5624
5625    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5626            String resolvedType, int flags, int userId) {
5627        if (!sUserManager.exists(userId)) return Collections.emptyList();
5628        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5629        flags = updateFlagsForResolve(flags, userId, intent);
5630        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5631                false /* requireFullPermission */, false /* checkShell */,
5632                "query intent activities");
5633        ComponentName comp = intent.getComponent();
5634        if (comp == null) {
5635            if (intent.getSelector() != null) {
5636                intent = intent.getSelector();
5637                comp = intent.getComponent();
5638            }
5639        }
5640
5641        if (comp != null) {
5642            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5643            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5644            if (ai != null) {
5645                // When specifying an explicit component, we prevent the activity from being
5646                // used when either 1) the calling package is normal and the activity is within
5647                // an ephemeral application or 2) the calling package is ephemeral and the
5648                // activity is not visible to ephemeral applications.
5649                boolean matchEphemeral =
5650                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5651                boolean ephemeralVisibleOnly =
5652                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5653                boolean blockResolution =
5654                        (!matchEphemeral && ephemeralPkgName == null
5655                                && (ai.applicationInfo.privateFlags
5656                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5657                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5658                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5659                if (!blockResolution) {
5660                    final ResolveInfo ri = new ResolveInfo();
5661                    ri.activityInfo = ai;
5662                    list.add(ri);
5663                }
5664            }
5665            return list;
5666        }
5667
5668        // reader
5669        boolean sortResult = false;
5670        boolean addEphemeral = false;
5671        List<ResolveInfo> result;
5672        final String pkgName = intent.getPackage();
5673        synchronized (mPackages) {
5674            if (pkgName == null) {
5675                List<CrossProfileIntentFilter> matchingFilters =
5676                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5677                // Check for results that need to skip the current profile.
5678                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5679                        resolvedType, flags, userId);
5680                if (xpResolveInfo != null) {
5681                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5682                    xpResult.add(xpResolveInfo);
5683                    return filterForEphemeral(
5684                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5685                }
5686
5687                // Check for results in the current profile.
5688                result = filterIfNotSystemUser(mActivities.queryIntent(
5689                        intent, resolvedType, flags, userId), userId);
5690                addEphemeral =
5691                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5692
5693                // Check for cross profile results.
5694                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5695                xpResolveInfo = queryCrossProfileIntents(
5696                        matchingFilters, intent, resolvedType, flags, userId,
5697                        hasNonNegativePriorityResult);
5698                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5699                    boolean isVisibleToUser = filterIfNotSystemUser(
5700                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5701                    if (isVisibleToUser) {
5702                        result.add(xpResolveInfo);
5703                        sortResult = true;
5704                    }
5705                }
5706                if (hasWebURI(intent)) {
5707                    CrossProfileDomainInfo xpDomainInfo = null;
5708                    final UserInfo parent = getProfileParent(userId);
5709                    if (parent != null) {
5710                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5711                                flags, userId, parent.id);
5712                    }
5713                    if (xpDomainInfo != null) {
5714                        if (xpResolveInfo != null) {
5715                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5716                            // in the result.
5717                            result.remove(xpResolveInfo);
5718                        }
5719                        if (result.size() == 0 && !addEphemeral) {
5720                            // No result in current profile, but found candidate in parent user.
5721                            // And we are not going to add emphemeral app, so we can return the
5722                            // result straight away.
5723                            result.add(xpDomainInfo.resolveInfo);
5724                            return filterForEphemeral(result, ephemeralPkgName);
5725                        }
5726                    } else if (result.size() <= 1 && !addEphemeral) {
5727                        // No result in parent user and <= 1 result in current profile, and we
5728                        // are not going to add emphemeral app, so we can return the result without
5729                        // further processing.
5730                        return filterForEphemeral(result, ephemeralPkgName);
5731                    }
5732                    // We have more than one candidate (combining results from current and parent
5733                    // profile), so we need filtering and sorting.
5734                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5735                            intent, flags, result, xpDomainInfo, userId);
5736                    sortResult = true;
5737                }
5738            } else {
5739                final PackageParser.Package pkg = mPackages.get(pkgName);
5740                if (pkg != null) {
5741                    result = filterForEphemeral(filterIfNotSystemUser(
5742                            mActivities.queryIntentForPackage(
5743                                    intent, resolvedType, flags, pkg.activities, userId),
5744                            userId), ephemeralPkgName);
5745                } else {
5746                    // the caller wants to resolve for a particular package; however, there
5747                    // were no installed results, so, try to find an ephemeral result
5748                    addEphemeral = isEphemeralAllowed(
5749                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5750                    result = new ArrayList<ResolveInfo>();
5751                }
5752            }
5753        }
5754        if (addEphemeral) {
5755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5756            final EphemeralRequest requestObject = new EphemeralRequest(
5757                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5758                    null /*launchIntent*/, null /*callingPackage*/, userId);
5759            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5760                    mContext, mEphemeralResolverConnection, requestObject);
5761            if (intentInfo != null) {
5762                if (DEBUG_EPHEMERAL) {
5763                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5764                }
5765                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5766                ephemeralInstaller.ephemeralResponse = intentInfo;
5767                // make sure this resolver is the default
5768                ephemeralInstaller.isDefault = true;
5769                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5770                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5771                // add a non-generic filter
5772                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5773                ephemeralInstaller.filter.addDataPath(
5774                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5775                result.add(ephemeralInstaller);
5776            }
5777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5778        }
5779        if (sortResult) {
5780            Collections.sort(result, mResolvePrioritySorter);
5781        }
5782        return filterForEphemeral(result, ephemeralPkgName);
5783    }
5784
5785    private static class CrossProfileDomainInfo {
5786        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5787        ResolveInfo resolveInfo;
5788        /* Best domain verification status of the activities found in the other profile */
5789        int bestDomainVerificationStatus;
5790    }
5791
5792    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5793            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5794        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5795                sourceUserId)) {
5796            return null;
5797        }
5798        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5799                resolvedType, flags, parentUserId);
5800
5801        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5802            return null;
5803        }
5804        CrossProfileDomainInfo result = null;
5805        int size = resultTargetUser.size();
5806        for (int i = 0; i < size; i++) {
5807            ResolveInfo riTargetUser = resultTargetUser.get(i);
5808            // Intent filter verification is only for filters that specify a host. So don't return
5809            // those that handle all web uris.
5810            if (riTargetUser.handleAllWebDataURI) {
5811                continue;
5812            }
5813            String packageName = riTargetUser.activityInfo.packageName;
5814            PackageSetting ps = mSettings.mPackages.get(packageName);
5815            if (ps == null) {
5816                continue;
5817            }
5818            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5819            int status = (int)(verificationState >> 32);
5820            if (result == null) {
5821                result = new CrossProfileDomainInfo();
5822                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5823                        sourceUserId, parentUserId);
5824                result.bestDomainVerificationStatus = status;
5825            } else {
5826                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5827                        result.bestDomainVerificationStatus);
5828            }
5829        }
5830        // Don't consider matches with status NEVER across profiles.
5831        if (result != null && result.bestDomainVerificationStatus
5832                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5833            return null;
5834        }
5835        return result;
5836    }
5837
5838    /**
5839     * Verification statuses are ordered from the worse to the best, except for
5840     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5841     */
5842    private int bestDomainVerificationStatus(int status1, int status2) {
5843        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5844            return status2;
5845        }
5846        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5847            return status1;
5848        }
5849        return (int) MathUtils.max(status1, status2);
5850    }
5851
5852    private boolean isUserEnabled(int userId) {
5853        long callingId = Binder.clearCallingIdentity();
5854        try {
5855            UserInfo userInfo = sUserManager.getUserInfo(userId);
5856            return userInfo != null && userInfo.isEnabled();
5857        } finally {
5858            Binder.restoreCallingIdentity(callingId);
5859        }
5860    }
5861
5862    /**
5863     * Filter out activities with systemUserOnly flag set, when current user is not System.
5864     *
5865     * @return filtered list
5866     */
5867    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5868        if (userId == UserHandle.USER_SYSTEM) {
5869            return resolveInfos;
5870        }
5871        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5872            ResolveInfo info = resolveInfos.get(i);
5873            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5874                resolveInfos.remove(i);
5875            }
5876        }
5877        return resolveInfos;
5878    }
5879
5880    /**
5881     * Filters out ephemeral activities.
5882     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5883     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5884     *
5885     * @param resolveInfos The pre-filtered list of resolved activities
5886     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5887     *          is performed.
5888     * @return A filtered list of resolved activities.
5889     */
5890    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5891            String ephemeralPkgName) {
5892        if (ephemeralPkgName == null) {
5893            return resolveInfos;
5894        }
5895        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5896            ResolveInfo info = resolveInfos.get(i);
5897            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5898            // allow activities that are defined in the provided package
5899            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5900                continue;
5901            }
5902            // allow activities that have been explicitly exposed to ephemeral apps
5903            if (!isEphemeralApp
5904                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5905                continue;
5906            }
5907            resolveInfos.remove(i);
5908        }
5909        return resolveInfos;
5910    }
5911
5912    /**
5913     * @param resolveInfos list of resolve infos in descending priority order
5914     * @return if the list contains a resolve info with non-negative priority
5915     */
5916    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5917        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5918    }
5919
5920    private static boolean hasWebURI(Intent intent) {
5921        if (intent.getData() == null) {
5922            return false;
5923        }
5924        final String scheme = intent.getScheme();
5925        if (TextUtils.isEmpty(scheme)) {
5926            return false;
5927        }
5928        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5929    }
5930
5931    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5932            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5933            int userId) {
5934        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5935
5936        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5937            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5938                    candidates.size());
5939        }
5940
5941        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5942        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5943        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5944        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5945        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5946        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5947
5948        synchronized (mPackages) {
5949            final int count = candidates.size();
5950            // First, try to use linked apps. Partition the candidates into four lists:
5951            // one for the final results, one for the "do not use ever", one for "undefined status"
5952            // and finally one for "browser app type".
5953            for (int n=0; n<count; n++) {
5954                ResolveInfo info = candidates.get(n);
5955                String packageName = info.activityInfo.packageName;
5956                PackageSetting ps = mSettings.mPackages.get(packageName);
5957                if (ps != null) {
5958                    // Add to the special match all list (Browser use case)
5959                    if (info.handleAllWebDataURI) {
5960                        matchAllList.add(info);
5961                        continue;
5962                    }
5963                    // Try to get the status from User settings first
5964                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5965                    int status = (int)(packedStatus >> 32);
5966                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5967                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5968                        if (DEBUG_DOMAIN_VERIFICATION) {
5969                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5970                                    + " : linkgen=" + linkGeneration);
5971                        }
5972                        // Use link-enabled generation as preferredOrder, i.e.
5973                        // prefer newly-enabled over earlier-enabled.
5974                        info.preferredOrder = linkGeneration;
5975                        alwaysList.add(info);
5976                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5977                        if (DEBUG_DOMAIN_VERIFICATION) {
5978                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5979                        }
5980                        neverList.add(info);
5981                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5982                        if (DEBUG_DOMAIN_VERIFICATION) {
5983                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5984                        }
5985                        alwaysAskList.add(info);
5986                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5987                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5988                        if (DEBUG_DOMAIN_VERIFICATION) {
5989                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5990                        }
5991                        undefinedList.add(info);
5992                    }
5993                }
5994            }
5995
5996            // We'll want to include browser possibilities in a few cases
5997            boolean includeBrowser = false;
5998
5999            // First try to add the "always" resolution(s) for the current user, if any
6000            if (alwaysList.size() > 0) {
6001                result.addAll(alwaysList);
6002            } else {
6003                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6004                result.addAll(undefinedList);
6005                // Maybe add one for the other profile.
6006                if (xpDomainInfo != null && (
6007                        xpDomainInfo.bestDomainVerificationStatus
6008                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6009                    result.add(xpDomainInfo.resolveInfo);
6010                }
6011                includeBrowser = true;
6012            }
6013
6014            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6015            // If there were 'always' entries their preferred order has been set, so we also
6016            // back that off to make the alternatives equivalent
6017            if (alwaysAskList.size() > 0) {
6018                for (ResolveInfo i : result) {
6019                    i.preferredOrder = 0;
6020                }
6021                result.addAll(alwaysAskList);
6022                includeBrowser = true;
6023            }
6024
6025            if (includeBrowser) {
6026                // Also add browsers (all of them or only the default one)
6027                if (DEBUG_DOMAIN_VERIFICATION) {
6028                    Slog.v(TAG, "   ...including browsers in candidate set");
6029                }
6030                if ((matchFlags & MATCH_ALL) != 0) {
6031                    result.addAll(matchAllList);
6032                } else {
6033                    // Browser/generic handling case.  If there's a default browser, go straight
6034                    // to that (but only if there is no other higher-priority match).
6035                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6036                    int maxMatchPrio = 0;
6037                    ResolveInfo defaultBrowserMatch = null;
6038                    final int numCandidates = matchAllList.size();
6039                    for (int n = 0; n < numCandidates; n++) {
6040                        ResolveInfo info = matchAllList.get(n);
6041                        // track the highest overall match priority...
6042                        if (info.priority > maxMatchPrio) {
6043                            maxMatchPrio = info.priority;
6044                        }
6045                        // ...and the highest-priority default browser match
6046                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6047                            if (defaultBrowserMatch == null
6048                                    || (defaultBrowserMatch.priority < info.priority)) {
6049                                if (debug) {
6050                                    Slog.v(TAG, "Considering default browser match " + info);
6051                                }
6052                                defaultBrowserMatch = info;
6053                            }
6054                        }
6055                    }
6056                    if (defaultBrowserMatch != null
6057                            && defaultBrowserMatch.priority >= maxMatchPrio
6058                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6059                    {
6060                        if (debug) {
6061                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6062                        }
6063                        result.add(defaultBrowserMatch);
6064                    } else {
6065                        result.addAll(matchAllList);
6066                    }
6067                }
6068
6069                // If there is nothing selected, add all candidates and remove the ones that the user
6070                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6071                if (result.size() == 0) {
6072                    result.addAll(candidates);
6073                    result.removeAll(neverList);
6074                }
6075            }
6076        }
6077        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6078            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6079                    result.size());
6080            for (ResolveInfo info : result) {
6081                Slog.v(TAG, "  + " + info.activityInfo);
6082            }
6083        }
6084        return result;
6085    }
6086
6087    // Returns a packed value as a long:
6088    //
6089    // high 'int'-sized word: link status: undefined/ask/never/always.
6090    // low 'int'-sized word: relative priority among 'always' results.
6091    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6092        long result = ps.getDomainVerificationStatusForUser(userId);
6093        // if none available, get the master status
6094        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6095            if (ps.getIntentFilterVerificationInfo() != null) {
6096                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6097            }
6098        }
6099        return result;
6100    }
6101
6102    private ResolveInfo querySkipCurrentProfileIntents(
6103            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6104            int flags, int sourceUserId) {
6105        if (matchingFilters != null) {
6106            int size = matchingFilters.size();
6107            for (int i = 0; i < size; i ++) {
6108                CrossProfileIntentFilter filter = matchingFilters.get(i);
6109                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6110                    // Checking if there are activities in the target user that can handle the
6111                    // intent.
6112                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6113                            resolvedType, flags, sourceUserId);
6114                    if (resolveInfo != null) {
6115                        return resolveInfo;
6116                    }
6117                }
6118            }
6119        }
6120        return null;
6121    }
6122
6123    // Return matching ResolveInfo in target user if any.
6124    private ResolveInfo queryCrossProfileIntents(
6125            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6126            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6127        if (matchingFilters != null) {
6128            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6129            // match the same intent. For performance reasons, it is better not to
6130            // run queryIntent twice for the same userId
6131            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6132            int size = matchingFilters.size();
6133            for (int i = 0; i < size; i++) {
6134                CrossProfileIntentFilter filter = matchingFilters.get(i);
6135                int targetUserId = filter.getTargetUserId();
6136                boolean skipCurrentProfile =
6137                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6138                boolean skipCurrentProfileIfNoMatchFound =
6139                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6140                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6141                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6142                    // Checking if there are activities in the target user that can handle the
6143                    // intent.
6144                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6145                            resolvedType, flags, sourceUserId);
6146                    if (resolveInfo != null) return resolveInfo;
6147                    alreadyTriedUserIds.put(targetUserId, true);
6148                }
6149            }
6150        }
6151        return null;
6152    }
6153
6154    /**
6155     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6156     * will forward the intent to the filter's target user.
6157     * Otherwise, returns null.
6158     */
6159    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6160            String resolvedType, int flags, int sourceUserId) {
6161        int targetUserId = filter.getTargetUserId();
6162        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6163                resolvedType, flags, targetUserId);
6164        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6165            // If all the matches in the target profile are suspended, return null.
6166            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6167                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6168                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6169                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6170                            targetUserId);
6171                }
6172            }
6173        }
6174        return null;
6175    }
6176
6177    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6178            int sourceUserId, int targetUserId) {
6179        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6180        long ident = Binder.clearCallingIdentity();
6181        boolean targetIsProfile;
6182        try {
6183            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6184        } finally {
6185            Binder.restoreCallingIdentity(ident);
6186        }
6187        String className;
6188        if (targetIsProfile) {
6189            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6190        } else {
6191            className = FORWARD_INTENT_TO_PARENT;
6192        }
6193        ComponentName forwardingActivityComponentName = new ComponentName(
6194                mAndroidApplication.packageName, className);
6195        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6196                sourceUserId);
6197        if (!targetIsProfile) {
6198            forwardingActivityInfo.showUserIcon = targetUserId;
6199            forwardingResolveInfo.noResourceId = true;
6200        }
6201        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6202        forwardingResolveInfo.priority = 0;
6203        forwardingResolveInfo.preferredOrder = 0;
6204        forwardingResolveInfo.match = 0;
6205        forwardingResolveInfo.isDefault = true;
6206        forwardingResolveInfo.filter = filter;
6207        forwardingResolveInfo.targetUserId = targetUserId;
6208        return forwardingResolveInfo;
6209    }
6210
6211    @Override
6212    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6213            Intent[] specifics, String[] specificTypes, Intent intent,
6214            String resolvedType, int flags, int userId) {
6215        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6216                specificTypes, intent, resolvedType, flags, userId));
6217    }
6218
6219    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6220            Intent[] specifics, String[] specificTypes, Intent intent,
6221            String resolvedType, int flags, int userId) {
6222        if (!sUserManager.exists(userId)) return Collections.emptyList();
6223        flags = updateFlagsForResolve(flags, userId, intent);
6224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6225                false /* requireFullPermission */, false /* checkShell */,
6226                "query intent activity options");
6227        final String resultsAction = intent.getAction();
6228
6229        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6230                | PackageManager.GET_RESOLVED_FILTER, userId);
6231
6232        if (DEBUG_INTENT_MATCHING) {
6233            Log.v(TAG, "Query " + intent + ": " + results);
6234        }
6235
6236        int specificsPos = 0;
6237        int N;
6238
6239        // todo: note that the algorithm used here is O(N^2).  This
6240        // isn't a problem in our current environment, but if we start running
6241        // into situations where we have more than 5 or 10 matches then this
6242        // should probably be changed to something smarter...
6243
6244        // First we go through and resolve each of the specific items
6245        // that were supplied, taking care of removing any corresponding
6246        // duplicate items in the generic resolve list.
6247        if (specifics != null) {
6248            for (int i=0; i<specifics.length; i++) {
6249                final Intent sintent = specifics[i];
6250                if (sintent == null) {
6251                    continue;
6252                }
6253
6254                if (DEBUG_INTENT_MATCHING) {
6255                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6256                }
6257
6258                String action = sintent.getAction();
6259                if (resultsAction != null && resultsAction.equals(action)) {
6260                    // If this action was explicitly requested, then don't
6261                    // remove things that have it.
6262                    action = null;
6263                }
6264
6265                ResolveInfo ri = null;
6266                ActivityInfo ai = null;
6267
6268                ComponentName comp = sintent.getComponent();
6269                if (comp == null) {
6270                    ri = resolveIntent(
6271                        sintent,
6272                        specificTypes != null ? specificTypes[i] : null,
6273                            flags, userId);
6274                    if (ri == null) {
6275                        continue;
6276                    }
6277                    if (ri == mResolveInfo) {
6278                        // ACK!  Must do something better with this.
6279                    }
6280                    ai = ri.activityInfo;
6281                    comp = new ComponentName(ai.applicationInfo.packageName,
6282                            ai.name);
6283                } else {
6284                    ai = getActivityInfo(comp, flags, userId);
6285                    if (ai == null) {
6286                        continue;
6287                    }
6288                }
6289
6290                // Look for any generic query activities that are duplicates
6291                // of this specific one, and remove them from the results.
6292                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6293                N = results.size();
6294                int j;
6295                for (j=specificsPos; j<N; j++) {
6296                    ResolveInfo sri = results.get(j);
6297                    if ((sri.activityInfo.name.equals(comp.getClassName())
6298                            && sri.activityInfo.applicationInfo.packageName.equals(
6299                                    comp.getPackageName()))
6300                        || (action != null && sri.filter.matchAction(action))) {
6301                        results.remove(j);
6302                        if (DEBUG_INTENT_MATCHING) Log.v(
6303                            TAG, "Removing duplicate item from " + j
6304                            + " due to specific " + specificsPos);
6305                        if (ri == null) {
6306                            ri = sri;
6307                        }
6308                        j--;
6309                        N--;
6310                    }
6311                }
6312
6313                // Add this specific item to its proper place.
6314                if (ri == null) {
6315                    ri = new ResolveInfo();
6316                    ri.activityInfo = ai;
6317                }
6318                results.add(specificsPos, ri);
6319                ri.specificIndex = i;
6320                specificsPos++;
6321            }
6322        }
6323
6324        // Now we go through the remaining generic results and remove any
6325        // duplicate actions that are found here.
6326        N = results.size();
6327        for (int i=specificsPos; i<N-1; i++) {
6328            final ResolveInfo rii = results.get(i);
6329            if (rii.filter == null) {
6330                continue;
6331            }
6332
6333            // Iterate over all of the actions of this result's intent
6334            // filter...  typically this should be just one.
6335            final Iterator<String> it = rii.filter.actionsIterator();
6336            if (it == null) {
6337                continue;
6338            }
6339            while (it.hasNext()) {
6340                final String action = it.next();
6341                if (resultsAction != null && resultsAction.equals(action)) {
6342                    // If this action was explicitly requested, then don't
6343                    // remove things that have it.
6344                    continue;
6345                }
6346                for (int j=i+1; j<N; j++) {
6347                    final ResolveInfo rij = results.get(j);
6348                    if (rij.filter != null && rij.filter.hasAction(action)) {
6349                        results.remove(j);
6350                        if (DEBUG_INTENT_MATCHING) Log.v(
6351                            TAG, "Removing duplicate item from " + j
6352                            + " due to action " + action + " at " + i);
6353                        j--;
6354                        N--;
6355                    }
6356                }
6357            }
6358
6359            // If the caller didn't request filter information, drop it now
6360            // so we don't have to marshall/unmarshall it.
6361            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6362                rii.filter = null;
6363            }
6364        }
6365
6366        // Filter out the caller activity if so requested.
6367        if (caller != null) {
6368            N = results.size();
6369            for (int i=0; i<N; i++) {
6370                ActivityInfo ainfo = results.get(i).activityInfo;
6371                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6372                        && caller.getClassName().equals(ainfo.name)) {
6373                    results.remove(i);
6374                    break;
6375                }
6376            }
6377        }
6378
6379        // If the caller didn't request filter information,
6380        // drop them now so we don't have to
6381        // marshall/unmarshall it.
6382        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6383            N = results.size();
6384            for (int i=0; i<N; i++) {
6385                results.get(i).filter = null;
6386            }
6387        }
6388
6389        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6390        return results;
6391    }
6392
6393    @Override
6394    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6395            String resolvedType, int flags, int userId) {
6396        return new ParceledListSlice<>(
6397                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6398    }
6399
6400    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6401            String resolvedType, int flags, int userId) {
6402        if (!sUserManager.exists(userId)) return Collections.emptyList();
6403        flags = updateFlagsForResolve(flags, userId, intent);
6404        ComponentName comp = intent.getComponent();
6405        if (comp == null) {
6406            if (intent.getSelector() != null) {
6407                intent = intent.getSelector();
6408                comp = intent.getComponent();
6409            }
6410        }
6411        if (comp != null) {
6412            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6413            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6414            if (ai != null) {
6415                ResolveInfo ri = new ResolveInfo();
6416                ri.activityInfo = ai;
6417                list.add(ri);
6418            }
6419            return list;
6420        }
6421
6422        // reader
6423        synchronized (mPackages) {
6424            String pkgName = intent.getPackage();
6425            if (pkgName == null) {
6426                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6427            }
6428            final PackageParser.Package pkg = mPackages.get(pkgName);
6429            if (pkg != null) {
6430                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6431                        userId);
6432            }
6433            return Collections.emptyList();
6434        }
6435    }
6436
6437    @Override
6438    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6439        if (!sUserManager.exists(userId)) return null;
6440        flags = updateFlagsForResolve(flags, userId, intent);
6441        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6442        if (query != null) {
6443            if (query.size() >= 1) {
6444                // If there is more than one service with the same priority,
6445                // just arbitrarily pick the first one.
6446                return query.get(0);
6447            }
6448        }
6449        return null;
6450    }
6451
6452    @Override
6453    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6454            String resolvedType, int flags, int userId) {
6455        return new ParceledListSlice<>(
6456                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6457    }
6458
6459    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6460            String resolvedType, int flags, int userId) {
6461        if (!sUserManager.exists(userId)) return Collections.emptyList();
6462        flags = updateFlagsForResolve(flags, userId, intent);
6463        ComponentName comp = intent.getComponent();
6464        if (comp == null) {
6465            if (intent.getSelector() != null) {
6466                intent = intent.getSelector();
6467                comp = intent.getComponent();
6468            }
6469        }
6470        if (comp != null) {
6471            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6472            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6473            if (si != null) {
6474                final ResolveInfo ri = new ResolveInfo();
6475                ri.serviceInfo = si;
6476                list.add(ri);
6477            }
6478            return list;
6479        }
6480
6481        // reader
6482        synchronized (mPackages) {
6483            String pkgName = intent.getPackage();
6484            if (pkgName == null) {
6485                return mServices.queryIntent(intent, resolvedType, flags, userId);
6486            }
6487            final PackageParser.Package pkg = mPackages.get(pkgName);
6488            if (pkg != null) {
6489                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6490                        userId);
6491            }
6492            return Collections.emptyList();
6493        }
6494    }
6495
6496    @Override
6497    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6498            String resolvedType, int flags, int userId) {
6499        return new ParceledListSlice<>(
6500                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6501    }
6502
6503    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6504            Intent intent, String resolvedType, int flags, int userId) {
6505        if (!sUserManager.exists(userId)) return Collections.emptyList();
6506        flags = updateFlagsForResolve(flags, userId, intent);
6507        ComponentName comp = intent.getComponent();
6508        if (comp == null) {
6509            if (intent.getSelector() != null) {
6510                intent = intent.getSelector();
6511                comp = intent.getComponent();
6512            }
6513        }
6514        if (comp != null) {
6515            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6516            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6517            if (pi != null) {
6518                final ResolveInfo ri = new ResolveInfo();
6519                ri.providerInfo = pi;
6520                list.add(ri);
6521            }
6522            return list;
6523        }
6524
6525        // reader
6526        synchronized (mPackages) {
6527            String pkgName = intent.getPackage();
6528            if (pkgName == null) {
6529                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6530            }
6531            final PackageParser.Package pkg = mPackages.get(pkgName);
6532            if (pkg != null) {
6533                return mProviders.queryIntentForPackage(
6534                        intent, resolvedType, flags, pkg.providers, userId);
6535            }
6536            return Collections.emptyList();
6537        }
6538    }
6539
6540    @Override
6541    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6542        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6543        flags = updateFlagsForPackage(flags, userId, null);
6544        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6546                true /* requireFullPermission */, false /* checkShell */,
6547                "get installed packages");
6548
6549        // writer
6550        synchronized (mPackages) {
6551            ArrayList<PackageInfo> list;
6552            if (listUninstalled) {
6553                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6554                for (PackageSetting ps : mSettings.mPackages.values()) {
6555                    final PackageInfo pi;
6556                    if (ps.pkg != null) {
6557                        pi = generatePackageInfo(ps, flags, userId);
6558                    } else {
6559                        pi = generatePackageInfo(ps, flags, userId);
6560                    }
6561                    if (pi != null) {
6562                        list.add(pi);
6563                    }
6564                }
6565            } else {
6566                list = new ArrayList<PackageInfo>(mPackages.size());
6567                for (PackageParser.Package p : mPackages.values()) {
6568                    final PackageInfo pi =
6569                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6570                    if (pi != null) {
6571                        list.add(pi);
6572                    }
6573                }
6574            }
6575
6576            return new ParceledListSlice<PackageInfo>(list);
6577        }
6578    }
6579
6580    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6581            String[] permissions, boolean[] tmp, int flags, int userId) {
6582        int numMatch = 0;
6583        final PermissionsState permissionsState = ps.getPermissionsState();
6584        for (int i=0; i<permissions.length; i++) {
6585            final String permission = permissions[i];
6586            if (permissionsState.hasPermission(permission, userId)) {
6587                tmp[i] = true;
6588                numMatch++;
6589            } else {
6590                tmp[i] = false;
6591            }
6592        }
6593        if (numMatch == 0) {
6594            return;
6595        }
6596        final PackageInfo pi;
6597        if (ps.pkg != null) {
6598            pi = generatePackageInfo(ps, flags, userId);
6599        } else {
6600            pi = generatePackageInfo(ps, flags, userId);
6601        }
6602        // The above might return null in cases of uninstalled apps or install-state
6603        // skew across users/profiles.
6604        if (pi != null) {
6605            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6606                if (numMatch == permissions.length) {
6607                    pi.requestedPermissions = permissions;
6608                } else {
6609                    pi.requestedPermissions = new String[numMatch];
6610                    numMatch = 0;
6611                    for (int i=0; i<permissions.length; i++) {
6612                        if (tmp[i]) {
6613                            pi.requestedPermissions[numMatch] = permissions[i];
6614                            numMatch++;
6615                        }
6616                    }
6617                }
6618            }
6619            list.add(pi);
6620        }
6621    }
6622
6623    @Override
6624    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6625            String[] permissions, int flags, int userId) {
6626        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6627        flags = updateFlagsForPackage(flags, userId, permissions);
6628        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6629                true /* requireFullPermission */, false /* checkShell */,
6630                "get packages holding permissions");
6631        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6632
6633        // writer
6634        synchronized (mPackages) {
6635            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6636            boolean[] tmpBools = new boolean[permissions.length];
6637            if (listUninstalled) {
6638                for (PackageSetting ps : mSettings.mPackages.values()) {
6639                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6640                            userId);
6641                }
6642            } else {
6643                for (PackageParser.Package pkg : mPackages.values()) {
6644                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6645                    if (ps != null) {
6646                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6647                                userId);
6648                    }
6649                }
6650            }
6651
6652            return new ParceledListSlice<PackageInfo>(list);
6653        }
6654    }
6655
6656    @Override
6657    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6658        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6659        flags = updateFlagsForApplication(flags, userId, null);
6660        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6661
6662        // writer
6663        synchronized (mPackages) {
6664            ArrayList<ApplicationInfo> list;
6665            if (listUninstalled) {
6666                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6667                for (PackageSetting ps : mSettings.mPackages.values()) {
6668                    ApplicationInfo ai;
6669                    int effectiveFlags = flags;
6670                    if (ps.isSystem()) {
6671                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6672                    }
6673                    if (ps.pkg != null) {
6674                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6675                                ps.readUserState(userId), userId);
6676                    } else {
6677                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6678                                userId);
6679                    }
6680                    if (ai != null) {
6681                        list.add(ai);
6682                    }
6683                }
6684            } else {
6685                list = new ArrayList<ApplicationInfo>(mPackages.size());
6686                for (PackageParser.Package p : mPackages.values()) {
6687                    if (p.mExtras != null) {
6688                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6689                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6690                        if (ai != null) {
6691                            list.add(ai);
6692                        }
6693                    }
6694                }
6695            }
6696
6697            return new ParceledListSlice<ApplicationInfo>(list);
6698        }
6699    }
6700
6701    @Override
6702    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6703        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6704            return null;
6705        }
6706
6707        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6708                "getEphemeralApplications");
6709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6710                true /* requireFullPermission */, false /* checkShell */,
6711                "getEphemeralApplications");
6712        synchronized (mPackages) {
6713            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6714                    .getEphemeralApplicationsLPw(userId);
6715            if (ephemeralApps != null) {
6716                return new ParceledListSlice<>(ephemeralApps);
6717            }
6718        }
6719        return null;
6720    }
6721
6722    @Override
6723    public boolean isEphemeralApplication(String packageName, int userId) {
6724        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6725                true /* requireFullPermission */, false /* checkShell */,
6726                "isEphemeral");
6727        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6728            return false;
6729        }
6730
6731        if (!isCallerSameApp(packageName)) {
6732            return false;
6733        }
6734        synchronized (mPackages) {
6735            PackageParser.Package pkg = mPackages.get(packageName);
6736            if (pkg != null) {
6737                return pkg.applicationInfo.isEphemeralApp();
6738            }
6739        }
6740        return false;
6741    }
6742
6743    @Override
6744    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6745        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6746            return null;
6747        }
6748
6749        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6750                true /* requireFullPermission */, false /* checkShell */,
6751                "getCookie");
6752        if (!isCallerSameApp(packageName)) {
6753            return null;
6754        }
6755        synchronized (mPackages) {
6756            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6757                    packageName, userId);
6758        }
6759    }
6760
6761    @Override
6762    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6763        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6764            return true;
6765        }
6766
6767        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6768                true /* requireFullPermission */, true /* checkShell */,
6769                "setCookie");
6770        if (!isCallerSameApp(packageName)) {
6771            return false;
6772        }
6773        synchronized (mPackages) {
6774            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6775                    packageName, cookie, userId);
6776        }
6777    }
6778
6779    @Override
6780    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6781        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6782            return null;
6783        }
6784
6785        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6786                "getEphemeralApplicationIcon");
6787        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6788                true /* requireFullPermission */, false /* checkShell */,
6789                "getEphemeralApplicationIcon");
6790        synchronized (mPackages) {
6791            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6792                    packageName, userId);
6793        }
6794    }
6795
6796    private boolean isCallerSameApp(String packageName) {
6797        PackageParser.Package pkg = mPackages.get(packageName);
6798        return pkg != null
6799                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6800    }
6801
6802    @Override
6803    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6804        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6805    }
6806
6807    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6808        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6809
6810        // reader
6811        synchronized (mPackages) {
6812            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6813            final int userId = UserHandle.getCallingUserId();
6814            while (i.hasNext()) {
6815                final PackageParser.Package p = i.next();
6816                if (p.applicationInfo == null) continue;
6817
6818                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6819                        && !p.applicationInfo.isDirectBootAware();
6820                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6821                        && p.applicationInfo.isDirectBootAware();
6822
6823                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6824                        && (!mSafeMode || isSystemApp(p))
6825                        && (matchesUnaware || matchesAware)) {
6826                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6827                    if (ps != null) {
6828                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6829                                ps.readUserState(userId), userId);
6830                        if (ai != null) {
6831                            finalList.add(ai);
6832                        }
6833                    }
6834                }
6835            }
6836        }
6837
6838        return finalList;
6839    }
6840
6841    @Override
6842    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6843        if (!sUserManager.exists(userId)) return null;
6844        flags = updateFlagsForComponent(flags, userId, name);
6845        // reader
6846        synchronized (mPackages) {
6847            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6848            PackageSetting ps = provider != null
6849                    ? mSettings.mPackages.get(provider.owner.packageName)
6850                    : null;
6851            return ps != null
6852                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6853                    ? PackageParser.generateProviderInfo(provider, flags,
6854                            ps.readUserState(userId), userId)
6855                    : null;
6856        }
6857    }
6858
6859    /**
6860     * @deprecated
6861     */
6862    @Deprecated
6863    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6864        // reader
6865        synchronized (mPackages) {
6866            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6867                    .entrySet().iterator();
6868            final int userId = UserHandle.getCallingUserId();
6869            while (i.hasNext()) {
6870                Map.Entry<String, PackageParser.Provider> entry = i.next();
6871                PackageParser.Provider p = entry.getValue();
6872                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6873
6874                if (ps != null && p.syncable
6875                        && (!mSafeMode || (p.info.applicationInfo.flags
6876                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6877                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6878                            ps.readUserState(userId), userId);
6879                    if (info != null) {
6880                        outNames.add(entry.getKey());
6881                        outInfo.add(info);
6882                    }
6883                }
6884            }
6885        }
6886    }
6887
6888    @Override
6889    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6890            int uid, int flags) {
6891        final int userId = processName != null ? UserHandle.getUserId(uid)
6892                : UserHandle.getCallingUserId();
6893        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6894        flags = updateFlagsForComponent(flags, userId, processName);
6895
6896        ArrayList<ProviderInfo> finalList = null;
6897        // reader
6898        synchronized (mPackages) {
6899            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6900            while (i.hasNext()) {
6901                final PackageParser.Provider p = i.next();
6902                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6903                if (ps != null && p.info.authority != null
6904                        && (processName == null
6905                                || (p.info.processName.equals(processName)
6906                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6907                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6908                    if (finalList == null) {
6909                        finalList = new ArrayList<ProviderInfo>(3);
6910                    }
6911                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6912                            ps.readUserState(userId), userId);
6913                    if (info != null) {
6914                        finalList.add(info);
6915                    }
6916                }
6917            }
6918        }
6919
6920        if (finalList != null) {
6921            Collections.sort(finalList, mProviderInitOrderSorter);
6922            return new ParceledListSlice<ProviderInfo>(finalList);
6923        }
6924
6925        return ParceledListSlice.emptyList();
6926    }
6927
6928    @Override
6929    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6930        // reader
6931        synchronized (mPackages) {
6932            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6933            return PackageParser.generateInstrumentationInfo(i, flags);
6934        }
6935    }
6936
6937    @Override
6938    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6939            String targetPackage, int flags) {
6940        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6941    }
6942
6943    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6944            int flags) {
6945        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6946
6947        // reader
6948        synchronized (mPackages) {
6949            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6950            while (i.hasNext()) {
6951                final PackageParser.Instrumentation p = i.next();
6952                if (targetPackage == null
6953                        || targetPackage.equals(p.info.targetPackage)) {
6954                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6955                            flags);
6956                    if (ii != null) {
6957                        finalList.add(ii);
6958                    }
6959                }
6960            }
6961        }
6962
6963        return finalList;
6964    }
6965
6966    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6967        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6968        if (overlays == null) {
6969            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6970            return;
6971        }
6972        for (PackageParser.Package opkg : overlays.values()) {
6973            // Not much to do if idmap fails: we already logged the error
6974            // and we certainly don't want to abort installation of pkg simply
6975            // because an overlay didn't fit properly. For these reasons,
6976            // ignore the return value of createIdmapForPackagePairLI.
6977            createIdmapForPackagePairLI(pkg, opkg);
6978        }
6979    }
6980
6981    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6982            PackageParser.Package opkg) {
6983        if (!opkg.mTrustedOverlay) {
6984            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6985                    opkg.baseCodePath + ": overlay not trusted");
6986            return false;
6987        }
6988        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6989        if (overlaySet == null) {
6990            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6991                    opkg.baseCodePath + " but target package has no known overlays");
6992            return false;
6993        }
6994        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6995        // TODO: generate idmap for split APKs
6996        try {
6997            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6998        } catch (InstallerException e) {
6999            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7000                    + opkg.baseCodePath);
7001            return false;
7002        }
7003        PackageParser.Package[] overlayArray =
7004            overlaySet.values().toArray(new PackageParser.Package[0]);
7005        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7006            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7007                return p1.mOverlayPriority - p2.mOverlayPriority;
7008            }
7009        };
7010        Arrays.sort(overlayArray, cmp);
7011
7012        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7013        int i = 0;
7014        for (PackageParser.Package p : overlayArray) {
7015            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7016        }
7017        return true;
7018    }
7019
7020    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7021        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7022        try {
7023            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7024        } finally {
7025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7026        }
7027    }
7028
7029    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7030        final File[] files = dir.listFiles();
7031        if (ArrayUtils.isEmpty(files)) {
7032            Log.d(TAG, "No files in app dir " + dir);
7033            return;
7034        }
7035
7036        if (DEBUG_PACKAGE_SCANNING) {
7037            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7038                    + " flags=0x" + Integer.toHexString(parseFlags));
7039        }
7040        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7041                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7042
7043        // Submit files for parsing in parallel
7044        int fileCount = 0;
7045        for (File file : files) {
7046            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7047                    && !PackageInstallerService.isStageName(file.getName());
7048            if (!isPackage) {
7049                // Ignore entries which are not packages
7050                continue;
7051            }
7052            parallelPackageParser.submit(file, parseFlags);
7053            fileCount++;
7054        }
7055
7056        // Process results one by one
7057        for (; fileCount > 0; fileCount--) {
7058            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7059            Throwable throwable = parseResult.throwable;
7060            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7061
7062            if (throwable == null) {
7063                try {
7064                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7065                            currentTime, null);
7066                } catch (PackageManagerException e) {
7067                    errorCode = e.error;
7068                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7069                }
7070            } else if (throwable instanceof PackageParser.PackageParserException) {
7071                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7072                        throwable;
7073                errorCode = e.error;
7074                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7075            } else {
7076                throw new IllegalStateException("Unexpected exception occurred while parsing "
7077                        + parseResult.scanFile, throwable);
7078            }
7079
7080            // Delete invalid userdata apps
7081            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7082                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7083                logCriticalInfo(Log.WARN,
7084                        "Deleting invalid package at " + parseResult.scanFile);
7085                removeCodePathLI(parseResult.scanFile);
7086            }
7087        }
7088        parallelPackageParser.close();
7089    }
7090
7091    private static File getSettingsProblemFile() {
7092        File dataDir = Environment.getDataDirectory();
7093        File systemDir = new File(dataDir, "system");
7094        File fname = new File(systemDir, "uiderrors.txt");
7095        return fname;
7096    }
7097
7098    static void reportSettingsProblem(int priority, String msg) {
7099        logCriticalInfo(priority, msg);
7100    }
7101
7102    static void logCriticalInfo(int priority, String msg) {
7103        Slog.println(priority, TAG, msg);
7104        EventLogTags.writePmCriticalInfo(msg);
7105        try {
7106            File fname = getSettingsProblemFile();
7107            FileOutputStream out = new FileOutputStream(fname, true);
7108            PrintWriter pw = new FastPrintWriter(out);
7109            SimpleDateFormat formatter = new SimpleDateFormat();
7110            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7111            pw.println(dateString + ": " + msg);
7112            pw.close();
7113            FileUtils.setPermissions(
7114                    fname.toString(),
7115                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7116                    -1, -1);
7117        } catch (java.io.IOException e) {
7118        }
7119    }
7120
7121    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7122        if (srcFile.isDirectory()) {
7123            final File baseFile = new File(pkg.baseCodePath);
7124            long maxModifiedTime = baseFile.lastModified();
7125            if (pkg.splitCodePaths != null) {
7126                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7127                    final File splitFile = new File(pkg.splitCodePaths[i]);
7128                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7129                }
7130            }
7131            return maxModifiedTime;
7132        }
7133        return srcFile.lastModified();
7134    }
7135
7136    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7137            final int policyFlags) throws PackageManagerException {
7138        // When upgrading from pre-N MR1, verify the package time stamp using the package
7139        // directory and not the APK file.
7140        final long lastModifiedTime = mIsPreNMR1Upgrade
7141                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7142        if (ps != null
7143                && ps.codePath.equals(srcFile)
7144                && ps.timeStamp == lastModifiedTime
7145                && !isCompatSignatureUpdateNeeded(pkg)
7146                && !isRecoverSignatureUpdateNeeded(pkg)) {
7147            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7148            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7149            ArraySet<PublicKey> signingKs;
7150            synchronized (mPackages) {
7151                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7152            }
7153            if (ps.signatures.mSignatures != null
7154                    && ps.signatures.mSignatures.length != 0
7155                    && signingKs != null) {
7156                // Optimization: reuse the existing cached certificates
7157                // if the package appears to be unchanged.
7158                pkg.mSignatures = ps.signatures.mSignatures;
7159                pkg.mSigningKeys = signingKs;
7160                return;
7161            }
7162
7163            Slog.w(TAG, "PackageSetting for " + ps.name
7164                    + " is missing signatures.  Collecting certs again to recover them.");
7165        } else {
7166            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7167        }
7168
7169        try {
7170            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7171            PackageParser.collectCertificates(pkg, policyFlags);
7172        } catch (PackageParserException e) {
7173            throw PackageManagerException.from(e);
7174        } finally {
7175            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7176        }
7177    }
7178
7179    /**
7180     *  Traces a package scan.
7181     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7182     */
7183    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7184            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7185        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7186        try {
7187            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7188        } finally {
7189            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7190        }
7191    }
7192
7193    /**
7194     *  Scans a package and returns the newly parsed package.
7195     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7196     */
7197    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7198            long currentTime, UserHandle user) throws PackageManagerException {
7199        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7200        PackageParser pp = new PackageParser();
7201        pp.setSeparateProcesses(mSeparateProcesses);
7202        pp.setOnlyCoreApps(mOnlyCore);
7203        pp.setDisplayMetrics(mMetrics);
7204
7205        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7206            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7207        }
7208
7209        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7210        final PackageParser.Package pkg;
7211        try {
7212            pkg = pp.parsePackage(scanFile, parseFlags);
7213        } catch (PackageParserException e) {
7214            throw PackageManagerException.from(e);
7215        } finally {
7216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7217        }
7218
7219        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7220    }
7221
7222    /**
7223     *  Scans a package and returns the newly parsed package.
7224     *  @throws PackageManagerException on a parse error.
7225     */
7226    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7227            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7228            throws PackageManagerException {
7229        // If the package has children and this is the first dive in the function
7230        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7231        // packages (parent and children) would be successfully scanned before the
7232        // actual scan since scanning mutates internal state and we want to atomically
7233        // install the package and its children.
7234        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7235            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7236                scanFlags |= SCAN_CHECK_ONLY;
7237            }
7238        } else {
7239            scanFlags &= ~SCAN_CHECK_ONLY;
7240        }
7241
7242        // Scan the parent
7243        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7244                scanFlags, currentTime, user);
7245
7246        // Scan the children
7247        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7248        for (int i = 0; i < childCount; i++) {
7249            PackageParser.Package childPackage = pkg.childPackages.get(i);
7250            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7251                    currentTime, user);
7252        }
7253
7254
7255        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7256            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7257        }
7258
7259        return scannedPkg;
7260    }
7261
7262    /**
7263     *  Scans a package and returns the newly parsed package.
7264     *  @throws PackageManagerException on a parse error.
7265     */
7266    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7267            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7268            throws PackageManagerException {
7269        PackageSetting ps = null;
7270        PackageSetting updatedPkg;
7271        // reader
7272        synchronized (mPackages) {
7273            // Look to see if we already know about this package.
7274            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7275            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7276                // This package has been renamed to its original name.  Let's
7277                // use that.
7278                ps = mSettings.getPackageLPr(oldName);
7279            }
7280            // If there was no original package, see one for the real package name.
7281            if (ps == null) {
7282                ps = mSettings.getPackageLPr(pkg.packageName);
7283            }
7284            // Check to see if this package could be hiding/updating a system
7285            // package.  Must look for it either under the original or real
7286            // package name depending on our state.
7287            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7288            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7289
7290            // If this is a package we don't know about on the system partition, we
7291            // may need to remove disabled child packages on the system partition
7292            // or may need to not add child packages if the parent apk is updated
7293            // on the data partition and no longer defines this child package.
7294            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7295                // If this is a parent package for an updated system app and this system
7296                // app got an OTA update which no longer defines some of the child packages
7297                // we have to prune them from the disabled system packages.
7298                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7299                if (disabledPs != null) {
7300                    final int scannedChildCount = (pkg.childPackages != null)
7301                            ? pkg.childPackages.size() : 0;
7302                    final int disabledChildCount = disabledPs.childPackageNames != null
7303                            ? disabledPs.childPackageNames.size() : 0;
7304                    for (int i = 0; i < disabledChildCount; i++) {
7305                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7306                        boolean disabledPackageAvailable = false;
7307                        for (int j = 0; j < scannedChildCount; j++) {
7308                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7309                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7310                                disabledPackageAvailable = true;
7311                                break;
7312                            }
7313                         }
7314                         if (!disabledPackageAvailable) {
7315                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7316                         }
7317                    }
7318                }
7319            }
7320        }
7321
7322        boolean updatedPkgBetter = false;
7323        // First check if this is a system package that may involve an update
7324        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7325            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7326            // it needs to drop FLAG_PRIVILEGED.
7327            if (locationIsPrivileged(scanFile)) {
7328                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7329            } else {
7330                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7331            }
7332
7333            if (ps != null && !ps.codePath.equals(scanFile)) {
7334                // The path has changed from what was last scanned...  check the
7335                // version of the new path against what we have stored to determine
7336                // what to do.
7337                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7338                if (pkg.mVersionCode <= ps.versionCode) {
7339                    // The system package has been updated and the code path does not match
7340                    // Ignore entry. Skip it.
7341                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7342                            + " ignored: updated version " + ps.versionCode
7343                            + " better than this " + pkg.mVersionCode);
7344                    if (!updatedPkg.codePath.equals(scanFile)) {
7345                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7346                                + ps.name + " changing from " + updatedPkg.codePathString
7347                                + " to " + scanFile);
7348                        updatedPkg.codePath = scanFile;
7349                        updatedPkg.codePathString = scanFile.toString();
7350                        updatedPkg.resourcePath = scanFile;
7351                        updatedPkg.resourcePathString = scanFile.toString();
7352                    }
7353                    updatedPkg.pkg = pkg;
7354                    updatedPkg.versionCode = pkg.mVersionCode;
7355
7356                    // Update the disabled system child packages to point to the package too.
7357                    final int childCount = updatedPkg.childPackageNames != null
7358                            ? updatedPkg.childPackageNames.size() : 0;
7359                    for (int i = 0; i < childCount; i++) {
7360                        String childPackageName = updatedPkg.childPackageNames.get(i);
7361                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7362                                childPackageName);
7363                        if (updatedChildPkg != null) {
7364                            updatedChildPkg.pkg = pkg;
7365                            updatedChildPkg.versionCode = pkg.mVersionCode;
7366                        }
7367                    }
7368
7369                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7370                            + scanFile + " ignored: updated version " + ps.versionCode
7371                            + " better than this " + pkg.mVersionCode);
7372                } else {
7373                    // The current app on the system partition is better than
7374                    // what we have updated to on the data partition; switch
7375                    // back to the system partition version.
7376                    // At this point, its safely assumed that package installation for
7377                    // apps in system partition will go through. If not there won't be a working
7378                    // version of the app
7379                    // writer
7380                    synchronized (mPackages) {
7381                        // Just remove the loaded entries from package lists.
7382                        mPackages.remove(ps.name);
7383                    }
7384
7385                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7386                            + " reverting from " + ps.codePathString
7387                            + ": new version " + pkg.mVersionCode
7388                            + " better than installed " + ps.versionCode);
7389
7390                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7391                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7392                    synchronized (mInstallLock) {
7393                        args.cleanUpResourcesLI();
7394                    }
7395                    synchronized (mPackages) {
7396                        mSettings.enableSystemPackageLPw(ps.name);
7397                    }
7398                    updatedPkgBetter = true;
7399                }
7400            }
7401        }
7402
7403        if (updatedPkg != null) {
7404            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7405            // initially
7406            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7407
7408            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7409            // flag set initially
7410            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7411                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7412            }
7413        }
7414
7415        // Verify certificates against what was last scanned
7416        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7417
7418        /*
7419         * A new system app appeared, but we already had a non-system one of the
7420         * same name installed earlier.
7421         */
7422        boolean shouldHideSystemApp = false;
7423        if (updatedPkg == null && ps != null
7424                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7425            /*
7426             * Check to make sure the signatures match first. If they don't,
7427             * wipe the installed application and its data.
7428             */
7429            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7430                    != PackageManager.SIGNATURE_MATCH) {
7431                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7432                        + " signatures don't match existing userdata copy; removing");
7433                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7434                        "scanPackageInternalLI")) {
7435                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7436                }
7437                ps = null;
7438            } else {
7439                /*
7440                 * If the newly-added system app is an older version than the
7441                 * already installed version, hide it. It will be scanned later
7442                 * and re-added like an update.
7443                 */
7444                if (pkg.mVersionCode <= ps.versionCode) {
7445                    shouldHideSystemApp = true;
7446                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7447                            + " but new version " + pkg.mVersionCode + " better than installed "
7448                            + ps.versionCode + "; hiding system");
7449                } else {
7450                    /*
7451                     * The newly found system app is a newer version that the
7452                     * one previously installed. Simply remove the
7453                     * already-installed application and replace it with our own
7454                     * while keeping the application data.
7455                     */
7456                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7457                            + " reverting from " + ps.codePathString + ": new version "
7458                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7459                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7460                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7461                    synchronized (mInstallLock) {
7462                        args.cleanUpResourcesLI();
7463                    }
7464                }
7465            }
7466        }
7467
7468        // The apk is forward locked (not public) if its code and resources
7469        // are kept in different files. (except for app in either system or
7470        // vendor path).
7471        // TODO grab this value from PackageSettings
7472        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7473            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7474                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7475            }
7476        }
7477
7478        // TODO: extend to support forward-locked splits
7479        String resourcePath = null;
7480        String baseResourcePath = null;
7481        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7482            if (ps != null && ps.resourcePathString != null) {
7483                resourcePath = ps.resourcePathString;
7484                baseResourcePath = ps.resourcePathString;
7485            } else {
7486                // Should not happen at all. Just log an error.
7487                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7488            }
7489        } else {
7490            resourcePath = pkg.codePath;
7491            baseResourcePath = pkg.baseCodePath;
7492        }
7493
7494        // Set application objects path explicitly.
7495        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7496        pkg.setApplicationInfoCodePath(pkg.codePath);
7497        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7498        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7499        pkg.setApplicationInfoResourcePath(resourcePath);
7500        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7501        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7502
7503        // Note that we invoke the following method only if we are about to unpack an application
7504        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7505                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7506
7507        /*
7508         * If the system app should be overridden by a previously installed
7509         * data, hide the system app now and let the /data/app scan pick it up
7510         * again.
7511         */
7512        if (shouldHideSystemApp) {
7513            synchronized (mPackages) {
7514                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7515            }
7516        }
7517
7518        return scannedPkg;
7519    }
7520
7521    private static String fixProcessName(String defProcessName,
7522            String processName) {
7523        if (processName == null) {
7524            return defProcessName;
7525        }
7526        return processName;
7527    }
7528
7529    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7530            throws PackageManagerException {
7531        if (pkgSetting.signatures.mSignatures != null) {
7532            // Already existing package. Make sure signatures match
7533            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7534                    == PackageManager.SIGNATURE_MATCH;
7535            if (!match) {
7536                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7537                        == PackageManager.SIGNATURE_MATCH;
7538            }
7539            if (!match) {
7540                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7541                        == PackageManager.SIGNATURE_MATCH;
7542            }
7543            if (!match) {
7544                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7545                        + pkg.packageName + " signatures do not match the "
7546                        + "previously installed version; ignoring!");
7547            }
7548        }
7549
7550        // Check for shared user signatures
7551        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7552            // Already existing package. Make sure signatures match
7553            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7554                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7555            if (!match) {
7556                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7557                        == PackageManager.SIGNATURE_MATCH;
7558            }
7559            if (!match) {
7560                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7561                        == PackageManager.SIGNATURE_MATCH;
7562            }
7563            if (!match) {
7564                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7565                        "Package " + pkg.packageName
7566                        + " has no signatures that match those in shared user "
7567                        + pkgSetting.sharedUser.name + "; ignoring!");
7568            }
7569        }
7570    }
7571
7572    /**
7573     * Enforces that only the system UID or root's UID can call a method exposed
7574     * via Binder.
7575     *
7576     * @param message used as message if SecurityException is thrown
7577     * @throws SecurityException if the caller is not system or root
7578     */
7579    private static final void enforceSystemOrRoot(String message) {
7580        final int uid = Binder.getCallingUid();
7581        if (uid != Process.SYSTEM_UID && uid != 0) {
7582            throw new SecurityException(message);
7583        }
7584    }
7585
7586    @Override
7587    public void performFstrimIfNeeded() {
7588        enforceSystemOrRoot("Only the system can request fstrim");
7589
7590        // Before everything else, see whether we need to fstrim.
7591        try {
7592            IStorageManager sm = PackageHelper.getStorageManager();
7593            if (sm != null) {
7594                boolean doTrim = false;
7595                final long interval = android.provider.Settings.Global.getLong(
7596                        mContext.getContentResolver(),
7597                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7598                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7599                if (interval > 0) {
7600                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7601                    if (timeSinceLast > interval) {
7602                        doTrim = true;
7603                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7604                                + "; running immediately");
7605                    }
7606                }
7607                if (doTrim) {
7608                    final boolean dexOptDialogShown;
7609                    synchronized (mPackages) {
7610                        dexOptDialogShown = mDexOptDialogShown;
7611                    }
7612                    if (!isFirstBoot() && dexOptDialogShown) {
7613                        try {
7614                            ActivityManager.getService().showBootMessage(
7615                                    mContext.getResources().getString(
7616                                            R.string.android_upgrading_fstrim), true);
7617                        } catch (RemoteException e) {
7618                        }
7619                    }
7620                    sm.runMaintenance();
7621                }
7622            } else {
7623                Slog.e(TAG, "storageManager service unavailable!");
7624            }
7625        } catch (RemoteException e) {
7626            // Can't happen; StorageManagerService is local
7627        }
7628    }
7629
7630    @Override
7631    public void updatePackagesIfNeeded() {
7632        enforceSystemOrRoot("Only the system can request package update");
7633
7634        // We need to re-extract after an OTA.
7635        boolean causeUpgrade = isUpgrade();
7636
7637        // First boot or factory reset.
7638        // Note: we also handle devices that are upgrading to N right now as if it is their
7639        //       first boot, as they do not have profile data.
7640        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7641
7642        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7643        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7644
7645        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7646            return;
7647        }
7648
7649        List<PackageParser.Package> pkgs;
7650        synchronized (mPackages) {
7651            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7652        }
7653
7654        final long startTime = System.nanoTime();
7655        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7656                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7657
7658        final int elapsedTimeSeconds =
7659                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7660
7661        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7662        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7663        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7664        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7665        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7666    }
7667
7668    /**
7669     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7670     * containing statistics about the invocation. The array consists of three elements,
7671     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7672     * and {@code numberOfPackagesFailed}.
7673     */
7674    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7675            String compilerFilter) {
7676
7677        int numberOfPackagesVisited = 0;
7678        int numberOfPackagesOptimized = 0;
7679        int numberOfPackagesSkipped = 0;
7680        int numberOfPackagesFailed = 0;
7681        final int numberOfPackagesToDexopt = pkgs.size();
7682
7683        for (PackageParser.Package pkg : pkgs) {
7684            numberOfPackagesVisited++;
7685
7686            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7687                if (DEBUG_DEXOPT) {
7688                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7689                }
7690                numberOfPackagesSkipped++;
7691                continue;
7692            }
7693
7694            if (DEBUG_DEXOPT) {
7695                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7696                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7697            }
7698
7699            if (showDialog) {
7700                try {
7701                    ActivityManager.getService().showBootMessage(
7702                            mContext.getResources().getString(R.string.android_upgrading_apk,
7703                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7704                } catch (RemoteException e) {
7705                }
7706                synchronized (mPackages) {
7707                    mDexOptDialogShown = true;
7708                }
7709            }
7710
7711            // If the OTA updates a system app which was previously preopted to a non-preopted state
7712            // the app might end up being verified at runtime. That's because by default the apps
7713            // are verify-profile but for preopted apps there's no profile.
7714            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7715            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7716            // filter (by default interpret-only).
7717            // Note that at this stage unused apps are already filtered.
7718            if (isSystemApp(pkg) &&
7719                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7720                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7721                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7722            }
7723
7724            // checkProfiles is false to avoid merging profiles during boot which
7725            // might interfere with background compilation (b/28612421).
7726            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7727            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7728            // trade-off worth doing to save boot time work.
7729            int dexOptStatus = performDexOptTraced(pkg.packageName,
7730                    false /* checkProfiles */,
7731                    compilerFilter,
7732                    false /* force */);
7733            switch (dexOptStatus) {
7734                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7735                    numberOfPackagesOptimized++;
7736                    break;
7737                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7738                    numberOfPackagesSkipped++;
7739                    break;
7740                case PackageDexOptimizer.DEX_OPT_FAILED:
7741                    numberOfPackagesFailed++;
7742                    break;
7743                default:
7744                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7745                    break;
7746            }
7747        }
7748
7749        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7750                numberOfPackagesFailed };
7751    }
7752
7753    @Override
7754    public void notifyPackageUse(String packageName, int reason) {
7755        synchronized (mPackages) {
7756            PackageParser.Package p = mPackages.get(packageName);
7757            if (p == null) {
7758                return;
7759            }
7760            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7761        }
7762    }
7763
7764    @Override
7765    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7766        int userId = UserHandle.getCallingUserId();
7767        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7768        if (ai == null) {
7769            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7770                + loadingPackageName + ", user=" + userId);
7771            return;
7772        }
7773        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7774    }
7775
7776    // TODO: this is not used nor needed. Delete it.
7777    @Override
7778    public boolean performDexOptIfNeeded(String packageName) {
7779        int dexOptStatus = performDexOptTraced(packageName,
7780                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7781        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7782    }
7783
7784    @Override
7785    public boolean performDexOpt(String packageName,
7786            boolean checkProfiles, int compileReason, boolean force) {
7787        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7788                getCompilerFilterForReason(compileReason), force);
7789        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7790    }
7791
7792    @Override
7793    public boolean performDexOptMode(String packageName,
7794            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7795        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7796                targetCompilerFilter, force);
7797        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7798    }
7799
7800    private int performDexOptTraced(String packageName,
7801                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7803        try {
7804            return performDexOptInternal(packageName, checkProfiles,
7805                    targetCompilerFilter, force);
7806        } finally {
7807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7808        }
7809    }
7810
7811    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7812    // if the package can now be considered up to date for the given filter.
7813    private int performDexOptInternal(String packageName,
7814                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7815        PackageParser.Package p;
7816        synchronized (mPackages) {
7817            p = mPackages.get(packageName);
7818            if (p == null) {
7819                // Package could not be found. Report failure.
7820                return PackageDexOptimizer.DEX_OPT_FAILED;
7821            }
7822            mPackageUsage.maybeWriteAsync(mPackages);
7823            mCompilerStats.maybeWriteAsync();
7824        }
7825        long callingId = Binder.clearCallingIdentity();
7826        try {
7827            synchronized (mInstallLock) {
7828                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7829                        targetCompilerFilter, force);
7830            }
7831        } finally {
7832            Binder.restoreCallingIdentity(callingId);
7833        }
7834    }
7835
7836    public ArraySet<String> getOptimizablePackages() {
7837        ArraySet<String> pkgs = new ArraySet<String>();
7838        synchronized (mPackages) {
7839            for (PackageParser.Package p : mPackages.values()) {
7840                if (PackageDexOptimizer.canOptimizePackage(p)) {
7841                    pkgs.add(p.packageName);
7842                }
7843            }
7844        }
7845        return pkgs;
7846    }
7847
7848    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7849            boolean checkProfiles, String targetCompilerFilter,
7850            boolean force) {
7851        // Select the dex optimizer based on the force parameter.
7852        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7853        //       allocate an object here.
7854        PackageDexOptimizer pdo = force
7855                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7856                : mPackageDexOptimizer;
7857
7858        // Optimize all dependencies first. Note: we ignore the return value and march on
7859        // on errors.
7860        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7861        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7862        if (!deps.isEmpty()) {
7863            for (PackageParser.Package depPackage : deps) {
7864                // TODO: Analyze and investigate if we (should) profile libraries.
7865                // Currently this will do a full compilation of the library by default.
7866                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7867                        false /* checkProfiles */,
7868                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7869                        getOrCreateCompilerPackageStats(depPackage));
7870            }
7871        }
7872        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7873                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7874    }
7875
7876    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7877        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7878            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7879            Set<String> collectedNames = new HashSet<>();
7880            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7881
7882            retValue.remove(p);
7883
7884            return retValue;
7885        } else {
7886            return Collections.emptyList();
7887        }
7888    }
7889
7890    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7891            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7892        if (!collectedNames.contains(p.packageName)) {
7893            collectedNames.add(p.packageName);
7894            collected.add(p);
7895
7896            if (p.usesLibraries != null) {
7897                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7898            }
7899            if (p.usesOptionalLibraries != null) {
7900                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7901                        collectedNames);
7902            }
7903        }
7904    }
7905
7906    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7907            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7908        for (String libName : libs) {
7909            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7910            if (libPkg != null) {
7911                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7912            }
7913        }
7914    }
7915
7916    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7917        synchronized (mPackages) {
7918            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7919            if (lib != null && lib.apk != null) {
7920                return mPackages.get(lib.apk);
7921            }
7922        }
7923        return null;
7924    }
7925
7926    public void shutdown() {
7927        mPackageUsage.writeNow(mPackages);
7928        mCompilerStats.writeNow();
7929    }
7930
7931    @Override
7932    public void dumpProfiles(String packageName) {
7933        PackageParser.Package pkg;
7934        synchronized (mPackages) {
7935            pkg = mPackages.get(packageName);
7936            if (pkg == null) {
7937                throw new IllegalArgumentException("Unknown package: " + packageName);
7938            }
7939        }
7940        /* Only the shell, root, or the app user should be able to dump profiles. */
7941        int callingUid = Binder.getCallingUid();
7942        if (callingUid != Process.SHELL_UID &&
7943            callingUid != Process.ROOT_UID &&
7944            callingUid != pkg.applicationInfo.uid) {
7945            throw new SecurityException("dumpProfiles");
7946        }
7947
7948        synchronized (mInstallLock) {
7949            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7950            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7951            try {
7952                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7953                String codePaths = TextUtils.join(";", allCodePaths);
7954                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7955            } catch (InstallerException e) {
7956                Slog.w(TAG, "Failed to dump profiles", e);
7957            }
7958            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7959        }
7960    }
7961
7962    @Override
7963    public void forceDexOpt(String packageName) {
7964        enforceSystemOrRoot("forceDexOpt");
7965
7966        PackageParser.Package pkg;
7967        synchronized (mPackages) {
7968            pkg = mPackages.get(packageName);
7969            if (pkg == null) {
7970                throw new IllegalArgumentException("Unknown package: " + packageName);
7971            }
7972        }
7973
7974        synchronized (mInstallLock) {
7975            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7976
7977            // Whoever is calling forceDexOpt wants a fully compiled package.
7978            // Don't use profiles since that may cause compilation to be skipped.
7979            final int res = performDexOptInternalWithDependenciesLI(pkg,
7980                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7981                    true /* force */);
7982
7983            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7984            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7985                throw new IllegalStateException("Failed to dexopt: " + res);
7986            }
7987        }
7988    }
7989
7990    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7991        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7992            Slog.w(TAG, "Unable to update from " + oldPkg.name
7993                    + " to " + newPkg.packageName
7994                    + ": old package not in system partition");
7995            return false;
7996        } else if (mPackages.get(oldPkg.name) != null) {
7997            Slog.w(TAG, "Unable to update from " + oldPkg.name
7998                    + " to " + newPkg.packageName
7999                    + ": old package still exists");
8000            return false;
8001        }
8002        return true;
8003    }
8004
8005    void removeCodePathLI(File codePath) {
8006        if (codePath.isDirectory()) {
8007            try {
8008                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8009            } catch (InstallerException e) {
8010                Slog.w(TAG, "Failed to remove code path", e);
8011            }
8012        } else {
8013            codePath.delete();
8014        }
8015    }
8016
8017    private int[] resolveUserIds(int userId) {
8018        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8019    }
8020
8021    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8022        if (pkg == null) {
8023            Slog.wtf(TAG, "Package was null!", new Throwable());
8024            return;
8025        }
8026        clearAppDataLeafLIF(pkg, userId, flags);
8027        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8028        for (int i = 0; i < childCount; i++) {
8029            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8030        }
8031    }
8032
8033    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8034        final PackageSetting ps;
8035        synchronized (mPackages) {
8036            ps = mSettings.mPackages.get(pkg.packageName);
8037        }
8038        for (int realUserId : resolveUserIds(userId)) {
8039            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8040            try {
8041                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8042                        ceDataInode);
8043            } catch (InstallerException e) {
8044                Slog.w(TAG, String.valueOf(e));
8045            }
8046        }
8047    }
8048
8049    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8050        if (pkg == null) {
8051            Slog.wtf(TAG, "Package was null!", new Throwable());
8052            return;
8053        }
8054        destroyAppDataLeafLIF(pkg, userId, flags);
8055        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8056        for (int i = 0; i < childCount; i++) {
8057            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8058        }
8059    }
8060
8061    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8062        final PackageSetting ps;
8063        synchronized (mPackages) {
8064            ps = mSettings.mPackages.get(pkg.packageName);
8065        }
8066        for (int realUserId : resolveUserIds(userId)) {
8067            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8068            try {
8069                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8070                        ceDataInode);
8071            } catch (InstallerException e) {
8072                Slog.w(TAG, String.valueOf(e));
8073            }
8074        }
8075    }
8076
8077    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8078        if (pkg == null) {
8079            Slog.wtf(TAG, "Package was null!", new Throwable());
8080            return;
8081        }
8082        destroyAppProfilesLeafLIF(pkg);
8083        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8084        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8085        for (int i = 0; i < childCount; i++) {
8086            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8087            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8088                    true /* removeBaseMarker */);
8089        }
8090    }
8091
8092    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8093            boolean removeBaseMarker) {
8094        if (pkg.isForwardLocked()) {
8095            return;
8096        }
8097
8098        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8099            try {
8100                path = PackageManagerServiceUtils.realpath(new File(path));
8101            } catch (IOException e) {
8102                // TODO: Should we return early here ?
8103                Slog.w(TAG, "Failed to get canonical path", e);
8104                continue;
8105            }
8106
8107            final String useMarker = path.replace('/', '@');
8108            for (int realUserId : resolveUserIds(userId)) {
8109                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8110                if (removeBaseMarker) {
8111                    File foreignUseMark = new File(profileDir, useMarker);
8112                    if (foreignUseMark.exists()) {
8113                        if (!foreignUseMark.delete()) {
8114                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8115                                    + pkg.packageName);
8116                        }
8117                    }
8118                }
8119
8120                File[] markers = profileDir.listFiles();
8121                if (markers != null) {
8122                    final String searchString = "@" + pkg.packageName + "@";
8123                    // We also delete all markers that contain the package name we're
8124                    // uninstalling. These are associated with secondary dex-files belonging
8125                    // to the package. Reconstructing the path of these dex files is messy
8126                    // in general.
8127                    for (File marker : markers) {
8128                        if (marker.getName().indexOf(searchString) > 0) {
8129                            if (!marker.delete()) {
8130                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8131                                    + pkg.packageName);
8132                            }
8133                        }
8134                    }
8135                }
8136            }
8137        }
8138    }
8139
8140    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8141        try {
8142            mInstaller.destroyAppProfiles(pkg.packageName);
8143        } catch (InstallerException e) {
8144            Slog.w(TAG, String.valueOf(e));
8145        }
8146    }
8147
8148    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8149        if (pkg == null) {
8150            Slog.wtf(TAG, "Package was null!", new Throwable());
8151            return;
8152        }
8153        clearAppProfilesLeafLIF(pkg);
8154        // We don't remove the base foreign use marker when clearing profiles because
8155        // we will rename it when the app is updated. Unlike the actual profile contents,
8156        // the foreign use marker is good across installs.
8157        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8158        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8159        for (int i = 0; i < childCount; i++) {
8160            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8161        }
8162    }
8163
8164    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8165        try {
8166            mInstaller.clearAppProfiles(pkg.packageName);
8167        } catch (InstallerException e) {
8168            Slog.w(TAG, String.valueOf(e));
8169        }
8170    }
8171
8172    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8173            long lastUpdateTime) {
8174        // Set parent install/update time
8175        PackageSetting ps = (PackageSetting) pkg.mExtras;
8176        if (ps != null) {
8177            ps.firstInstallTime = firstInstallTime;
8178            ps.lastUpdateTime = lastUpdateTime;
8179        }
8180        // Set children install/update time
8181        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8182        for (int i = 0; i < childCount; i++) {
8183            PackageParser.Package childPkg = pkg.childPackages.get(i);
8184            ps = (PackageSetting) childPkg.mExtras;
8185            if (ps != null) {
8186                ps.firstInstallTime = firstInstallTime;
8187                ps.lastUpdateTime = lastUpdateTime;
8188            }
8189        }
8190    }
8191
8192    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8193            PackageParser.Package changingLib) {
8194        if (file.path != null) {
8195            usesLibraryFiles.add(file.path);
8196            return;
8197        }
8198        PackageParser.Package p = mPackages.get(file.apk);
8199        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8200            // If we are doing this while in the middle of updating a library apk,
8201            // then we need to make sure to use that new apk for determining the
8202            // dependencies here.  (We haven't yet finished committing the new apk
8203            // to the package manager state.)
8204            if (p == null || p.packageName.equals(changingLib.packageName)) {
8205                p = changingLib;
8206            }
8207        }
8208        if (p != null) {
8209            usesLibraryFiles.addAll(p.getAllCodePaths());
8210        }
8211    }
8212
8213    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8214            PackageParser.Package changingLib) throws PackageManagerException {
8215        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8216            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8217            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8218            for (int i=0; i<N; i++) {
8219                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8220                if (file == null) {
8221                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8222                            "Package " + pkg.packageName + " requires unavailable shared library "
8223                            + pkg.usesLibraries.get(i) + "; failing!");
8224                }
8225                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8226            }
8227            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8228            for (int i=0; i<N; i++) {
8229                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8230                if (file == null) {
8231                    Slog.w(TAG, "Package " + pkg.packageName
8232                            + " desires unavailable shared library "
8233                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8234                } else {
8235                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8236                }
8237            }
8238            N = usesLibraryFiles.size();
8239            if (N > 0) {
8240                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8241            } else {
8242                pkg.usesLibraryFiles = null;
8243            }
8244        }
8245    }
8246
8247    private static boolean hasString(List<String> list, List<String> which) {
8248        if (list == null) {
8249            return false;
8250        }
8251        for (int i=list.size()-1; i>=0; i--) {
8252            for (int j=which.size()-1; j>=0; j--) {
8253                if (which.get(j).equals(list.get(i))) {
8254                    return true;
8255                }
8256            }
8257        }
8258        return false;
8259    }
8260
8261    private void updateAllSharedLibrariesLPw() {
8262        for (PackageParser.Package pkg : mPackages.values()) {
8263            try {
8264                updateSharedLibrariesLPr(pkg, null);
8265            } catch (PackageManagerException e) {
8266                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8267            }
8268        }
8269    }
8270
8271    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8272            PackageParser.Package changingPkg) {
8273        ArrayList<PackageParser.Package> res = null;
8274        for (PackageParser.Package pkg : mPackages.values()) {
8275            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8276                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8277                if (res == null) {
8278                    res = new ArrayList<PackageParser.Package>();
8279                }
8280                res.add(pkg);
8281                try {
8282                    updateSharedLibrariesLPr(pkg, changingPkg);
8283                } catch (PackageManagerException e) {
8284                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8285                }
8286            }
8287        }
8288        return res;
8289    }
8290
8291    /**
8292     * Derive the value of the {@code cpuAbiOverride} based on the provided
8293     * value and an optional stored value from the package settings.
8294     */
8295    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8296        String cpuAbiOverride = null;
8297
8298        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8299            cpuAbiOverride = null;
8300        } else if (abiOverride != null) {
8301            cpuAbiOverride = abiOverride;
8302        } else if (settings != null) {
8303            cpuAbiOverride = settings.cpuAbiOverrideString;
8304        }
8305
8306        return cpuAbiOverride;
8307    }
8308
8309    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8310            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8311                    throws PackageManagerException {
8312        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8313        // If the package has children and this is the first dive in the function
8314        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8315        // whether all packages (parent and children) would be successfully scanned
8316        // before the actual scan since scanning mutates internal state and we want
8317        // to atomically install the package and its children.
8318        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8319            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8320                scanFlags |= SCAN_CHECK_ONLY;
8321            }
8322        } else {
8323            scanFlags &= ~SCAN_CHECK_ONLY;
8324        }
8325
8326        final PackageParser.Package scannedPkg;
8327        try {
8328            // Scan the parent
8329            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8330            // Scan the children
8331            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8332            for (int i = 0; i < childCount; i++) {
8333                PackageParser.Package childPkg = pkg.childPackages.get(i);
8334                scanPackageLI(childPkg, policyFlags,
8335                        scanFlags, currentTime, user);
8336            }
8337        } finally {
8338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8339        }
8340
8341        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8342            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8343        }
8344
8345        return scannedPkg;
8346    }
8347
8348    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8349            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8350        boolean success = false;
8351        try {
8352            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8353                    currentTime, user);
8354            success = true;
8355            return res;
8356        } finally {
8357            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8358                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8359                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8360                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8361                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8362            }
8363        }
8364    }
8365
8366    /**
8367     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8368     */
8369    private static boolean apkHasCode(String fileName) {
8370        StrictJarFile jarFile = null;
8371        try {
8372            jarFile = new StrictJarFile(fileName,
8373                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8374            return jarFile.findEntry("classes.dex") != null;
8375        } catch (IOException ignore) {
8376        } finally {
8377            try {
8378                if (jarFile != null) {
8379                    jarFile.close();
8380                }
8381            } catch (IOException ignore) {}
8382        }
8383        return false;
8384    }
8385
8386    /**
8387     * Enforces code policy for the package. This ensures that if an APK has
8388     * declared hasCode="true" in its manifest that the APK actually contains
8389     * code.
8390     *
8391     * @throws PackageManagerException If bytecode could not be found when it should exist
8392     */
8393    private static void assertCodePolicy(PackageParser.Package pkg)
8394            throws PackageManagerException {
8395        final boolean shouldHaveCode =
8396                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8397        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8398            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8399                    "Package " + pkg.baseCodePath + " code is missing");
8400        }
8401
8402        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8403            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8404                final boolean splitShouldHaveCode =
8405                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8406                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8407                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8408                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8409                }
8410            }
8411        }
8412    }
8413
8414    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8415            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8416                    throws PackageManagerException {
8417        if (DEBUG_PACKAGE_SCANNING) {
8418            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8419                Log.d(TAG, "Scanning package " + pkg.packageName);
8420        }
8421
8422        applyPolicy(pkg, policyFlags);
8423
8424        assertPackageIsValid(pkg, policyFlags, scanFlags);
8425
8426        // Initialize package source and resource directories
8427        final File scanFile = new File(pkg.codePath);
8428        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8429        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8430
8431        SharedUserSetting suid = null;
8432        PackageSetting pkgSetting = null;
8433
8434        // Getting the package setting may have a side-effect, so if we
8435        // are only checking if scan would succeed, stash a copy of the
8436        // old setting to restore at the end.
8437        PackageSetting nonMutatedPs = null;
8438
8439        // We keep references to the derived CPU Abis from settings in oder to reuse
8440        // them in the case where we're not upgrading or booting for the first time.
8441        String primaryCpuAbiFromSettings = null;
8442        String secondaryCpuAbiFromSettings = null;
8443
8444        // writer
8445        synchronized (mPackages) {
8446            if (pkg.mSharedUserId != null) {
8447                // SIDE EFFECTS; may potentially allocate a new shared user
8448                suid = mSettings.getSharedUserLPw(
8449                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8450                if (DEBUG_PACKAGE_SCANNING) {
8451                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8452                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8453                                + "): packages=" + suid.packages);
8454                }
8455            }
8456
8457            // Check if we are renaming from an original package name.
8458            PackageSetting origPackage = null;
8459            String realName = null;
8460            if (pkg.mOriginalPackages != null) {
8461                // This package may need to be renamed to a previously
8462                // installed name.  Let's check on that...
8463                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8464                if (pkg.mOriginalPackages.contains(renamed)) {
8465                    // This package had originally been installed as the
8466                    // original name, and we have already taken care of
8467                    // transitioning to the new one.  Just update the new
8468                    // one to continue using the old name.
8469                    realName = pkg.mRealPackage;
8470                    if (!pkg.packageName.equals(renamed)) {
8471                        // Callers into this function may have already taken
8472                        // care of renaming the package; only do it here if
8473                        // it is not already done.
8474                        pkg.setPackageName(renamed);
8475                    }
8476                } else {
8477                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8478                        if ((origPackage = mSettings.getPackageLPr(
8479                                pkg.mOriginalPackages.get(i))) != null) {
8480                            // We do have the package already installed under its
8481                            // original name...  should we use it?
8482                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8483                                // New package is not compatible with original.
8484                                origPackage = null;
8485                                continue;
8486                            } else if (origPackage.sharedUser != null) {
8487                                // Make sure uid is compatible between packages.
8488                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8489                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8490                                            + " to " + pkg.packageName + ": old uid "
8491                                            + origPackage.sharedUser.name
8492                                            + " differs from " + pkg.mSharedUserId);
8493                                    origPackage = null;
8494                                    continue;
8495                                }
8496                                // TODO: Add case when shared user id is added [b/28144775]
8497                            } else {
8498                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8499                                        + pkg.packageName + " to old name " + origPackage.name);
8500                            }
8501                            break;
8502                        }
8503                    }
8504                }
8505            }
8506
8507            if (mTransferedPackages.contains(pkg.packageName)) {
8508                Slog.w(TAG, "Package " + pkg.packageName
8509                        + " was transferred to another, but its .apk remains");
8510            }
8511
8512            // See comments in nonMutatedPs declaration
8513            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8514                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8515                if (foundPs != null) {
8516                    nonMutatedPs = new PackageSetting(foundPs);
8517                }
8518            }
8519
8520            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8521                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8522                if (foundPs != null) {
8523                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8524                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8525                }
8526            }
8527
8528            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8529            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8530                PackageManagerService.reportSettingsProblem(Log.WARN,
8531                        "Package " + pkg.packageName + " shared user changed from "
8532                                + (pkgSetting.sharedUser != null
8533                                        ? pkgSetting.sharedUser.name : "<nothing>")
8534                                + " to "
8535                                + (suid != null ? suid.name : "<nothing>")
8536                                + "; replacing with new");
8537                pkgSetting = null;
8538            }
8539            final PackageSetting oldPkgSetting =
8540                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8541            final PackageSetting disabledPkgSetting =
8542                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8543            if (pkgSetting == null) {
8544                final String parentPackageName = (pkg.parentPackage != null)
8545                        ? pkg.parentPackage.packageName : null;
8546                // REMOVE SharedUserSetting from method; update in a separate call
8547                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8548                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8549                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8550                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8551                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8552                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8553                        UserManagerService.getInstance());
8554                // SIDE EFFECTS; updates system state; move elsewhere
8555                if (origPackage != null) {
8556                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8557                }
8558                mSettings.addUserToSettingLPw(pkgSetting);
8559            } else {
8560                // REMOVE SharedUserSetting from method; update in a separate call.
8561                //
8562                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8563                // secondaryCpuAbi are not known at this point so we always update them
8564                // to null here, only to reset them at a later point.
8565                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8566                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8567                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8568                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8569                        UserManagerService.getInstance());
8570            }
8571            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8572            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8573
8574            // SIDE EFFECTS; modifies system state; move elsewhere
8575            if (pkgSetting.origPackage != null) {
8576                // If we are first transitioning from an original package,
8577                // fix up the new package's name now.  We need to do this after
8578                // looking up the package under its new name, so getPackageLP
8579                // can take care of fiddling things correctly.
8580                pkg.setPackageName(origPackage.name);
8581
8582                // File a report about this.
8583                String msg = "New package " + pkgSetting.realName
8584                        + " renamed to replace old package " + pkgSetting.name;
8585                reportSettingsProblem(Log.WARN, msg);
8586
8587                // Make a note of it.
8588                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8589                    mTransferedPackages.add(origPackage.name);
8590                }
8591
8592                // No longer need to retain this.
8593                pkgSetting.origPackage = null;
8594            }
8595
8596            // SIDE EFFECTS; modifies system state; move elsewhere
8597            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8598                // Make a note of it.
8599                mTransferedPackages.add(pkg.packageName);
8600            }
8601
8602            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8603                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8604            }
8605
8606            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8607                // Check all shared libraries and map to their actual file path.
8608                // We only do this here for apps not on a system dir, because those
8609                // are the only ones that can fail an install due to this.  We
8610                // will take care of the system apps by updating all of their
8611                // library paths after the scan is done.
8612                updateSharedLibrariesLPr(pkg, null);
8613            }
8614
8615            if (mFoundPolicyFile) {
8616                SELinuxMMAC.assignSeinfoValue(pkg);
8617            }
8618
8619            pkg.applicationInfo.uid = pkgSetting.appId;
8620            pkg.mExtras = pkgSetting;
8621            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8622                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8623                    // We just determined the app is signed correctly, so bring
8624                    // over the latest parsed certs.
8625                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8626                } else {
8627                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8628                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8629                                "Package " + pkg.packageName + " upgrade keys do not match the "
8630                                + "previously installed version");
8631                    } else {
8632                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8633                        String msg = "System package " + pkg.packageName
8634                                + " signature changed; retaining data.";
8635                        reportSettingsProblem(Log.WARN, msg);
8636                    }
8637                }
8638            } else {
8639                try {
8640                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8641                    verifySignaturesLP(pkgSetting, pkg);
8642                    // We just determined the app is signed correctly, so bring
8643                    // over the latest parsed certs.
8644                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8645                } catch (PackageManagerException e) {
8646                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8647                        throw e;
8648                    }
8649                    // The signature has changed, but this package is in the system
8650                    // image...  let's recover!
8651                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8652                    // However...  if this package is part of a shared user, but it
8653                    // doesn't match the signature of the shared user, let's fail.
8654                    // What this means is that you can't change the signatures
8655                    // associated with an overall shared user, which doesn't seem all
8656                    // that unreasonable.
8657                    if (pkgSetting.sharedUser != null) {
8658                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8659                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8660                            throw new PackageManagerException(
8661                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8662                                    "Signature mismatch for shared user: "
8663                                            + pkgSetting.sharedUser);
8664                        }
8665                    }
8666                    // File a report about this.
8667                    String msg = "System package " + pkg.packageName
8668                            + " signature changed; retaining data.";
8669                    reportSettingsProblem(Log.WARN, msg);
8670                }
8671            }
8672
8673            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8674                // This package wants to adopt ownership of permissions from
8675                // another package.
8676                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8677                    final String origName = pkg.mAdoptPermissions.get(i);
8678                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8679                    if (orig != null) {
8680                        if (verifyPackageUpdateLPr(orig, pkg)) {
8681                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8682                                    + pkg.packageName);
8683                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8684                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8685                        }
8686                    }
8687                }
8688            }
8689        }
8690
8691        pkg.applicationInfo.processName = fixProcessName(
8692                pkg.applicationInfo.packageName,
8693                pkg.applicationInfo.processName);
8694
8695        if (pkg != mPlatformPackage) {
8696            // Get all of our default paths setup
8697            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8698        }
8699
8700        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8701
8702        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8703            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8704                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8705                derivePackageAbi(
8706                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8707                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8708
8709                // Some system apps still use directory structure for native libraries
8710                // in which case we might end up not detecting abi solely based on apk
8711                // structure. Try to detect abi based on directory structure.
8712                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8713                        pkg.applicationInfo.primaryCpuAbi == null) {
8714                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8715                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8716                }
8717            } else {
8718                // This is not a first boot or an upgrade, don't bother deriving the
8719                // ABI during the scan. Instead, trust the value that was stored in the
8720                // package setting.
8721                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8722                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8723
8724                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8725
8726                if (DEBUG_ABI_SELECTION) {
8727                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8728                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8729                        pkg.applicationInfo.secondaryCpuAbi);
8730                }
8731            }
8732        } else {
8733            if ((scanFlags & SCAN_MOVE) != 0) {
8734                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8735                // but we already have this packages package info in the PackageSetting. We just
8736                // use that and derive the native library path based on the new codepath.
8737                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8738                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8739            }
8740
8741            // Set native library paths again. For moves, the path will be updated based on the
8742            // ABIs we've determined above. For non-moves, the path will be updated based on the
8743            // ABIs we determined during compilation, but the path will depend on the final
8744            // package path (after the rename away from the stage path).
8745            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8746        }
8747
8748        // This is a special case for the "system" package, where the ABI is
8749        // dictated by the zygote configuration (and init.rc). We should keep track
8750        // of this ABI so that we can deal with "normal" applications that run under
8751        // the same UID correctly.
8752        if (mPlatformPackage == pkg) {
8753            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8754                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8755        }
8756
8757        // If there's a mismatch between the abi-override in the package setting
8758        // and the abiOverride specified for the install. Warn about this because we
8759        // would've already compiled the app without taking the package setting into
8760        // account.
8761        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8762            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8763                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8764                        " for package " + pkg.packageName);
8765            }
8766        }
8767
8768        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8769        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8770        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8771
8772        // Copy the derived override back to the parsed package, so that we can
8773        // update the package settings accordingly.
8774        pkg.cpuAbiOverride = cpuAbiOverride;
8775
8776        if (DEBUG_ABI_SELECTION) {
8777            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8778                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8779                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8780        }
8781
8782        // Push the derived path down into PackageSettings so we know what to
8783        // clean up at uninstall time.
8784        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8785
8786        if (DEBUG_ABI_SELECTION) {
8787            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8788                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8789                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8790        }
8791
8792        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8793        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8794            // We don't do this here during boot because we can do it all
8795            // at once after scanning all existing packages.
8796            //
8797            // We also do this *before* we perform dexopt on this package, so that
8798            // we can avoid redundant dexopts, and also to make sure we've got the
8799            // code and package path correct.
8800            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8801        }
8802
8803        if (mFactoryTest && pkg.requestedPermissions.contains(
8804                android.Manifest.permission.FACTORY_TEST)) {
8805            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8806        }
8807
8808        if (isSystemApp(pkg)) {
8809            pkgSetting.isOrphaned = true;
8810        }
8811
8812        // Take care of first install / last update times.
8813        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8814        if (currentTime != 0) {
8815            if (pkgSetting.firstInstallTime == 0) {
8816                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8817            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8818                pkgSetting.lastUpdateTime = currentTime;
8819            }
8820        } else if (pkgSetting.firstInstallTime == 0) {
8821            // We need *something*.  Take time time stamp of the file.
8822            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8823        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8824            if (scanFileTime != pkgSetting.timeStamp) {
8825                // A package on the system image has changed; consider this
8826                // to be an update.
8827                pkgSetting.lastUpdateTime = scanFileTime;
8828            }
8829        }
8830        pkgSetting.setTimeStamp(scanFileTime);
8831
8832        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8833            if (nonMutatedPs != null) {
8834                synchronized (mPackages) {
8835                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8836                }
8837            }
8838        } else {
8839            // Modify state for the given package setting
8840            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8841                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8842        }
8843        return pkg;
8844    }
8845
8846    /**
8847     * Applies policy to the parsed package based upon the given policy flags.
8848     * Ensures the package is in a good state.
8849     * <p>
8850     * Implementation detail: This method must NOT have any side effect. It would
8851     * ideally be static, but, it requires locks to read system state.
8852     */
8853    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8854        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8855            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8856            if (pkg.applicationInfo.isDirectBootAware()) {
8857                // we're direct boot aware; set for all components
8858                for (PackageParser.Service s : pkg.services) {
8859                    s.info.encryptionAware = s.info.directBootAware = true;
8860                }
8861                for (PackageParser.Provider p : pkg.providers) {
8862                    p.info.encryptionAware = p.info.directBootAware = true;
8863                }
8864                for (PackageParser.Activity a : pkg.activities) {
8865                    a.info.encryptionAware = a.info.directBootAware = true;
8866                }
8867                for (PackageParser.Activity r : pkg.receivers) {
8868                    r.info.encryptionAware = r.info.directBootAware = true;
8869                }
8870            }
8871        } else {
8872            // Only allow system apps to be flagged as core apps.
8873            pkg.coreApp = false;
8874            // clear flags not applicable to regular apps
8875            pkg.applicationInfo.privateFlags &=
8876                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8877            pkg.applicationInfo.privateFlags &=
8878                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8879        }
8880        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8881
8882        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8883            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8884        }
8885
8886        if (!isSystemApp(pkg)) {
8887            // Only system apps can use these features.
8888            pkg.mOriginalPackages = null;
8889            pkg.mRealPackage = null;
8890            pkg.mAdoptPermissions = null;
8891        }
8892    }
8893
8894    /**
8895     * Asserts the parsed package is valid according to teh given policy. If the
8896     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8897     * <p>
8898     * Implementation detail: This method must NOT have any side effects. It would
8899     * ideally be static, but, it requires locks to read system state.
8900     *
8901     * @throws PackageManagerException If the package fails any of the validation checks
8902     */
8903    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8904            throws PackageManagerException {
8905        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8906            assertCodePolicy(pkg);
8907        }
8908
8909        if (pkg.applicationInfo.getCodePath() == null ||
8910                pkg.applicationInfo.getResourcePath() == null) {
8911            // Bail out. The resource and code paths haven't been set.
8912            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8913                    "Code and resource paths haven't been set correctly");
8914        }
8915
8916        // Make sure we're not adding any bogus keyset info
8917        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8918        ksms.assertScannedPackageValid(pkg);
8919
8920        synchronized (mPackages) {
8921            // The special "android" package can only be defined once
8922            if (pkg.packageName.equals("android")) {
8923                if (mAndroidApplication != null) {
8924                    Slog.w(TAG, "*************************************************");
8925                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8926                    Slog.w(TAG, " codePath=" + pkg.codePath);
8927                    Slog.w(TAG, "*************************************************");
8928                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8929                            "Core android package being redefined.  Skipping.");
8930                }
8931            }
8932
8933            // A package name must be unique; don't allow duplicates
8934            if (mPackages.containsKey(pkg.packageName)
8935                    || mSharedLibraries.containsKey(pkg.packageName)) {
8936                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8937                        "Application package " + pkg.packageName
8938                        + " already installed.  Skipping duplicate.");
8939            }
8940
8941            // Only privileged apps and updated privileged apps can add child packages.
8942            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8943                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8944                    throw new PackageManagerException("Only privileged apps can add child "
8945                            + "packages. Ignoring package " + pkg.packageName);
8946                }
8947                final int childCount = pkg.childPackages.size();
8948                for (int i = 0; i < childCount; i++) {
8949                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8950                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8951                            childPkg.packageName)) {
8952                        throw new PackageManagerException("Can't override child of "
8953                                + "another disabled app. Ignoring package " + pkg.packageName);
8954                    }
8955                }
8956            }
8957
8958            // If we're only installing presumed-existing packages, require that the
8959            // scanned APK is both already known and at the path previously established
8960            // for it.  Previously unknown packages we pick up normally, but if we have an
8961            // a priori expectation about this package's install presence, enforce it.
8962            // With a singular exception for new system packages. When an OTA contains
8963            // a new system package, we allow the codepath to change from a system location
8964            // to the user-installed location. If we don't allow this change, any newer,
8965            // user-installed version of the application will be ignored.
8966            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8967                if (mExpectingBetter.containsKey(pkg.packageName)) {
8968                    logCriticalInfo(Log.WARN,
8969                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8970                } else {
8971                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8972                    if (known != null) {
8973                        if (DEBUG_PACKAGE_SCANNING) {
8974                            Log.d(TAG, "Examining " + pkg.codePath
8975                                    + " and requiring known paths " + known.codePathString
8976                                    + " & " + known.resourcePathString);
8977                        }
8978                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8979                                || !pkg.applicationInfo.getResourcePath().equals(
8980                                        known.resourcePathString)) {
8981                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8982                                    "Application package " + pkg.packageName
8983                                    + " found at " + pkg.applicationInfo.getCodePath()
8984                                    + " but expected at " + known.codePathString
8985                                    + "; ignoring.");
8986                        }
8987                    }
8988                }
8989            }
8990
8991            // Verify that this new package doesn't have any content providers
8992            // that conflict with existing packages.  Only do this if the
8993            // package isn't already installed, since we don't want to break
8994            // things that are installed.
8995            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8996                final int N = pkg.providers.size();
8997                int i;
8998                for (i=0; i<N; i++) {
8999                    PackageParser.Provider p = pkg.providers.get(i);
9000                    if (p.info.authority != null) {
9001                        String names[] = p.info.authority.split(";");
9002                        for (int j = 0; j < names.length; j++) {
9003                            if (mProvidersByAuthority.containsKey(names[j])) {
9004                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9005                                final String otherPackageName =
9006                                        ((other != null && other.getComponentName() != null) ?
9007                                                other.getComponentName().getPackageName() : "?");
9008                                throw new PackageManagerException(
9009                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9010                                        "Can't install because provider name " + names[j]
9011                                                + " (in package " + pkg.applicationInfo.packageName
9012                                                + ") is already used by " + otherPackageName);
9013                            }
9014                        }
9015                    }
9016                }
9017            }
9018        }
9019    }
9020
9021    /**
9022     * Adds a scanned package to the system. When this method is finished, the package will
9023     * be available for query, resolution, etc...
9024     */
9025    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9026            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9027        final String pkgName = pkg.packageName;
9028        if (mCustomResolverComponentName != null &&
9029                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9030            setUpCustomResolverActivity(pkg);
9031        }
9032
9033        if (pkg.packageName.equals("android")) {
9034            synchronized (mPackages) {
9035                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9036                    // Set up information for our fall-back user intent resolution activity.
9037                    mPlatformPackage = pkg;
9038                    pkg.mVersionCode = mSdkVersion;
9039                    mAndroidApplication = pkg.applicationInfo;
9040
9041                    if (!mResolverReplaced) {
9042                        mResolveActivity.applicationInfo = mAndroidApplication;
9043                        mResolveActivity.name = ResolverActivity.class.getName();
9044                        mResolveActivity.packageName = mAndroidApplication.packageName;
9045                        mResolveActivity.processName = "system:ui";
9046                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9047                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9048                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9049                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9050                        mResolveActivity.exported = true;
9051                        mResolveActivity.enabled = true;
9052                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9053                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9054                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9055                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9056                                | ActivityInfo.CONFIG_ORIENTATION
9057                                | ActivityInfo.CONFIG_KEYBOARD
9058                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9059                        mResolveInfo.activityInfo = mResolveActivity;
9060                        mResolveInfo.priority = 0;
9061                        mResolveInfo.preferredOrder = 0;
9062                        mResolveInfo.match = 0;
9063                        mResolveComponentName = new ComponentName(
9064                                mAndroidApplication.packageName, mResolveActivity.name);
9065                    }
9066                }
9067            }
9068        }
9069
9070        ArrayList<PackageParser.Package> clientLibPkgs = null;
9071        // writer
9072        synchronized (mPackages) {
9073            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9074                // Only system apps can add new shared libraries.
9075                if (pkg.libraryNames != null) {
9076                    for (int i=0; i<pkg.libraryNames.size(); i++) {
9077                        String name = pkg.libraryNames.get(i);
9078                        boolean allowed = false;
9079                        if (pkg.isUpdatedSystemApp()) {
9080                            // New library entries can only be added through the
9081                            // system image.  This is important to get rid of a lot
9082                            // of nasty edge cases: for example if we allowed a non-
9083                            // system update of the app to add a library, then uninstalling
9084                            // the update would make the library go away, and assumptions
9085                            // we made such as through app install filtering would now
9086                            // have allowed apps on the device which aren't compatible
9087                            // with it.  Better to just have the restriction here, be
9088                            // conservative, and create many fewer cases that can negatively
9089                            // impact the user experience.
9090                            final PackageSetting sysPs = mSettings
9091                                    .getDisabledSystemPkgLPr(pkg.packageName);
9092                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9093                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
9094                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9095                                        allowed = true;
9096                                        break;
9097                                    }
9098                                }
9099                            }
9100                        } else {
9101                            allowed = true;
9102                        }
9103                        if (allowed) {
9104                            if (!mSharedLibraries.containsKey(name)) {
9105                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
9106                            } else if (!name.equals(pkg.packageName)) {
9107                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9108                                        + name + " already exists; skipping");
9109                            }
9110                        } else {
9111                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9112                                    + name + " that is not declared on system image; skipping");
9113                        }
9114                    }
9115                    if ((scanFlags & SCAN_BOOTING) == 0) {
9116                        // If we are not booting, we need to update any applications
9117                        // that are clients of our shared library.  If we are booting,
9118                        // this will all be done once the scan is complete.
9119                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9120                    }
9121                }
9122            }
9123        }
9124
9125        if ((scanFlags & SCAN_BOOTING) != 0) {
9126            // No apps can run during boot scan, so they don't need to be frozen
9127        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9128            // Caller asked to not kill app, so it's probably not frozen
9129        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9130            // Caller asked us to ignore frozen check for some reason; they
9131            // probably didn't know the package name
9132        } else {
9133            // We're doing major surgery on this package, so it better be frozen
9134            // right now to keep it from launching
9135            checkPackageFrozen(pkgName);
9136        }
9137
9138        // Also need to kill any apps that are dependent on the library.
9139        if (clientLibPkgs != null) {
9140            for (int i=0; i<clientLibPkgs.size(); i++) {
9141                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9142                killApplication(clientPkg.applicationInfo.packageName,
9143                        clientPkg.applicationInfo.uid, "update lib");
9144            }
9145        }
9146
9147        // writer
9148        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9149
9150        boolean createIdmapFailed = false;
9151        synchronized (mPackages) {
9152            // We don't expect installation to fail beyond this point
9153
9154            if (pkgSetting.pkg != null) {
9155                // Note that |user| might be null during the initial boot scan. If a codePath
9156                // for an app has changed during a boot scan, it's due to an app update that's
9157                // part of the system partition and marker changes must be applied to all users.
9158                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9159                final int[] userIds = resolveUserIds(userId);
9160                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9161            }
9162
9163            // Add the new setting to mSettings
9164            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9165            // Add the new setting to mPackages
9166            mPackages.put(pkg.applicationInfo.packageName, pkg);
9167            // Make sure we don't accidentally delete its data.
9168            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9169            while (iter.hasNext()) {
9170                PackageCleanItem item = iter.next();
9171                if (pkgName.equals(item.packageName)) {
9172                    iter.remove();
9173                }
9174            }
9175
9176            // Add the package's KeySets to the global KeySetManagerService
9177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9178            ksms.addScannedPackageLPw(pkg);
9179
9180            int N = pkg.providers.size();
9181            StringBuilder r = null;
9182            int i;
9183            for (i=0; i<N; i++) {
9184                PackageParser.Provider p = pkg.providers.get(i);
9185                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9186                        p.info.processName);
9187                mProviders.addProvider(p);
9188                p.syncable = p.info.isSyncable;
9189                if (p.info.authority != null) {
9190                    String names[] = p.info.authority.split(";");
9191                    p.info.authority = null;
9192                    for (int j = 0; j < names.length; j++) {
9193                        if (j == 1 && p.syncable) {
9194                            // We only want the first authority for a provider to possibly be
9195                            // syncable, so if we already added this provider using a different
9196                            // authority clear the syncable flag. We copy the provider before
9197                            // changing it because the mProviders object contains a reference
9198                            // to a provider that we don't want to change.
9199                            // Only do this for the second authority since the resulting provider
9200                            // object can be the same for all future authorities for this provider.
9201                            p = new PackageParser.Provider(p);
9202                            p.syncable = false;
9203                        }
9204                        if (!mProvidersByAuthority.containsKey(names[j])) {
9205                            mProvidersByAuthority.put(names[j], p);
9206                            if (p.info.authority == null) {
9207                                p.info.authority = names[j];
9208                            } else {
9209                                p.info.authority = p.info.authority + ";" + names[j];
9210                            }
9211                            if (DEBUG_PACKAGE_SCANNING) {
9212                                if (chatty)
9213                                    Log.d(TAG, "Registered content provider: " + names[j]
9214                                            + ", className = " + p.info.name + ", isSyncable = "
9215                                            + p.info.isSyncable);
9216                            }
9217                        } else {
9218                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9219                            Slog.w(TAG, "Skipping provider name " + names[j] +
9220                                    " (in package " + pkg.applicationInfo.packageName +
9221                                    "): name already used by "
9222                                    + ((other != null && other.getComponentName() != null)
9223                                            ? other.getComponentName().getPackageName() : "?"));
9224                        }
9225                    }
9226                }
9227                if (chatty) {
9228                    if (r == null) {
9229                        r = new StringBuilder(256);
9230                    } else {
9231                        r.append(' ');
9232                    }
9233                    r.append(p.info.name);
9234                }
9235            }
9236            if (r != null) {
9237                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9238            }
9239
9240            N = pkg.services.size();
9241            r = null;
9242            for (i=0; i<N; i++) {
9243                PackageParser.Service s = pkg.services.get(i);
9244                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9245                        s.info.processName);
9246                mServices.addService(s);
9247                if (chatty) {
9248                    if (r == null) {
9249                        r = new StringBuilder(256);
9250                    } else {
9251                        r.append(' ');
9252                    }
9253                    r.append(s.info.name);
9254                }
9255            }
9256            if (r != null) {
9257                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9258            }
9259
9260            N = pkg.receivers.size();
9261            r = null;
9262            for (i=0; i<N; i++) {
9263                PackageParser.Activity a = pkg.receivers.get(i);
9264                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9265                        a.info.processName);
9266                mReceivers.addActivity(a, "receiver");
9267                if (chatty) {
9268                    if (r == null) {
9269                        r = new StringBuilder(256);
9270                    } else {
9271                        r.append(' ');
9272                    }
9273                    r.append(a.info.name);
9274                }
9275            }
9276            if (r != null) {
9277                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9278            }
9279
9280            N = pkg.activities.size();
9281            r = null;
9282            for (i=0; i<N; i++) {
9283                PackageParser.Activity a = pkg.activities.get(i);
9284                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9285                        a.info.processName);
9286                mActivities.addActivity(a, "activity");
9287                if (chatty) {
9288                    if (r == null) {
9289                        r = new StringBuilder(256);
9290                    } else {
9291                        r.append(' ');
9292                    }
9293                    r.append(a.info.name);
9294                }
9295            }
9296            if (r != null) {
9297                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9298            }
9299
9300            N = pkg.permissionGroups.size();
9301            r = null;
9302            for (i=0; i<N; i++) {
9303                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9304                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9305                final String curPackageName = cur == null ? null : cur.info.packageName;
9306                // Dont allow ephemeral apps to define new permission groups.
9307                if (pkg.applicationInfo.isEphemeralApp()) {
9308                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9309                            + pg.info.packageName
9310                            + " ignored: ephemeral apps cannot define new permission groups.");
9311                    continue;
9312                }
9313                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9314                if (cur == null || isPackageUpdate) {
9315                    mPermissionGroups.put(pg.info.name, pg);
9316                    if (chatty) {
9317                        if (r == null) {
9318                            r = new StringBuilder(256);
9319                        } else {
9320                            r.append(' ');
9321                        }
9322                        if (isPackageUpdate) {
9323                            r.append("UPD:");
9324                        }
9325                        r.append(pg.info.name);
9326                    }
9327                } else {
9328                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9329                            + pg.info.packageName + " ignored: original from "
9330                            + cur.info.packageName);
9331                    if (chatty) {
9332                        if (r == null) {
9333                            r = new StringBuilder(256);
9334                        } else {
9335                            r.append(' ');
9336                        }
9337                        r.append("DUP:");
9338                        r.append(pg.info.name);
9339                    }
9340                }
9341            }
9342            if (r != null) {
9343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9344            }
9345
9346            N = pkg.permissions.size();
9347            r = null;
9348            for (i=0; i<N; i++) {
9349                PackageParser.Permission p = pkg.permissions.get(i);
9350
9351                // Dont allow ephemeral apps to define new permissions.
9352                if (pkg.applicationInfo.isEphemeralApp()) {
9353                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9354                            + p.info.packageName
9355                            + " ignored: ephemeral apps cannot define new permissions.");
9356                    continue;
9357                }
9358
9359                // Assume by default that we did not install this permission into the system.
9360                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9361
9362                // Now that permission groups have a special meaning, we ignore permission
9363                // groups for legacy apps to prevent unexpected behavior. In particular,
9364                // permissions for one app being granted to someone just becase they happen
9365                // to be in a group defined by another app (before this had no implications).
9366                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9367                    p.group = mPermissionGroups.get(p.info.group);
9368                    // Warn for a permission in an unknown group.
9369                    if (p.info.group != null && p.group == null) {
9370                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9371                                + p.info.packageName + " in an unknown group " + p.info.group);
9372                    }
9373                }
9374
9375                ArrayMap<String, BasePermission> permissionMap =
9376                        p.tree ? mSettings.mPermissionTrees
9377                                : mSettings.mPermissions;
9378                BasePermission bp = permissionMap.get(p.info.name);
9379
9380                // Allow system apps to redefine non-system permissions
9381                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9382                    final boolean currentOwnerIsSystem = (bp.perm != null
9383                            && isSystemApp(bp.perm.owner));
9384                    if (isSystemApp(p.owner)) {
9385                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9386                            // It's a built-in permission and no owner, take ownership now
9387                            bp.packageSetting = pkgSetting;
9388                            bp.perm = p;
9389                            bp.uid = pkg.applicationInfo.uid;
9390                            bp.sourcePackage = p.info.packageName;
9391                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9392                        } else if (!currentOwnerIsSystem) {
9393                            String msg = "New decl " + p.owner + " of permission  "
9394                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9395                            reportSettingsProblem(Log.WARN, msg);
9396                            bp = null;
9397                        }
9398                    }
9399                }
9400
9401                if (bp == null) {
9402                    bp = new BasePermission(p.info.name, p.info.packageName,
9403                            BasePermission.TYPE_NORMAL);
9404                    permissionMap.put(p.info.name, bp);
9405                }
9406
9407                if (bp.perm == null) {
9408                    if (bp.sourcePackage == null
9409                            || bp.sourcePackage.equals(p.info.packageName)) {
9410                        BasePermission tree = findPermissionTreeLP(p.info.name);
9411                        if (tree == null
9412                                || tree.sourcePackage.equals(p.info.packageName)) {
9413                            bp.packageSetting = pkgSetting;
9414                            bp.perm = p;
9415                            bp.uid = pkg.applicationInfo.uid;
9416                            bp.sourcePackage = p.info.packageName;
9417                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9418                            if (chatty) {
9419                                if (r == null) {
9420                                    r = new StringBuilder(256);
9421                                } else {
9422                                    r.append(' ');
9423                                }
9424                                r.append(p.info.name);
9425                            }
9426                        } else {
9427                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9428                                    + p.info.packageName + " ignored: base tree "
9429                                    + tree.name + " is from package "
9430                                    + tree.sourcePackage);
9431                        }
9432                    } else {
9433                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9434                                + p.info.packageName + " ignored: original from "
9435                                + bp.sourcePackage);
9436                    }
9437                } else if (chatty) {
9438                    if (r == null) {
9439                        r = new StringBuilder(256);
9440                    } else {
9441                        r.append(' ');
9442                    }
9443                    r.append("DUP:");
9444                    r.append(p.info.name);
9445                }
9446                if (bp.perm == p) {
9447                    bp.protectionLevel = p.info.protectionLevel;
9448                }
9449            }
9450
9451            if (r != null) {
9452                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9453            }
9454
9455            N = pkg.instrumentation.size();
9456            r = null;
9457            for (i=0; i<N; i++) {
9458                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9459                a.info.packageName = pkg.applicationInfo.packageName;
9460                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9461                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9462                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9463                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9464                a.info.dataDir = pkg.applicationInfo.dataDir;
9465                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9466                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9467                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9468                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9469                mInstrumentation.put(a.getComponentName(), a);
9470                if (chatty) {
9471                    if (r == null) {
9472                        r = new StringBuilder(256);
9473                    } else {
9474                        r.append(' ');
9475                    }
9476                    r.append(a.info.name);
9477                }
9478            }
9479            if (r != null) {
9480                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9481            }
9482
9483            if (pkg.protectedBroadcasts != null) {
9484                N = pkg.protectedBroadcasts.size();
9485                for (i=0; i<N; i++) {
9486                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9487                }
9488            }
9489
9490            // Create idmap files for pairs of (packages, overlay packages).
9491            // Note: "android", ie framework-res.apk, is handled by native layers.
9492            if (pkg.mOverlayTarget != null) {
9493                // This is an overlay package.
9494                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9495                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9496                        mOverlays.put(pkg.mOverlayTarget,
9497                                new ArrayMap<String, PackageParser.Package>());
9498                    }
9499                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9500                    map.put(pkg.packageName, pkg);
9501                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9502                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9503                        createIdmapFailed = true;
9504                    }
9505                }
9506            } else if (mOverlays.containsKey(pkg.packageName) &&
9507                    !pkg.packageName.equals("android")) {
9508                // This is a regular package, with one or more known overlay packages.
9509                createIdmapsForPackageLI(pkg);
9510            }
9511        }
9512
9513        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9514
9515        if (createIdmapFailed) {
9516            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9517                    "scanPackageLI failed to createIdmap");
9518        }
9519    }
9520
9521    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9522            PackageParser.Package update, int[] userIds) {
9523        if (existing.applicationInfo == null || update.applicationInfo == null) {
9524            // This isn't due to an app installation.
9525            return;
9526        }
9527
9528        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9529        final File newCodePath = new File(update.applicationInfo.getCodePath());
9530
9531        // The codePath hasn't changed, so there's nothing for us to do.
9532        if (Objects.equals(oldCodePath, newCodePath)) {
9533            return;
9534        }
9535
9536        File canonicalNewCodePath;
9537        try {
9538            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9539        } catch (IOException e) {
9540            Slog.w(TAG, "Failed to get canonical path.", e);
9541            return;
9542        }
9543
9544        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9545        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9546        // that the last component of the path (i.e, the name) doesn't need canonicalization
9547        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9548        // but may change in the future. Hopefully this function won't exist at that point.
9549        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9550                oldCodePath.getName());
9551
9552        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9553        // with "@".
9554        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9555        if (!oldMarkerPrefix.endsWith("@")) {
9556            oldMarkerPrefix += "@";
9557        }
9558        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9559        if (!newMarkerPrefix.endsWith("@")) {
9560            newMarkerPrefix += "@";
9561        }
9562
9563        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9564        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9565        for (String updatedPath : updatedPaths) {
9566            String updatedPathName = new File(updatedPath).getName();
9567            markerSuffixes.add(updatedPathName.replace('/', '@'));
9568        }
9569
9570        for (int userId : userIds) {
9571            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9572
9573            for (String markerSuffix : markerSuffixes) {
9574                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9575                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9576                if (oldForeignUseMark.exists()) {
9577                    try {
9578                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9579                                newForeignUseMark.getAbsolutePath());
9580                    } catch (ErrnoException e) {
9581                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9582                        oldForeignUseMark.delete();
9583                    }
9584                }
9585            }
9586        }
9587    }
9588
9589    /**
9590     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9591     * is derived purely on the basis of the contents of {@code scanFile} and
9592     * {@code cpuAbiOverride}.
9593     *
9594     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9595     */
9596    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9597                                 String cpuAbiOverride, boolean extractLibs,
9598                                 File appLib32InstallDir)
9599            throws PackageManagerException {
9600        // Give ourselves some initial paths; we'll come back for another
9601        // pass once we've determined ABI below.
9602        setNativeLibraryPaths(pkg, appLib32InstallDir);
9603
9604        // We would never need to extract libs for forward-locked and external packages,
9605        // since the container service will do it for us. We shouldn't attempt to
9606        // extract libs from system app when it was not updated.
9607        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9608                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9609            extractLibs = false;
9610        }
9611
9612        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9613        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9614
9615        NativeLibraryHelper.Handle handle = null;
9616        try {
9617            handle = NativeLibraryHelper.Handle.create(pkg);
9618            // TODO(multiArch): This can be null for apps that didn't go through the
9619            // usual installation process. We can calculate it again, like we
9620            // do during install time.
9621            //
9622            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9623            // unnecessary.
9624            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9625
9626            // Null out the abis so that they can be recalculated.
9627            pkg.applicationInfo.primaryCpuAbi = null;
9628            pkg.applicationInfo.secondaryCpuAbi = null;
9629            if (isMultiArch(pkg.applicationInfo)) {
9630                // Warn if we've set an abiOverride for multi-lib packages..
9631                // By definition, we need to copy both 32 and 64 bit libraries for
9632                // such packages.
9633                if (pkg.cpuAbiOverride != null
9634                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9635                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9636                }
9637
9638                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9639                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9640                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9641                    if (extractLibs) {
9642                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9643                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9644                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9645                                useIsaSpecificSubdirs);
9646                    } else {
9647                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9648                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9649                    }
9650                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9651                }
9652
9653                maybeThrowExceptionForMultiArchCopy(
9654                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9655
9656                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9657                    if (extractLibs) {
9658                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9659                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9660                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9661                                useIsaSpecificSubdirs);
9662                    } else {
9663                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9664                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9665                    }
9666                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9667                }
9668
9669                maybeThrowExceptionForMultiArchCopy(
9670                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9671
9672                if (abi64 >= 0) {
9673                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9674                }
9675
9676                if (abi32 >= 0) {
9677                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9678                    if (abi64 >= 0) {
9679                        if (pkg.use32bitAbi) {
9680                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9681                            pkg.applicationInfo.primaryCpuAbi = abi;
9682                        } else {
9683                            pkg.applicationInfo.secondaryCpuAbi = abi;
9684                        }
9685                    } else {
9686                        pkg.applicationInfo.primaryCpuAbi = abi;
9687                    }
9688                }
9689
9690            } else {
9691                String[] abiList = (cpuAbiOverride != null) ?
9692                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9693
9694                // Enable gross and lame hacks for apps that are built with old
9695                // SDK tools. We must scan their APKs for renderscript bitcode and
9696                // not launch them if it's present. Don't bother checking on devices
9697                // that don't have 64 bit support.
9698                boolean needsRenderScriptOverride = false;
9699                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9700                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9701                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9702                    needsRenderScriptOverride = true;
9703                }
9704
9705                final int copyRet;
9706                if (extractLibs) {
9707                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9708                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9709                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9710                } else {
9711                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9712                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9713                }
9714                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9715
9716                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9717                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9718                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9719                }
9720
9721                if (copyRet >= 0) {
9722                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9723                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9724                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9725                } else if (needsRenderScriptOverride) {
9726                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9727                }
9728            }
9729        } catch (IOException ioe) {
9730            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9731        } finally {
9732            IoUtils.closeQuietly(handle);
9733        }
9734
9735        // Now that we've calculated the ABIs and determined if it's an internal app,
9736        // we will go ahead and populate the nativeLibraryPath.
9737        setNativeLibraryPaths(pkg, appLib32InstallDir);
9738    }
9739
9740    /**
9741     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9742     * i.e, so that all packages can be run inside a single process if required.
9743     *
9744     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9745     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9746     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9747     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9748     * updating a package that belongs to a shared user.
9749     *
9750     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9751     * adds unnecessary complexity.
9752     */
9753    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9754            PackageParser.Package scannedPackage) {
9755        String requiredInstructionSet = null;
9756        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9757            requiredInstructionSet = VMRuntime.getInstructionSet(
9758                     scannedPackage.applicationInfo.primaryCpuAbi);
9759        }
9760
9761        PackageSetting requirer = null;
9762        for (PackageSetting ps : packagesForUser) {
9763            // If packagesForUser contains scannedPackage, we skip it. This will happen
9764            // when scannedPackage is an update of an existing package. Without this check,
9765            // we will never be able to change the ABI of any package belonging to a shared
9766            // user, even if it's compatible with other packages.
9767            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9768                if (ps.primaryCpuAbiString == null) {
9769                    continue;
9770                }
9771
9772                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9773                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9774                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9775                    // this but there's not much we can do.
9776                    String errorMessage = "Instruction set mismatch, "
9777                            + ((requirer == null) ? "[caller]" : requirer)
9778                            + " requires " + requiredInstructionSet + " whereas " + ps
9779                            + " requires " + instructionSet;
9780                    Slog.w(TAG, errorMessage);
9781                }
9782
9783                if (requiredInstructionSet == null) {
9784                    requiredInstructionSet = instructionSet;
9785                    requirer = ps;
9786                }
9787            }
9788        }
9789
9790        if (requiredInstructionSet != null) {
9791            String adjustedAbi;
9792            if (requirer != null) {
9793                // requirer != null implies that either scannedPackage was null or that scannedPackage
9794                // did not require an ABI, in which case we have to adjust scannedPackage to match
9795                // the ABI of the set (which is the same as requirer's ABI)
9796                adjustedAbi = requirer.primaryCpuAbiString;
9797                if (scannedPackage != null) {
9798                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9799                }
9800            } else {
9801                // requirer == null implies that we're updating all ABIs in the set to
9802                // match scannedPackage.
9803                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9804            }
9805
9806            for (PackageSetting ps : packagesForUser) {
9807                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9808                    if (ps.primaryCpuAbiString != null) {
9809                        continue;
9810                    }
9811
9812                    ps.primaryCpuAbiString = adjustedAbi;
9813                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9814                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9815                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9816                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9817                                + " (requirer="
9818                                + (requirer == null ? "null" : requirer.pkg.packageName)
9819                                + ", scannedPackage="
9820                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9821                                + ")");
9822                        try {
9823                            mInstaller.rmdex(ps.codePathString,
9824                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9825                        } catch (InstallerException ignored) {
9826                        }
9827                    }
9828                }
9829            }
9830        }
9831    }
9832
9833    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9834        synchronized (mPackages) {
9835            mResolverReplaced = true;
9836            // Set up information for custom user intent resolution activity.
9837            mResolveActivity.applicationInfo = pkg.applicationInfo;
9838            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9839            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9840            mResolveActivity.processName = pkg.applicationInfo.packageName;
9841            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9842            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9843                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9844            mResolveActivity.theme = 0;
9845            mResolveActivity.exported = true;
9846            mResolveActivity.enabled = true;
9847            mResolveInfo.activityInfo = mResolveActivity;
9848            mResolveInfo.priority = 0;
9849            mResolveInfo.preferredOrder = 0;
9850            mResolveInfo.match = 0;
9851            mResolveComponentName = mCustomResolverComponentName;
9852            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9853                    mResolveComponentName);
9854        }
9855    }
9856
9857    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9858        if (installerComponent == null) {
9859            if (DEBUG_EPHEMERAL) {
9860                Slog.d(TAG, "Clear ephemeral installer activity");
9861            }
9862            mEphemeralInstallerActivity.applicationInfo = null;
9863            return;
9864        }
9865
9866        if (DEBUG_EPHEMERAL) {
9867            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9868        }
9869        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9870        // Set up information for ephemeral installer activity
9871        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9872        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9873        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9874        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9875        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9876        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9877                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9878        mEphemeralInstallerActivity.theme = 0;
9879        mEphemeralInstallerActivity.exported = true;
9880        mEphemeralInstallerActivity.enabled = true;
9881        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9882        mEphemeralInstallerInfo.priority = 0;
9883        mEphemeralInstallerInfo.preferredOrder = 1;
9884        mEphemeralInstallerInfo.isDefault = true;
9885        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9886                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9887    }
9888
9889    private static String calculateBundledApkRoot(final String codePathString) {
9890        final File codePath = new File(codePathString);
9891        final File codeRoot;
9892        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9893            codeRoot = Environment.getRootDirectory();
9894        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9895            codeRoot = Environment.getOemDirectory();
9896        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9897            codeRoot = Environment.getVendorDirectory();
9898        } else {
9899            // Unrecognized code path; take its top real segment as the apk root:
9900            // e.g. /something/app/blah.apk => /something
9901            try {
9902                File f = codePath.getCanonicalFile();
9903                File parent = f.getParentFile();    // non-null because codePath is a file
9904                File tmp;
9905                while ((tmp = parent.getParentFile()) != null) {
9906                    f = parent;
9907                    parent = tmp;
9908                }
9909                codeRoot = f;
9910                Slog.w(TAG, "Unrecognized code path "
9911                        + codePath + " - using " + codeRoot);
9912            } catch (IOException e) {
9913                // Can't canonicalize the code path -- shenanigans?
9914                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9915                return Environment.getRootDirectory().getPath();
9916            }
9917        }
9918        return codeRoot.getPath();
9919    }
9920
9921    /**
9922     * Derive and set the location of native libraries for the given package,
9923     * which varies depending on where and how the package was installed.
9924     */
9925    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9926        final ApplicationInfo info = pkg.applicationInfo;
9927        final String codePath = pkg.codePath;
9928        final File codeFile = new File(codePath);
9929        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9930        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9931
9932        info.nativeLibraryRootDir = null;
9933        info.nativeLibraryRootRequiresIsa = false;
9934        info.nativeLibraryDir = null;
9935        info.secondaryNativeLibraryDir = null;
9936
9937        if (isApkFile(codeFile)) {
9938            // Monolithic install
9939            if (bundledApp) {
9940                // If "/system/lib64/apkname" exists, assume that is the per-package
9941                // native library directory to use; otherwise use "/system/lib/apkname".
9942                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9943                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9944                        getPrimaryInstructionSet(info));
9945
9946                // This is a bundled system app so choose the path based on the ABI.
9947                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9948                // is just the default path.
9949                final String apkName = deriveCodePathName(codePath);
9950                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9951                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9952                        apkName).getAbsolutePath();
9953
9954                if (info.secondaryCpuAbi != null) {
9955                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9956                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9957                            secondaryLibDir, apkName).getAbsolutePath();
9958                }
9959            } else if (asecApp) {
9960                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9961                        .getAbsolutePath();
9962            } else {
9963                final String apkName = deriveCodePathName(codePath);
9964                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9965                        .getAbsolutePath();
9966            }
9967
9968            info.nativeLibraryRootRequiresIsa = false;
9969            info.nativeLibraryDir = info.nativeLibraryRootDir;
9970        } else {
9971            // Cluster install
9972            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9973            info.nativeLibraryRootRequiresIsa = true;
9974
9975            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9976                    getPrimaryInstructionSet(info)).getAbsolutePath();
9977
9978            if (info.secondaryCpuAbi != null) {
9979                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9980                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9981            }
9982        }
9983    }
9984
9985    /**
9986     * Calculate the abis and roots for a bundled app. These can uniquely
9987     * be determined from the contents of the system partition, i.e whether
9988     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9989     * of this information, and instead assume that the system was built
9990     * sensibly.
9991     */
9992    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9993                                           PackageSetting pkgSetting) {
9994        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9995
9996        // If "/system/lib64/apkname" exists, assume that is the per-package
9997        // native library directory to use; otherwise use "/system/lib/apkname".
9998        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9999        setBundledAppAbi(pkg, apkRoot, apkName);
10000        // pkgSetting might be null during rescan following uninstall of updates
10001        // to a bundled app, so accommodate that possibility.  The settings in
10002        // that case will be established later from the parsed package.
10003        //
10004        // If the settings aren't null, sync them up with what we've just derived.
10005        // note that apkRoot isn't stored in the package settings.
10006        if (pkgSetting != null) {
10007            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10008            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10009        }
10010    }
10011
10012    /**
10013     * Deduces the ABI of a bundled app and sets the relevant fields on the
10014     * parsed pkg object.
10015     *
10016     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10017     *        under which system libraries are installed.
10018     * @param apkName the name of the installed package.
10019     */
10020    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10021        final File codeFile = new File(pkg.codePath);
10022
10023        final boolean has64BitLibs;
10024        final boolean has32BitLibs;
10025        if (isApkFile(codeFile)) {
10026            // Monolithic install
10027            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10028            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10029        } else {
10030            // Cluster install
10031            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10032            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10033                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10034                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10035                has64BitLibs = (new File(rootDir, isa)).exists();
10036            } else {
10037                has64BitLibs = false;
10038            }
10039            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10040                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10041                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10042                has32BitLibs = (new File(rootDir, isa)).exists();
10043            } else {
10044                has32BitLibs = false;
10045            }
10046        }
10047
10048        if (has64BitLibs && !has32BitLibs) {
10049            // The package has 64 bit libs, but not 32 bit libs. Its primary
10050            // ABI should be 64 bit. We can safely assume here that the bundled
10051            // native libraries correspond to the most preferred ABI in the list.
10052
10053            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10054            pkg.applicationInfo.secondaryCpuAbi = null;
10055        } else if (has32BitLibs && !has64BitLibs) {
10056            // The package has 32 bit libs but not 64 bit libs. Its primary
10057            // ABI should be 32 bit.
10058
10059            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10060            pkg.applicationInfo.secondaryCpuAbi = null;
10061        } else if (has32BitLibs && has64BitLibs) {
10062            // The application has both 64 and 32 bit bundled libraries. We check
10063            // here that the app declares multiArch support, and warn if it doesn't.
10064            //
10065            // We will be lenient here and record both ABIs. The primary will be the
10066            // ABI that's higher on the list, i.e, a device that's configured to prefer
10067            // 64 bit apps will see a 64 bit primary ABI,
10068
10069            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10070                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10071            }
10072
10073            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10074                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10075                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10076            } else {
10077                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10078                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10079            }
10080        } else {
10081            pkg.applicationInfo.primaryCpuAbi = null;
10082            pkg.applicationInfo.secondaryCpuAbi = null;
10083        }
10084    }
10085
10086    private void killApplication(String pkgName, int appId, String reason) {
10087        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10088    }
10089
10090    private void killApplication(String pkgName, int appId, int userId, String reason) {
10091        // Request the ActivityManager to kill the process(only for existing packages)
10092        // so that we do not end up in a confused state while the user is still using the older
10093        // version of the application while the new one gets installed.
10094        final long token = Binder.clearCallingIdentity();
10095        try {
10096            IActivityManager am = ActivityManager.getService();
10097            if (am != null) {
10098                try {
10099                    am.killApplication(pkgName, appId, userId, reason);
10100                } catch (RemoteException e) {
10101                }
10102            }
10103        } finally {
10104            Binder.restoreCallingIdentity(token);
10105        }
10106    }
10107
10108    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10109        // Remove the parent package setting
10110        PackageSetting ps = (PackageSetting) pkg.mExtras;
10111        if (ps != null) {
10112            removePackageLI(ps, chatty);
10113        }
10114        // Remove the child package setting
10115        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10116        for (int i = 0; i < childCount; i++) {
10117            PackageParser.Package childPkg = pkg.childPackages.get(i);
10118            ps = (PackageSetting) childPkg.mExtras;
10119            if (ps != null) {
10120                removePackageLI(ps, chatty);
10121            }
10122        }
10123    }
10124
10125    void removePackageLI(PackageSetting ps, boolean chatty) {
10126        if (DEBUG_INSTALL) {
10127            if (chatty)
10128                Log.d(TAG, "Removing package " + ps.name);
10129        }
10130
10131        // writer
10132        synchronized (mPackages) {
10133            mPackages.remove(ps.name);
10134            final PackageParser.Package pkg = ps.pkg;
10135            if (pkg != null) {
10136                cleanPackageDataStructuresLILPw(pkg, chatty);
10137            }
10138        }
10139    }
10140
10141    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10142        if (DEBUG_INSTALL) {
10143            if (chatty)
10144                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10145        }
10146
10147        // writer
10148        synchronized (mPackages) {
10149            // Remove the parent package
10150            mPackages.remove(pkg.applicationInfo.packageName);
10151            cleanPackageDataStructuresLILPw(pkg, chatty);
10152
10153            // Remove the child packages
10154            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10155            for (int i = 0; i < childCount; i++) {
10156                PackageParser.Package childPkg = pkg.childPackages.get(i);
10157                mPackages.remove(childPkg.applicationInfo.packageName);
10158                cleanPackageDataStructuresLILPw(childPkg, chatty);
10159            }
10160        }
10161    }
10162
10163    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10164        int N = pkg.providers.size();
10165        StringBuilder r = null;
10166        int i;
10167        for (i=0; i<N; i++) {
10168            PackageParser.Provider p = pkg.providers.get(i);
10169            mProviders.removeProvider(p);
10170            if (p.info.authority == null) {
10171
10172                /* There was another ContentProvider with this authority when
10173                 * this app was installed so this authority is null,
10174                 * Ignore it as we don't have to unregister the provider.
10175                 */
10176                continue;
10177            }
10178            String names[] = p.info.authority.split(";");
10179            for (int j = 0; j < names.length; j++) {
10180                if (mProvidersByAuthority.get(names[j]) == p) {
10181                    mProvidersByAuthority.remove(names[j]);
10182                    if (DEBUG_REMOVE) {
10183                        if (chatty)
10184                            Log.d(TAG, "Unregistered content provider: " + names[j]
10185                                    + ", className = " + p.info.name + ", isSyncable = "
10186                                    + p.info.isSyncable);
10187                    }
10188                }
10189            }
10190            if (DEBUG_REMOVE && chatty) {
10191                if (r == null) {
10192                    r = new StringBuilder(256);
10193                } else {
10194                    r.append(' ');
10195                }
10196                r.append(p.info.name);
10197            }
10198        }
10199        if (r != null) {
10200            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10201        }
10202
10203        N = pkg.services.size();
10204        r = null;
10205        for (i=0; i<N; i++) {
10206            PackageParser.Service s = pkg.services.get(i);
10207            mServices.removeService(s);
10208            if (chatty) {
10209                if (r == null) {
10210                    r = new StringBuilder(256);
10211                } else {
10212                    r.append(' ');
10213                }
10214                r.append(s.info.name);
10215            }
10216        }
10217        if (r != null) {
10218            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10219        }
10220
10221        N = pkg.receivers.size();
10222        r = null;
10223        for (i=0; i<N; i++) {
10224            PackageParser.Activity a = pkg.receivers.get(i);
10225            mReceivers.removeActivity(a, "receiver");
10226            if (DEBUG_REMOVE && chatty) {
10227                if (r == null) {
10228                    r = new StringBuilder(256);
10229                } else {
10230                    r.append(' ');
10231                }
10232                r.append(a.info.name);
10233            }
10234        }
10235        if (r != null) {
10236            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10237        }
10238
10239        N = pkg.activities.size();
10240        r = null;
10241        for (i=0; i<N; i++) {
10242            PackageParser.Activity a = pkg.activities.get(i);
10243            mActivities.removeActivity(a, "activity");
10244            if (DEBUG_REMOVE && chatty) {
10245                if (r == null) {
10246                    r = new StringBuilder(256);
10247                } else {
10248                    r.append(' ');
10249                }
10250                r.append(a.info.name);
10251            }
10252        }
10253        if (r != null) {
10254            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10255        }
10256
10257        N = pkg.permissions.size();
10258        r = null;
10259        for (i=0; i<N; i++) {
10260            PackageParser.Permission p = pkg.permissions.get(i);
10261            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10262            if (bp == null) {
10263                bp = mSettings.mPermissionTrees.get(p.info.name);
10264            }
10265            if (bp != null && bp.perm == p) {
10266                bp.perm = null;
10267                if (DEBUG_REMOVE && chatty) {
10268                    if (r == null) {
10269                        r = new StringBuilder(256);
10270                    } else {
10271                        r.append(' ');
10272                    }
10273                    r.append(p.info.name);
10274                }
10275            }
10276            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10277                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10278                if (appOpPkgs != null) {
10279                    appOpPkgs.remove(pkg.packageName);
10280                }
10281            }
10282        }
10283        if (r != null) {
10284            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10285        }
10286
10287        N = pkg.requestedPermissions.size();
10288        r = null;
10289        for (i=0; i<N; i++) {
10290            String perm = pkg.requestedPermissions.get(i);
10291            BasePermission bp = mSettings.mPermissions.get(perm);
10292            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10293                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10294                if (appOpPkgs != null) {
10295                    appOpPkgs.remove(pkg.packageName);
10296                    if (appOpPkgs.isEmpty()) {
10297                        mAppOpPermissionPackages.remove(perm);
10298                    }
10299                }
10300            }
10301        }
10302        if (r != null) {
10303            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10304        }
10305
10306        N = pkg.instrumentation.size();
10307        r = null;
10308        for (i=0; i<N; i++) {
10309            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10310            mInstrumentation.remove(a.getComponentName());
10311            if (DEBUG_REMOVE && chatty) {
10312                if (r == null) {
10313                    r = new StringBuilder(256);
10314                } else {
10315                    r.append(' ');
10316                }
10317                r.append(a.info.name);
10318            }
10319        }
10320        if (r != null) {
10321            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10322        }
10323
10324        r = null;
10325        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10326            // Only system apps can hold shared libraries.
10327            if (pkg.libraryNames != null) {
10328                for (i=0; i<pkg.libraryNames.size(); i++) {
10329                    String name = pkg.libraryNames.get(i);
10330                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10331                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10332                        mSharedLibraries.remove(name);
10333                        if (DEBUG_REMOVE && chatty) {
10334                            if (r == null) {
10335                                r = new StringBuilder(256);
10336                            } else {
10337                                r.append(' ');
10338                            }
10339                            r.append(name);
10340                        }
10341                    }
10342                }
10343            }
10344        }
10345        if (r != null) {
10346            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10347        }
10348    }
10349
10350    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10351        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10352            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10353                return true;
10354            }
10355        }
10356        return false;
10357    }
10358
10359    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10360    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10361    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10362
10363    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10364        // Update the parent permissions
10365        updatePermissionsLPw(pkg.packageName, pkg, flags);
10366        // Update the child permissions
10367        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10368        for (int i = 0; i < childCount; i++) {
10369            PackageParser.Package childPkg = pkg.childPackages.get(i);
10370            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10371        }
10372    }
10373
10374    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10375            int flags) {
10376        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10377        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10378    }
10379
10380    private void updatePermissionsLPw(String changingPkg,
10381            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10382        // Make sure there are no dangling permission trees.
10383        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10384        while (it.hasNext()) {
10385            final BasePermission bp = it.next();
10386            if (bp.packageSetting == null) {
10387                // We may not yet have parsed the package, so just see if
10388                // we still know about its settings.
10389                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10390            }
10391            if (bp.packageSetting == null) {
10392                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10393                        + " from package " + bp.sourcePackage);
10394                it.remove();
10395            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10396                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10397                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10398                            + " from package " + bp.sourcePackage);
10399                    flags |= UPDATE_PERMISSIONS_ALL;
10400                    it.remove();
10401                }
10402            }
10403        }
10404
10405        // Make sure all dynamic permissions have been assigned to a package,
10406        // and make sure there are no dangling permissions.
10407        it = mSettings.mPermissions.values().iterator();
10408        while (it.hasNext()) {
10409            final BasePermission bp = it.next();
10410            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10411                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10412                        + bp.name + " pkg=" + bp.sourcePackage
10413                        + " info=" + bp.pendingInfo);
10414                if (bp.packageSetting == null && bp.pendingInfo != null) {
10415                    final BasePermission tree = findPermissionTreeLP(bp.name);
10416                    if (tree != null && tree.perm != null) {
10417                        bp.packageSetting = tree.packageSetting;
10418                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10419                                new PermissionInfo(bp.pendingInfo));
10420                        bp.perm.info.packageName = tree.perm.info.packageName;
10421                        bp.perm.info.name = bp.name;
10422                        bp.uid = tree.uid;
10423                    }
10424                }
10425            }
10426            if (bp.packageSetting == null) {
10427                // We may not yet have parsed the package, so just see if
10428                // we still know about its settings.
10429                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10430            }
10431            if (bp.packageSetting == null) {
10432                Slog.w(TAG, "Removing dangling permission: " + bp.name
10433                        + " from package " + bp.sourcePackage);
10434                it.remove();
10435            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10436                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10437                    Slog.i(TAG, "Removing old permission: " + bp.name
10438                            + " from package " + bp.sourcePackage);
10439                    flags |= UPDATE_PERMISSIONS_ALL;
10440                    it.remove();
10441                }
10442            }
10443        }
10444
10445        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10446        // Now update the permissions for all packages, in particular
10447        // replace the granted permissions of the system packages.
10448        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10449            for (PackageParser.Package pkg : mPackages.values()) {
10450                if (pkg != pkgInfo) {
10451                    // Only replace for packages on requested volume
10452                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10453                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10454                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10455                    grantPermissionsLPw(pkg, replace, changingPkg);
10456                }
10457            }
10458        }
10459
10460        if (pkgInfo != null) {
10461            // Only replace for packages on requested volume
10462            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10463            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10464                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10465            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10466        }
10467        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10468    }
10469
10470    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10471            String packageOfInterest) {
10472        // IMPORTANT: There are two types of permissions: install and runtime.
10473        // Install time permissions are granted when the app is installed to
10474        // all device users and users added in the future. Runtime permissions
10475        // are granted at runtime explicitly to specific users. Normal and signature
10476        // protected permissions are install time permissions. Dangerous permissions
10477        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10478        // otherwise they are runtime permissions. This function does not manage
10479        // runtime permissions except for the case an app targeting Lollipop MR1
10480        // being upgraded to target a newer SDK, in which case dangerous permissions
10481        // are transformed from install time to runtime ones.
10482
10483        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10484        if (ps == null) {
10485            return;
10486        }
10487
10488        PermissionsState permissionsState = ps.getPermissionsState();
10489        PermissionsState origPermissions = permissionsState;
10490
10491        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10492
10493        boolean runtimePermissionsRevoked = false;
10494        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10495
10496        boolean changedInstallPermission = false;
10497
10498        if (replace) {
10499            ps.installPermissionsFixed = false;
10500            if (!ps.isSharedUser()) {
10501                origPermissions = new PermissionsState(permissionsState);
10502                permissionsState.reset();
10503            } else {
10504                // We need to know only about runtime permission changes since the
10505                // calling code always writes the install permissions state but
10506                // the runtime ones are written only if changed. The only cases of
10507                // changed runtime permissions here are promotion of an install to
10508                // runtime and revocation of a runtime from a shared user.
10509                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10510                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10511                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10512                    runtimePermissionsRevoked = true;
10513                }
10514            }
10515        }
10516
10517        permissionsState.setGlobalGids(mGlobalGids);
10518
10519        final int N = pkg.requestedPermissions.size();
10520        for (int i=0; i<N; i++) {
10521            final String name = pkg.requestedPermissions.get(i);
10522            final BasePermission bp = mSettings.mPermissions.get(name);
10523
10524            if (DEBUG_INSTALL) {
10525                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10526            }
10527
10528            if (bp == null || bp.packageSetting == null) {
10529                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10530                    Slog.w(TAG, "Unknown permission " + name
10531                            + " in package " + pkg.packageName);
10532                }
10533                continue;
10534            }
10535
10536
10537            // Limit ephemeral apps to ephemeral allowed permissions.
10538            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10539                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10540                        + pkg.packageName);
10541                continue;
10542            }
10543
10544            final String perm = bp.name;
10545            boolean allowedSig = false;
10546            int grant = GRANT_DENIED;
10547
10548            // Keep track of app op permissions.
10549            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10550                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10551                if (pkgs == null) {
10552                    pkgs = new ArraySet<>();
10553                    mAppOpPermissionPackages.put(bp.name, pkgs);
10554                }
10555                pkgs.add(pkg.packageName);
10556            }
10557
10558            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10559            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10560                    >= Build.VERSION_CODES.M;
10561            switch (level) {
10562                case PermissionInfo.PROTECTION_NORMAL: {
10563                    // For all apps normal permissions are install time ones.
10564                    grant = GRANT_INSTALL;
10565                } break;
10566
10567                case PermissionInfo.PROTECTION_DANGEROUS: {
10568                    // If a permission review is required for legacy apps we represent
10569                    // their permissions as always granted runtime ones since we need
10570                    // to keep the review required permission flag per user while an
10571                    // install permission's state is shared across all users.
10572                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10573                        // For legacy apps dangerous permissions are install time ones.
10574                        grant = GRANT_INSTALL;
10575                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10576                        // For legacy apps that became modern, install becomes runtime.
10577                        grant = GRANT_UPGRADE;
10578                    } else if (mPromoteSystemApps
10579                            && isSystemApp(ps)
10580                            && mExistingSystemPackages.contains(ps.name)) {
10581                        // For legacy system apps, install becomes runtime.
10582                        // We cannot check hasInstallPermission() for system apps since those
10583                        // permissions were granted implicitly and not persisted pre-M.
10584                        grant = GRANT_UPGRADE;
10585                    } else {
10586                        // For modern apps keep runtime permissions unchanged.
10587                        grant = GRANT_RUNTIME;
10588                    }
10589                } break;
10590
10591                case PermissionInfo.PROTECTION_SIGNATURE: {
10592                    // For all apps signature permissions are install time ones.
10593                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10594                    if (allowedSig) {
10595                        grant = GRANT_INSTALL;
10596                    }
10597                } break;
10598            }
10599
10600            if (DEBUG_INSTALL) {
10601                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10602            }
10603
10604            if (grant != GRANT_DENIED) {
10605                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10606                    // If this is an existing, non-system package, then
10607                    // we can't add any new permissions to it.
10608                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10609                        // Except...  if this is a permission that was added
10610                        // to the platform (note: need to only do this when
10611                        // updating the platform).
10612                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10613                            grant = GRANT_DENIED;
10614                        }
10615                    }
10616                }
10617
10618                switch (grant) {
10619                    case GRANT_INSTALL: {
10620                        // Revoke this as runtime permission to handle the case of
10621                        // a runtime permission being downgraded to an install one.
10622                        // Also in permission review mode we keep dangerous permissions
10623                        // for legacy apps
10624                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10625                            if (origPermissions.getRuntimePermissionState(
10626                                    bp.name, userId) != null) {
10627                                // Revoke the runtime permission and clear the flags.
10628                                origPermissions.revokeRuntimePermission(bp, userId);
10629                                origPermissions.updatePermissionFlags(bp, userId,
10630                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10631                                // If we revoked a permission permission, we have to write.
10632                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10633                                        changedRuntimePermissionUserIds, userId);
10634                            }
10635                        }
10636                        // Grant an install permission.
10637                        if (permissionsState.grantInstallPermission(bp) !=
10638                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10639                            changedInstallPermission = true;
10640                        }
10641                    } break;
10642
10643                    case GRANT_RUNTIME: {
10644                        // Grant previously granted runtime permissions.
10645                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10646                            PermissionState permissionState = origPermissions
10647                                    .getRuntimePermissionState(bp.name, userId);
10648                            int flags = permissionState != null
10649                                    ? permissionState.getFlags() : 0;
10650                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10651                                // Don't propagate the permission in a permission review mode if
10652                                // the former was revoked, i.e. marked to not propagate on upgrade.
10653                                // Note that in a permission review mode install permissions are
10654                                // represented as constantly granted runtime ones since we need to
10655                                // keep a per user state associated with the permission. Also the
10656                                // revoke on upgrade flag is no longer applicable and is reset.
10657                                final boolean revokeOnUpgrade = (flags & PackageManager
10658                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10659                                if (revokeOnUpgrade) {
10660                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10661                                    // Since we changed the flags, we have to write.
10662                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10663                                            changedRuntimePermissionUserIds, userId);
10664                                }
10665                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10666                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
10667                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
10668                                        // If we cannot put the permission as it was,
10669                                        // we have to write.
10670                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10671                                                changedRuntimePermissionUserIds, userId);
10672                                    }
10673                                }
10674
10675                                // If the app supports runtime permissions no need for a review.
10676                                if (mPermissionReviewRequired
10677                                        && appSupportsRuntimePermissions
10678                                        && (flags & PackageManager
10679                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10680                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10681                                    // Since we changed the flags, we have to write.
10682                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10683                                            changedRuntimePermissionUserIds, userId);
10684                                }
10685                            } else if (mPermissionReviewRequired
10686                                    && !appSupportsRuntimePermissions) {
10687                                // For legacy apps that need a permission review, every new
10688                                // runtime permission is granted but it is pending a review.
10689                                // We also need to review only platform defined runtime
10690                                // permissions as these are the only ones the platform knows
10691                                // how to disable the API to simulate revocation as legacy
10692                                // apps don't expect to run with revoked permissions.
10693                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10694                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10695                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10696                                        // We changed the flags, hence have to write.
10697                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10698                                                changedRuntimePermissionUserIds, userId);
10699                                    }
10700                                }
10701                                if (permissionsState.grantRuntimePermission(bp, userId)
10702                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10703                                    // We changed the permission, hence have to write.
10704                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10705                                            changedRuntimePermissionUserIds, userId);
10706                                }
10707                            }
10708                            // Propagate the permission flags.
10709                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10710                        }
10711                    } break;
10712
10713                    case GRANT_UPGRADE: {
10714                        // Grant runtime permissions for a previously held install permission.
10715                        PermissionState permissionState = origPermissions
10716                                .getInstallPermissionState(bp.name);
10717                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10718
10719                        if (origPermissions.revokeInstallPermission(bp)
10720                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10721                            // We will be transferring the permission flags, so clear them.
10722                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10723                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10724                            changedInstallPermission = true;
10725                        }
10726
10727                        // If the permission is not to be promoted to runtime we ignore it and
10728                        // also its other flags as they are not applicable to install permissions.
10729                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10730                            for (int userId : currentUserIds) {
10731                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10732                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10733                                    // Transfer the permission flags.
10734                                    permissionsState.updatePermissionFlags(bp, userId,
10735                                            flags, flags);
10736                                    // If we granted the permission, we have to write.
10737                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10738                                            changedRuntimePermissionUserIds, userId);
10739                                }
10740                            }
10741                        }
10742                    } break;
10743
10744                    default: {
10745                        if (packageOfInterest == null
10746                                || packageOfInterest.equals(pkg.packageName)) {
10747                            Slog.w(TAG, "Not granting permission " + perm
10748                                    + " to package " + pkg.packageName
10749                                    + " because it was previously installed without");
10750                        }
10751                    } break;
10752                }
10753            } else {
10754                if (permissionsState.revokeInstallPermission(bp) !=
10755                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10756                    // Also drop the permission flags.
10757                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10758                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10759                    changedInstallPermission = true;
10760                    Slog.i(TAG, "Un-granting permission " + perm
10761                            + " from package " + pkg.packageName
10762                            + " (protectionLevel=" + bp.protectionLevel
10763                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10764                            + ")");
10765                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10766                    // Don't print warning for app op permissions, since it is fine for them
10767                    // not to be granted, there is a UI for the user to decide.
10768                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10769                        Slog.w(TAG, "Not granting permission " + perm
10770                                + " to package " + pkg.packageName
10771                                + " (protectionLevel=" + bp.protectionLevel
10772                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10773                                + ")");
10774                    }
10775                }
10776            }
10777        }
10778
10779        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10780                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10781            // This is the first that we have heard about this package, so the
10782            // permissions we have now selected are fixed until explicitly
10783            // changed.
10784            ps.installPermissionsFixed = true;
10785        }
10786
10787        // Persist the runtime permissions state for users with changes. If permissions
10788        // were revoked because no app in the shared user declares them we have to
10789        // write synchronously to avoid losing runtime permissions state.
10790        for (int userId : changedRuntimePermissionUserIds) {
10791            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10792        }
10793    }
10794
10795    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10796        boolean allowed = false;
10797        final int NP = PackageParser.NEW_PERMISSIONS.length;
10798        for (int ip=0; ip<NP; ip++) {
10799            final PackageParser.NewPermissionInfo npi
10800                    = PackageParser.NEW_PERMISSIONS[ip];
10801            if (npi.name.equals(perm)
10802                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10803                allowed = true;
10804                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10805                        + pkg.packageName);
10806                break;
10807            }
10808        }
10809        return allowed;
10810    }
10811
10812    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10813            BasePermission bp, PermissionsState origPermissions) {
10814        boolean privilegedPermission = (bp.protectionLevel
10815                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10816        boolean privappPermissionsDisable =
10817                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10818        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10819        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10820        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10821                && !platformPackage && platformPermission) {
10822            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10823                    .getPrivAppPermissions(pkg.packageName);
10824            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10825            if (!whitelisted) {
10826                Slog.w(TAG, "Privileged permission " + perm + " for package "
10827                        + pkg.packageName + " - not in privapp-permissions whitelist");
10828                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10829                    return false;
10830                }
10831            }
10832        }
10833        boolean allowed = (compareSignatures(
10834                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10835                        == PackageManager.SIGNATURE_MATCH)
10836                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10837                        == PackageManager.SIGNATURE_MATCH);
10838        if (!allowed && privilegedPermission) {
10839            if (isSystemApp(pkg)) {
10840                // For updated system applications, a system permission
10841                // is granted only if it had been defined by the original application.
10842                if (pkg.isUpdatedSystemApp()) {
10843                    final PackageSetting sysPs = mSettings
10844                            .getDisabledSystemPkgLPr(pkg.packageName);
10845                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10846                        // If the original was granted this permission, we take
10847                        // that grant decision as read and propagate it to the
10848                        // update.
10849                        if (sysPs.isPrivileged()) {
10850                            allowed = true;
10851                        }
10852                    } else {
10853                        // The system apk may have been updated with an older
10854                        // version of the one on the data partition, but which
10855                        // granted a new system permission that it didn't have
10856                        // before.  In this case we do want to allow the app to
10857                        // now get the new permission if the ancestral apk is
10858                        // privileged to get it.
10859                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10860                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10861                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10862                                    allowed = true;
10863                                    break;
10864                                }
10865                            }
10866                        }
10867                        // Also if a privileged parent package on the system image or any of
10868                        // its children requested a privileged permission, the updated child
10869                        // packages can also get the permission.
10870                        if (pkg.parentPackage != null) {
10871                            final PackageSetting disabledSysParentPs = mSettings
10872                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10873                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10874                                    && disabledSysParentPs.isPrivileged()) {
10875                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10876                                    allowed = true;
10877                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10878                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10879                                    for (int i = 0; i < count; i++) {
10880                                        PackageParser.Package disabledSysChildPkg =
10881                                                disabledSysParentPs.pkg.childPackages.get(i);
10882                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10883                                                perm)) {
10884                                            allowed = true;
10885                                            break;
10886                                        }
10887                                    }
10888                                }
10889                            }
10890                        }
10891                    }
10892                } else {
10893                    allowed = isPrivilegedApp(pkg);
10894                }
10895            }
10896        }
10897        if (!allowed) {
10898            if (!allowed && (bp.protectionLevel
10899                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10900                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10901                // If this was a previously normal/dangerous permission that got moved
10902                // to a system permission as part of the runtime permission redesign, then
10903                // we still want to blindly grant it to old apps.
10904                allowed = true;
10905            }
10906            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10907                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10908                // If this permission is to be granted to the system installer and
10909                // this app is an installer, then it gets the permission.
10910                allowed = true;
10911            }
10912            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10913                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10914                // If this permission is to be granted to the system verifier and
10915                // this app is a verifier, then it gets the permission.
10916                allowed = true;
10917            }
10918            if (!allowed && (bp.protectionLevel
10919                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10920                    && isSystemApp(pkg)) {
10921                // Any pre-installed system app is allowed to get this permission.
10922                allowed = true;
10923            }
10924            if (!allowed && (bp.protectionLevel
10925                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10926                // For development permissions, a development permission
10927                // is granted only if it was already granted.
10928                allowed = origPermissions.hasInstallPermission(perm);
10929            }
10930            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10931                    && pkg.packageName.equals(mSetupWizardPackage)) {
10932                // If this permission is to be granted to the system setup wizard and
10933                // this app is a setup wizard, then it gets the permission.
10934                allowed = true;
10935            }
10936        }
10937        return allowed;
10938    }
10939
10940    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10941        final int permCount = pkg.requestedPermissions.size();
10942        for (int j = 0; j < permCount; j++) {
10943            String requestedPermission = pkg.requestedPermissions.get(j);
10944            if (permission.equals(requestedPermission)) {
10945                return true;
10946            }
10947        }
10948        return false;
10949    }
10950
10951    final class ActivityIntentResolver
10952            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10954                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10955            if (!sUserManager.exists(userId)) return null;
10956            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10957                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10958                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10959            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10960                    isEphemeral, userId);
10961        }
10962
10963        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10964                int userId) {
10965            if (!sUserManager.exists(userId)) return null;
10966            mFlags = flags;
10967            return super.queryIntent(intent, resolvedType,
10968                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10969                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10970                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10971        }
10972
10973        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10974                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10975            if (!sUserManager.exists(userId)) return null;
10976            if (packageActivities == null) {
10977                return null;
10978            }
10979            mFlags = flags;
10980            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10981            final boolean vislbleToEphemeral =
10982                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10983            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10984            final int N = packageActivities.size();
10985            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10986                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10987
10988            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10989            for (int i = 0; i < N; ++i) {
10990                intentFilters = packageActivities.get(i).intents;
10991                if (intentFilters != null && intentFilters.size() > 0) {
10992                    PackageParser.ActivityIntentInfo[] array =
10993                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10994                    intentFilters.toArray(array);
10995                    listCut.add(array);
10996                }
10997            }
10998            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10999                    vislbleToEphemeral, isEphemeral, listCut, userId);
11000        }
11001
11002        /**
11003         * Finds a privileged activity that matches the specified activity names.
11004         */
11005        private PackageParser.Activity findMatchingActivity(
11006                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11007            for (PackageParser.Activity sysActivity : activityList) {
11008                if (sysActivity.info.name.equals(activityInfo.name)) {
11009                    return sysActivity;
11010                }
11011                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11012                    return sysActivity;
11013                }
11014                if (sysActivity.info.targetActivity != null) {
11015                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11016                        return sysActivity;
11017                    }
11018                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11019                        return sysActivity;
11020                    }
11021                }
11022            }
11023            return null;
11024        }
11025
11026        public class IterGenerator<E> {
11027            public Iterator<E> generate(ActivityIntentInfo info) {
11028                return null;
11029            }
11030        }
11031
11032        public class ActionIterGenerator extends IterGenerator<String> {
11033            @Override
11034            public Iterator<String> generate(ActivityIntentInfo info) {
11035                return info.actionsIterator();
11036            }
11037        }
11038
11039        public class CategoriesIterGenerator extends IterGenerator<String> {
11040            @Override
11041            public Iterator<String> generate(ActivityIntentInfo info) {
11042                return info.categoriesIterator();
11043            }
11044        }
11045
11046        public class SchemesIterGenerator extends IterGenerator<String> {
11047            @Override
11048            public Iterator<String> generate(ActivityIntentInfo info) {
11049                return info.schemesIterator();
11050            }
11051        }
11052
11053        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11054            @Override
11055            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11056                return info.authoritiesIterator();
11057            }
11058        }
11059
11060        /**
11061         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11062         * MODIFIED. Do not pass in a list that should not be changed.
11063         */
11064        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11065                IterGenerator<T> generator, Iterator<T> searchIterator) {
11066            // loop through the set of actions; every one must be found in the intent filter
11067            while (searchIterator.hasNext()) {
11068                // we must have at least one filter in the list to consider a match
11069                if (intentList.size() == 0) {
11070                    break;
11071                }
11072
11073                final T searchAction = searchIterator.next();
11074
11075                // loop through the set of intent filters
11076                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11077                while (intentIter.hasNext()) {
11078                    final ActivityIntentInfo intentInfo = intentIter.next();
11079                    boolean selectionFound = false;
11080
11081                    // loop through the intent filter's selection criteria; at least one
11082                    // of them must match the searched criteria
11083                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11084                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11085                        final T intentSelection = intentSelectionIter.next();
11086                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11087                            selectionFound = true;
11088                            break;
11089                        }
11090                    }
11091
11092                    // the selection criteria wasn't found in this filter's set; this filter
11093                    // is not a potential match
11094                    if (!selectionFound) {
11095                        intentIter.remove();
11096                    }
11097                }
11098            }
11099        }
11100
11101        private boolean isProtectedAction(ActivityIntentInfo filter) {
11102            final Iterator<String> actionsIter = filter.actionsIterator();
11103            while (actionsIter != null && actionsIter.hasNext()) {
11104                final String filterAction = actionsIter.next();
11105                if (PROTECTED_ACTIONS.contains(filterAction)) {
11106                    return true;
11107                }
11108            }
11109            return false;
11110        }
11111
11112        /**
11113         * Adjusts the priority of the given intent filter according to policy.
11114         * <p>
11115         * <ul>
11116         * <li>The priority for non privileged applications is capped to '0'</li>
11117         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11118         * <li>The priority for unbundled updates to privileged applications is capped to the
11119         *      priority defined on the system partition</li>
11120         * </ul>
11121         * <p>
11122         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11123         * allowed to obtain any priority on any action.
11124         */
11125        private void adjustPriority(
11126                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11127            // nothing to do; priority is fine as-is
11128            if (intent.getPriority() <= 0) {
11129                return;
11130            }
11131
11132            final ActivityInfo activityInfo = intent.activity.info;
11133            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11134
11135            final boolean privilegedApp =
11136                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11137            if (!privilegedApp) {
11138                // non-privileged applications can never define a priority >0
11139                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11140                        + " package: " + applicationInfo.packageName
11141                        + " activity: " + intent.activity.className
11142                        + " origPrio: " + intent.getPriority());
11143                intent.setPriority(0);
11144                return;
11145            }
11146
11147            if (systemActivities == null) {
11148                // the system package is not disabled; we're parsing the system partition
11149                if (isProtectedAction(intent)) {
11150                    if (mDeferProtectedFilters) {
11151                        // We can't deal with these just yet. No component should ever obtain a
11152                        // >0 priority for a protected actions, with ONE exception -- the setup
11153                        // wizard. The setup wizard, however, cannot be known until we're able to
11154                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11155                        // until all intent filters have been processed. Chicken, meet egg.
11156                        // Let the filter temporarily have a high priority and rectify the
11157                        // priorities after all system packages have been scanned.
11158                        mProtectedFilters.add(intent);
11159                        if (DEBUG_FILTERS) {
11160                            Slog.i(TAG, "Protected action; save for later;"
11161                                    + " package: " + applicationInfo.packageName
11162                                    + " activity: " + intent.activity.className
11163                                    + " origPrio: " + intent.getPriority());
11164                        }
11165                        return;
11166                    } else {
11167                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11168                            Slog.i(TAG, "No setup wizard;"
11169                                + " All protected intents capped to priority 0");
11170                        }
11171                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11172                            if (DEBUG_FILTERS) {
11173                                Slog.i(TAG, "Found setup wizard;"
11174                                    + " allow priority " + intent.getPriority() + ";"
11175                                    + " package: " + intent.activity.info.packageName
11176                                    + " activity: " + intent.activity.className
11177                                    + " priority: " + intent.getPriority());
11178                            }
11179                            // setup wizard gets whatever it wants
11180                            return;
11181                        }
11182                        Slog.w(TAG, "Protected action; cap priority to 0;"
11183                                + " package: " + intent.activity.info.packageName
11184                                + " activity: " + intent.activity.className
11185                                + " origPrio: " + intent.getPriority());
11186                        intent.setPriority(0);
11187                        return;
11188                    }
11189                }
11190                // privileged apps on the system image get whatever priority they request
11191                return;
11192            }
11193
11194            // privileged app unbundled update ... try to find the same activity
11195            final PackageParser.Activity foundActivity =
11196                    findMatchingActivity(systemActivities, activityInfo);
11197            if (foundActivity == null) {
11198                // this is a new activity; it cannot obtain >0 priority
11199                if (DEBUG_FILTERS) {
11200                    Slog.i(TAG, "New activity; cap priority to 0;"
11201                            + " package: " + applicationInfo.packageName
11202                            + " activity: " + intent.activity.className
11203                            + " origPrio: " + intent.getPriority());
11204                }
11205                intent.setPriority(0);
11206                return;
11207            }
11208
11209            // found activity, now check for filter equivalence
11210
11211            // a shallow copy is enough; we modify the list, not its contents
11212            final List<ActivityIntentInfo> intentListCopy =
11213                    new ArrayList<>(foundActivity.intents);
11214            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11215
11216            // find matching action subsets
11217            final Iterator<String> actionsIterator = intent.actionsIterator();
11218            if (actionsIterator != null) {
11219                getIntentListSubset(
11220                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11221                if (intentListCopy.size() == 0) {
11222                    // no more intents to match; we're not equivalent
11223                    if (DEBUG_FILTERS) {
11224                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11225                                + " package: " + applicationInfo.packageName
11226                                + " activity: " + intent.activity.className
11227                                + " origPrio: " + intent.getPriority());
11228                    }
11229                    intent.setPriority(0);
11230                    return;
11231                }
11232            }
11233
11234            // find matching category subsets
11235            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11236            if (categoriesIterator != null) {
11237                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11238                        categoriesIterator);
11239                if (intentListCopy.size() == 0) {
11240                    // no more intents to match; we're not equivalent
11241                    if (DEBUG_FILTERS) {
11242                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11243                                + " package: " + applicationInfo.packageName
11244                                + " activity: " + intent.activity.className
11245                                + " origPrio: " + intent.getPriority());
11246                    }
11247                    intent.setPriority(0);
11248                    return;
11249                }
11250            }
11251
11252            // find matching schemes subsets
11253            final Iterator<String> schemesIterator = intent.schemesIterator();
11254            if (schemesIterator != null) {
11255                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11256                        schemesIterator);
11257                if (intentListCopy.size() == 0) {
11258                    // no more intents to match; we're not equivalent
11259                    if (DEBUG_FILTERS) {
11260                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11261                                + " package: " + applicationInfo.packageName
11262                                + " activity: " + intent.activity.className
11263                                + " origPrio: " + intent.getPriority());
11264                    }
11265                    intent.setPriority(0);
11266                    return;
11267                }
11268            }
11269
11270            // find matching authorities subsets
11271            final Iterator<IntentFilter.AuthorityEntry>
11272                    authoritiesIterator = intent.authoritiesIterator();
11273            if (authoritiesIterator != null) {
11274                getIntentListSubset(intentListCopy,
11275                        new AuthoritiesIterGenerator(),
11276                        authoritiesIterator);
11277                if (intentListCopy.size() == 0) {
11278                    // no more intents to match; we're not equivalent
11279                    if (DEBUG_FILTERS) {
11280                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11281                                + " package: " + applicationInfo.packageName
11282                                + " activity: " + intent.activity.className
11283                                + " origPrio: " + intent.getPriority());
11284                    }
11285                    intent.setPriority(0);
11286                    return;
11287                }
11288            }
11289
11290            // we found matching filter(s); app gets the max priority of all intents
11291            int cappedPriority = 0;
11292            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11293                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11294            }
11295            if (intent.getPriority() > cappedPriority) {
11296                if (DEBUG_FILTERS) {
11297                    Slog.i(TAG, "Found matching filter(s);"
11298                            + " cap priority to " + cappedPriority + ";"
11299                            + " package: " + applicationInfo.packageName
11300                            + " activity: " + intent.activity.className
11301                            + " origPrio: " + intent.getPriority());
11302                }
11303                intent.setPriority(cappedPriority);
11304                return;
11305            }
11306            // all this for nothing; the requested priority was <= what was on the system
11307        }
11308
11309        public final void addActivity(PackageParser.Activity a, String type) {
11310            mActivities.put(a.getComponentName(), a);
11311            if (DEBUG_SHOW_INFO)
11312                Log.v(
11313                TAG, "  " + type + " " +
11314                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11315            if (DEBUG_SHOW_INFO)
11316                Log.v(TAG, "    Class=" + a.info.name);
11317            final int NI = a.intents.size();
11318            for (int j=0; j<NI; j++) {
11319                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11320                if ("activity".equals(type)) {
11321                    final PackageSetting ps =
11322                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11323                    final List<PackageParser.Activity> systemActivities =
11324                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11325                    adjustPriority(systemActivities, intent);
11326                }
11327                if (DEBUG_SHOW_INFO) {
11328                    Log.v(TAG, "    IntentFilter:");
11329                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11330                }
11331                if (!intent.debugCheck()) {
11332                    Log.w(TAG, "==> For Activity " + a.info.name);
11333                }
11334                addFilter(intent);
11335            }
11336        }
11337
11338        public final void removeActivity(PackageParser.Activity a, String type) {
11339            mActivities.remove(a.getComponentName());
11340            if (DEBUG_SHOW_INFO) {
11341                Log.v(TAG, "  " + type + " "
11342                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11343                                : a.info.name) + ":");
11344                Log.v(TAG, "    Class=" + a.info.name);
11345            }
11346            final int NI = a.intents.size();
11347            for (int j=0; j<NI; j++) {
11348                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11349                if (DEBUG_SHOW_INFO) {
11350                    Log.v(TAG, "    IntentFilter:");
11351                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11352                }
11353                removeFilter(intent);
11354            }
11355        }
11356
11357        @Override
11358        protected boolean allowFilterResult(
11359                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11360            ActivityInfo filterAi = filter.activity.info;
11361            for (int i=dest.size()-1; i>=0; i--) {
11362                ActivityInfo destAi = dest.get(i).activityInfo;
11363                if (destAi.name == filterAi.name
11364                        && destAi.packageName == filterAi.packageName) {
11365                    return false;
11366                }
11367            }
11368            return true;
11369        }
11370
11371        @Override
11372        protected ActivityIntentInfo[] newArray(int size) {
11373            return new ActivityIntentInfo[size];
11374        }
11375
11376        @Override
11377        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11378            if (!sUserManager.exists(userId)) return true;
11379            PackageParser.Package p = filter.activity.owner;
11380            if (p != null) {
11381                PackageSetting ps = (PackageSetting)p.mExtras;
11382                if (ps != null) {
11383                    // System apps are never considered stopped for purposes of
11384                    // filtering, because there may be no way for the user to
11385                    // actually re-launch them.
11386                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11387                            && ps.getStopped(userId);
11388                }
11389            }
11390            return false;
11391        }
11392
11393        @Override
11394        protected boolean isPackageForFilter(String packageName,
11395                PackageParser.ActivityIntentInfo info) {
11396            return packageName.equals(info.activity.owner.packageName);
11397        }
11398
11399        @Override
11400        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11401                int match, int userId) {
11402            if (!sUserManager.exists(userId)) return null;
11403            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11404                return null;
11405            }
11406            final PackageParser.Activity activity = info.activity;
11407            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11408            if (ps == null) {
11409                return null;
11410            }
11411            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11412                    ps.readUserState(userId), userId);
11413            if (ai == null) {
11414                return null;
11415            }
11416            final ResolveInfo res = new ResolveInfo();
11417            res.activityInfo = ai;
11418            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11419                res.filter = info;
11420            }
11421            if (info != null) {
11422                res.handleAllWebDataURI = info.handleAllWebDataURI();
11423            }
11424            res.priority = info.getPriority();
11425            res.preferredOrder = activity.owner.mPreferredOrder;
11426            //System.out.println("Result: " + res.activityInfo.className +
11427            //                   " = " + res.priority);
11428            res.match = match;
11429            res.isDefault = info.hasDefault;
11430            res.labelRes = info.labelRes;
11431            res.nonLocalizedLabel = info.nonLocalizedLabel;
11432            if (userNeedsBadging(userId)) {
11433                res.noResourceId = true;
11434            } else {
11435                res.icon = info.icon;
11436            }
11437            res.iconResourceId = info.icon;
11438            res.system = res.activityInfo.applicationInfo.isSystemApp();
11439            return res;
11440        }
11441
11442        @Override
11443        protected void sortResults(List<ResolveInfo> results) {
11444            Collections.sort(results, mResolvePrioritySorter);
11445        }
11446
11447        @Override
11448        protected void dumpFilter(PrintWriter out, String prefix,
11449                PackageParser.ActivityIntentInfo filter) {
11450            out.print(prefix); out.print(
11451                    Integer.toHexString(System.identityHashCode(filter.activity)));
11452                    out.print(' ');
11453                    filter.activity.printComponentShortName(out);
11454                    out.print(" filter ");
11455                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11456        }
11457
11458        @Override
11459        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11460            return filter.activity;
11461        }
11462
11463        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11464            PackageParser.Activity activity = (PackageParser.Activity)label;
11465            out.print(prefix); out.print(
11466                    Integer.toHexString(System.identityHashCode(activity)));
11467                    out.print(' ');
11468                    activity.printComponentShortName(out);
11469            if (count > 1) {
11470                out.print(" ("); out.print(count); out.print(" filters)");
11471            }
11472            out.println();
11473        }
11474
11475        // Keys are String (activity class name), values are Activity.
11476        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11477                = new ArrayMap<ComponentName, PackageParser.Activity>();
11478        private int mFlags;
11479    }
11480
11481    private final class ServiceIntentResolver
11482            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11483        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11484                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11485            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11486            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11487                    isEphemeral, userId);
11488        }
11489
11490        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11491                int userId) {
11492            if (!sUserManager.exists(userId)) return null;
11493            mFlags = flags;
11494            return super.queryIntent(intent, resolvedType,
11495                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11496                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11497                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11498        }
11499
11500        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11501                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11502            if (!sUserManager.exists(userId)) return null;
11503            if (packageServices == null) {
11504                return null;
11505            }
11506            mFlags = flags;
11507            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11508            final boolean vislbleToEphemeral =
11509                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11510            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11511            final int N = packageServices.size();
11512            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11513                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11514
11515            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11516            for (int i = 0; i < N; ++i) {
11517                intentFilters = packageServices.get(i).intents;
11518                if (intentFilters != null && intentFilters.size() > 0) {
11519                    PackageParser.ServiceIntentInfo[] array =
11520                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11521                    intentFilters.toArray(array);
11522                    listCut.add(array);
11523                }
11524            }
11525            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11526                    vislbleToEphemeral, isEphemeral, listCut, userId);
11527        }
11528
11529        public final void addService(PackageParser.Service s) {
11530            mServices.put(s.getComponentName(), s);
11531            if (DEBUG_SHOW_INFO) {
11532                Log.v(TAG, "  "
11533                        + (s.info.nonLocalizedLabel != null
11534                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11535                Log.v(TAG, "    Class=" + s.info.name);
11536            }
11537            final int NI = s.intents.size();
11538            int j;
11539            for (j=0; j<NI; j++) {
11540                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11541                if (DEBUG_SHOW_INFO) {
11542                    Log.v(TAG, "    IntentFilter:");
11543                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11544                }
11545                if (!intent.debugCheck()) {
11546                    Log.w(TAG, "==> For Service " + s.info.name);
11547                }
11548                addFilter(intent);
11549            }
11550        }
11551
11552        public final void removeService(PackageParser.Service s) {
11553            mServices.remove(s.getComponentName());
11554            if (DEBUG_SHOW_INFO) {
11555                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11556                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11557                Log.v(TAG, "    Class=" + s.info.name);
11558            }
11559            final int NI = s.intents.size();
11560            int j;
11561            for (j=0; j<NI; j++) {
11562                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11563                if (DEBUG_SHOW_INFO) {
11564                    Log.v(TAG, "    IntentFilter:");
11565                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11566                }
11567                removeFilter(intent);
11568            }
11569        }
11570
11571        @Override
11572        protected boolean allowFilterResult(
11573                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11574            ServiceInfo filterSi = filter.service.info;
11575            for (int i=dest.size()-1; i>=0; i--) {
11576                ServiceInfo destAi = dest.get(i).serviceInfo;
11577                if (destAi.name == filterSi.name
11578                        && destAi.packageName == filterSi.packageName) {
11579                    return false;
11580                }
11581            }
11582            return true;
11583        }
11584
11585        @Override
11586        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11587            return new PackageParser.ServiceIntentInfo[size];
11588        }
11589
11590        @Override
11591        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11592            if (!sUserManager.exists(userId)) return true;
11593            PackageParser.Package p = filter.service.owner;
11594            if (p != null) {
11595                PackageSetting ps = (PackageSetting)p.mExtras;
11596                if (ps != null) {
11597                    // System apps are never considered stopped for purposes of
11598                    // filtering, because there may be no way for the user to
11599                    // actually re-launch them.
11600                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11601                            && ps.getStopped(userId);
11602                }
11603            }
11604            return false;
11605        }
11606
11607        @Override
11608        protected boolean isPackageForFilter(String packageName,
11609                PackageParser.ServiceIntentInfo info) {
11610            return packageName.equals(info.service.owner.packageName);
11611        }
11612
11613        @Override
11614        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11615                int match, int userId) {
11616            if (!sUserManager.exists(userId)) return null;
11617            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11618            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11619                return null;
11620            }
11621            final PackageParser.Service service = info.service;
11622            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11623            if (ps == null) {
11624                return null;
11625            }
11626            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11627                    ps.readUserState(userId), userId);
11628            if (si == null) {
11629                return null;
11630            }
11631            final ResolveInfo res = new ResolveInfo();
11632            res.serviceInfo = si;
11633            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11634                res.filter = filter;
11635            }
11636            res.priority = info.getPriority();
11637            res.preferredOrder = service.owner.mPreferredOrder;
11638            res.match = match;
11639            res.isDefault = info.hasDefault;
11640            res.labelRes = info.labelRes;
11641            res.nonLocalizedLabel = info.nonLocalizedLabel;
11642            res.icon = info.icon;
11643            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11644            return res;
11645        }
11646
11647        @Override
11648        protected void sortResults(List<ResolveInfo> results) {
11649            Collections.sort(results, mResolvePrioritySorter);
11650        }
11651
11652        @Override
11653        protected void dumpFilter(PrintWriter out, String prefix,
11654                PackageParser.ServiceIntentInfo filter) {
11655            out.print(prefix); out.print(
11656                    Integer.toHexString(System.identityHashCode(filter.service)));
11657                    out.print(' ');
11658                    filter.service.printComponentShortName(out);
11659                    out.print(" filter ");
11660                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11661        }
11662
11663        @Override
11664        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11665            return filter.service;
11666        }
11667
11668        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11669            PackageParser.Service service = (PackageParser.Service)label;
11670            out.print(prefix); out.print(
11671                    Integer.toHexString(System.identityHashCode(service)));
11672                    out.print(' ');
11673                    service.printComponentShortName(out);
11674            if (count > 1) {
11675                out.print(" ("); out.print(count); out.print(" filters)");
11676            }
11677            out.println();
11678        }
11679
11680//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11681//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11682//            final List<ResolveInfo> retList = Lists.newArrayList();
11683//            while (i.hasNext()) {
11684//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11685//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11686//                    retList.add(resolveInfo);
11687//                }
11688//            }
11689//            return retList;
11690//        }
11691
11692        // Keys are String (activity class name), values are Activity.
11693        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11694                = new ArrayMap<ComponentName, PackageParser.Service>();
11695        private int mFlags;
11696    }
11697
11698    private final class ProviderIntentResolver
11699            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11700        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11701                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11702            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11703            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11704                    isEphemeral, userId);
11705        }
11706
11707        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11708                int userId) {
11709            if (!sUserManager.exists(userId))
11710                return null;
11711            mFlags = flags;
11712            return super.queryIntent(intent, resolvedType,
11713                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11714                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11715                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11716        }
11717
11718        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11719                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11720            if (!sUserManager.exists(userId))
11721                return null;
11722            if (packageProviders == null) {
11723                return null;
11724            }
11725            mFlags = flags;
11726            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11727            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11728            final boolean vislbleToEphemeral =
11729                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11730            final int N = packageProviders.size();
11731            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11732                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11733
11734            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11735            for (int i = 0; i < N; ++i) {
11736                intentFilters = packageProviders.get(i).intents;
11737                if (intentFilters != null && intentFilters.size() > 0) {
11738                    PackageParser.ProviderIntentInfo[] array =
11739                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11740                    intentFilters.toArray(array);
11741                    listCut.add(array);
11742                }
11743            }
11744            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11745                    vislbleToEphemeral, isEphemeral, listCut, userId);
11746        }
11747
11748        public final void addProvider(PackageParser.Provider p) {
11749            if (mProviders.containsKey(p.getComponentName())) {
11750                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11751                return;
11752            }
11753
11754            mProviders.put(p.getComponentName(), p);
11755            if (DEBUG_SHOW_INFO) {
11756                Log.v(TAG, "  "
11757                        + (p.info.nonLocalizedLabel != null
11758                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11759                Log.v(TAG, "    Class=" + p.info.name);
11760            }
11761            final int NI = p.intents.size();
11762            int j;
11763            for (j = 0; j < NI; j++) {
11764                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11765                if (DEBUG_SHOW_INFO) {
11766                    Log.v(TAG, "    IntentFilter:");
11767                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11768                }
11769                if (!intent.debugCheck()) {
11770                    Log.w(TAG, "==> For Provider " + p.info.name);
11771                }
11772                addFilter(intent);
11773            }
11774        }
11775
11776        public final void removeProvider(PackageParser.Provider p) {
11777            mProviders.remove(p.getComponentName());
11778            if (DEBUG_SHOW_INFO) {
11779                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11780                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11781                Log.v(TAG, "    Class=" + p.info.name);
11782            }
11783            final int NI = p.intents.size();
11784            int j;
11785            for (j = 0; j < NI; j++) {
11786                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11787                if (DEBUG_SHOW_INFO) {
11788                    Log.v(TAG, "    IntentFilter:");
11789                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11790                }
11791                removeFilter(intent);
11792            }
11793        }
11794
11795        @Override
11796        protected boolean allowFilterResult(
11797                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11798            ProviderInfo filterPi = filter.provider.info;
11799            for (int i = dest.size() - 1; i >= 0; i--) {
11800                ProviderInfo destPi = dest.get(i).providerInfo;
11801                if (destPi.name == filterPi.name
11802                        && destPi.packageName == filterPi.packageName) {
11803                    return false;
11804                }
11805            }
11806            return true;
11807        }
11808
11809        @Override
11810        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11811            return new PackageParser.ProviderIntentInfo[size];
11812        }
11813
11814        @Override
11815        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11816            if (!sUserManager.exists(userId))
11817                return true;
11818            PackageParser.Package p = filter.provider.owner;
11819            if (p != null) {
11820                PackageSetting ps = (PackageSetting) p.mExtras;
11821                if (ps != null) {
11822                    // System apps are never considered stopped for purposes of
11823                    // filtering, because there may be no way for the user to
11824                    // actually re-launch them.
11825                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11826                            && ps.getStopped(userId);
11827                }
11828            }
11829            return false;
11830        }
11831
11832        @Override
11833        protected boolean isPackageForFilter(String packageName,
11834                PackageParser.ProviderIntentInfo info) {
11835            return packageName.equals(info.provider.owner.packageName);
11836        }
11837
11838        @Override
11839        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11840                int match, int userId) {
11841            if (!sUserManager.exists(userId))
11842                return null;
11843            final PackageParser.ProviderIntentInfo info = filter;
11844            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11845                return null;
11846            }
11847            final PackageParser.Provider provider = info.provider;
11848            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11849            if (ps == null) {
11850                return null;
11851            }
11852            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11853                    ps.readUserState(userId), userId);
11854            if (pi == null) {
11855                return null;
11856            }
11857            final ResolveInfo res = new ResolveInfo();
11858            res.providerInfo = pi;
11859            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11860                res.filter = filter;
11861            }
11862            res.priority = info.getPriority();
11863            res.preferredOrder = provider.owner.mPreferredOrder;
11864            res.match = match;
11865            res.isDefault = info.hasDefault;
11866            res.labelRes = info.labelRes;
11867            res.nonLocalizedLabel = info.nonLocalizedLabel;
11868            res.icon = info.icon;
11869            res.system = res.providerInfo.applicationInfo.isSystemApp();
11870            return res;
11871        }
11872
11873        @Override
11874        protected void sortResults(List<ResolveInfo> results) {
11875            Collections.sort(results, mResolvePrioritySorter);
11876        }
11877
11878        @Override
11879        protected void dumpFilter(PrintWriter out, String prefix,
11880                PackageParser.ProviderIntentInfo filter) {
11881            out.print(prefix);
11882            out.print(
11883                    Integer.toHexString(System.identityHashCode(filter.provider)));
11884            out.print(' ');
11885            filter.provider.printComponentShortName(out);
11886            out.print(" filter ");
11887            out.println(Integer.toHexString(System.identityHashCode(filter)));
11888        }
11889
11890        @Override
11891        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11892            return filter.provider;
11893        }
11894
11895        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11896            PackageParser.Provider provider = (PackageParser.Provider)label;
11897            out.print(prefix); out.print(
11898                    Integer.toHexString(System.identityHashCode(provider)));
11899                    out.print(' ');
11900                    provider.printComponentShortName(out);
11901            if (count > 1) {
11902                out.print(" ("); out.print(count); out.print(" filters)");
11903            }
11904            out.println();
11905        }
11906
11907        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11908                = new ArrayMap<ComponentName, PackageParser.Provider>();
11909        private int mFlags;
11910    }
11911
11912    static final class EphemeralIntentResolver
11913            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11914        /**
11915         * The result that has the highest defined order. Ordering applies on a
11916         * per-package basis. Mapping is from package name to Pair of order and
11917         * EphemeralResolveInfo.
11918         * <p>
11919         * NOTE: This is implemented as a field variable for convenience and efficiency.
11920         * By having a field variable, we're able to track filter ordering as soon as
11921         * a non-zero order is defined. Otherwise, multiple loops across the result set
11922         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11923         * this needs to be contained entirely within {@link #filterResults()}.
11924         */
11925        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11926
11927        @Override
11928        protected EphemeralResponse[] newArray(int size) {
11929            return new EphemeralResponse[size];
11930        }
11931
11932        @Override
11933        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11934            return true;
11935        }
11936
11937        @Override
11938        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11939                int userId) {
11940            if (!sUserManager.exists(userId)) {
11941                return null;
11942            }
11943            final String packageName = responseObj.resolveInfo.getPackageName();
11944            final Integer order = responseObj.getOrder();
11945            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11946                    mOrderResult.get(packageName);
11947            // ordering is enabled and this item's order isn't high enough
11948            if (lastOrderResult != null && lastOrderResult.first >= order) {
11949                return null;
11950            }
11951            final EphemeralResolveInfo res = responseObj.resolveInfo;
11952            if (order > 0) {
11953                // non-zero order, enable ordering
11954                mOrderResult.put(packageName, new Pair<>(order, res));
11955            }
11956            return responseObj;
11957        }
11958
11959        @Override
11960        protected void filterResults(List<EphemeralResponse> results) {
11961            // only do work if ordering is enabled [most of the time it won't be]
11962            if (mOrderResult.size() == 0) {
11963                return;
11964            }
11965            int resultSize = results.size();
11966            for (int i = 0; i < resultSize; i++) {
11967                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11968                final String packageName = info.getPackageName();
11969                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11970                if (savedInfo == null) {
11971                    // package doesn't having ordering
11972                    continue;
11973                }
11974                if (savedInfo.second == info) {
11975                    // circled back to the highest ordered item; remove from order list
11976                    mOrderResult.remove(savedInfo);
11977                    if (mOrderResult.size() == 0) {
11978                        // no more ordered items
11979                        break;
11980                    }
11981                    continue;
11982                }
11983                // item has a worse order, remove it from the result list
11984                results.remove(i);
11985                resultSize--;
11986                i--;
11987            }
11988        }
11989    }
11990
11991    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11992            new Comparator<ResolveInfo>() {
11993        public int compare(ResolveInfo r1, ResolveInfo r2) {
11994            int v1 = r1.priority;
11995            int v2 = r2.priority;
11996            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11997            if (v1 != v2) {
11998                return (v1 > v2) ? -1 : 1;
11999            }
12000            v1 = r1.preferredOrder;
12001            v2 = r2.preferredOrder;
12002            if (v1 != v2) {
12003                return (v1 > v2) ? -1 : 1;
12004            }
12005            if (r1.isDefault != r2.isDefault) {
12006                return r1.isDefault ? -1 : 1;
12007            }
12008            v1 = r1.match;
12009            v2 = r2.match;
12010            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12011            if (v1 != v2) {
12012                return (v1 > v2) ? -1 : 1;
12013            }
12014            if (r1.system != r2.system) {
12015                return r1.system ? -1 : 1;
12016            }
12017            if (r1.activityInfo != null) {
12018                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12019            }
12020            if (r1.serviceInfo != null) {
12021                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12022            }
12023            if (r1.providerInfo != null) {
12024                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12025            }
12026            return 0;
12027        }
12028    };
12029
12030    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12031            new Comparator<ProviderInfo>() {
12032        public int compare(ProviderInfo p1, ProviderInfo p2) {
12033            final int v1 = p1.initOrder;
12034            final int v2 = p2.initOrder;
12035            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12036        }
12037    };
12038
12039    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12040            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12041            final int[] userIds) {
12042        mHandler.post(new Runnable() {
12043            @Override
12044            public void run() {
12045                try {
12046                    final IActivityManager am = ActivityManager.getService();
12047                    if (am == null) return;
12048                    final int[] resolvedUserIds;
12049                    if (userIds == null) {
12050                        resolvedUserIds = am.getRunningUserIds();
12051                    } else {
12052                        resolvedUserIds = userIds;
12053                    }
12054                    for (int id : resolvedUserIds) {
12055                        final Intent intent = new Intent(action,
12056                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12057                        if (extras != null) {
12058                            intent.putExtras(extras);
12059                        }
12060                        if (targetPkg != null) {
12061                            intent.setPackage(targetPkg);
12062                        }
12063                        // Modify the UID when posting to other users
12064                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12065                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12066                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12067                            intent.putExtra(Intent.EXTRA_UID, uid);
12068                        }
12069                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12070                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12071                        if (DEBUG_BROADCASTS) {
12072                            RuntimeException here = new RuntimeException("here");
12073                            here.fillInStackTrace();
12074                            Slog.d(TAG, "Sending to user " + id + ": "
12075                                    + intent.toShortString(false, true, false, false)
12076                                    + " " + intent.getExtras(), here);
12077                        }
12078                        am.broadcastIntent(null, intent, null, finishedReceiver,
12079                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12080                                null, finishedReceiver != null, false, id);
12081                    }
12082                } catch (RemoteException ex) {
12083                }
12084            }
12085        });
12086    }
12087
12088    /**
12089     * Check if the external storage media is available. This is true if there
12090     * is a mounted external storage medium or if the external storage is
12091     * emulated.
12092     */
12093    private boolean isExternalMediaAvailable() {
12094        return mMediaMounted || Environment.isExternalStorageEmulated();
12095    }
12096
12097    @Override
12098    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12099        // writer
12100        synchronized (mPackages) {
12101            if (!isExternalMediaAvailable()) {
12102                // If the external storage is no longer mounted at this point,
12103                // the caller may not have been able to delete all of this
12104                // packages files and can not delete any more.  Bail.
12105                return null;
12106            }
12107            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12108            if (lastPackage != null) {
12109                pkgs.remove(lastPackage);
12110            }
12111            if (pkgs.size() > 0) {
12112                return pkgs.get(0);
12113            }
12114        }
12115        return null;
12116    }
12117
12118    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12119        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12120                userId, andCode ? 1 : 0, packageName);
12121        if (mSystemReady) {
12122            msg.sendToTarget();
12123        } else {
12124            if (mPostSystemReadyMessages == null) {
12125                mPostSystemReadyMessages = new ArrayList<>();
12126            }
12127            mPostSystemReadyMessages.add(msg);
12128        }
12129    }
12130
12131    void startCleaningPackages() {
12132        // reader
12133        if (!isExternalMediaAvailable()) {
12134            return;
12135        }
12136        synchronized (mPackages) {
12137            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12138                return;
12139            }
12140        }
12141        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12142        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12143        IActivityManager am = ActivityManager.getService();
12144        if (am != null) {
12145            try {
12146                am.startService(null, intent, null, mContext.getOpPackageName(),
12147                        UserHandle.USER_SYSTEM);
12148            } catch (RemoteException e) {
12149            }
12150        }
12151    }
12152
12153    @Override
12154    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12155            int installFlags, String installerPackageName, int userId) {
12156        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12157
12158        final int callingUid = Binder.getCallingUid();
12159        enforceCrossUserPermission(callingUid, userId,
12160                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12161
12162        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12163            try {
12164                if (observer != null) {
12165                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12166                }
12167            } catch (RemoteException re) {
12168            }
12169            return;
12170        }
12171
12172        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12173            installFlags |= PackageManager.INSTALL_FROM_ADB;
12174
12175        } else {
12176            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12177            // about installerPackageName.
12178
12179            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12180            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12181        }
12182
12183        UserHandle user;
12184        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12185            user = UserHandle.ALL;
12186        } else {
12187            user = new UserHandle(userId);
12188        }
12189
12190        // Only system components can circumvent runtime permissions when installing.
12191        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12192                && mContext.checkCallingOrSelfPermission(Manifest.permission
12193                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12194            throw new SecurityException("You need the "
12195                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12196                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12197        }
12198
12199        final File originFile = new File(originPath);
12200        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12201
12202        final Message msg = mHandler.obtainMessage(INIT_COPY);
12203        final VerificationInfo verificationInfo = new VerificationInfo(
12204                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12205        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12206                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12207                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12208                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12209        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12210        msg.obj = params;
12211
12212        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12213                System.identityHashCode(msg.obj));
12214        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12215                System.identityHashCode(msg.obj));
12216
12217        mHandler.sendMessage(msg);
12218    }
12219
12220
12221    /**
12222     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12223     * it is acting on behalf on an enterprise or the user).
12224     *
12225     * Note that the ordering of the conditionals in this method is important. The checks we perform
12226     * are as follows, in this order:
12227     *
12228     * 1) If the install is being performed by a system app, we can trust the app to have set the
12229     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12230     *    what it is.
12231     * 2) If the install is being performed by a device or profile owner app, the install reason
12232     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12233     *    set the install reason correctly. If the app targets an older SDK version where install
12234     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12235     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12236     * 3) In all other cases, the install is being performed by a regular app that is neither part
12237     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12238     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12239     *    set to enterprise policy and if so, change it to unknown instead.
12240     */
12241    private int fixUpInstallReason(String installerPackageName, int installerUid,
12242            int installReason) {
12243        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12244                == PERMISSION_GRANTED) {
12245            // If the install is being performed by a system app, we trust that app to have set the
12246            // install reason correctly.
12247            return installReason;
12248        }
12249
12250        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12251            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12252        if (dpm != null) {
12253            ComponentName owner = null;
12254            try {
12255                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12256                if (owner == null) {
12257                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12258                }
12259            } catch (RemoteException e) {
12260            }
12261            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12262                // If the install is being performed by a device or profile owner, the install
12263                // reason should be enterprise policy.
12264                return PackageManager.INSTALL_REASON_POLICY;
12265            }
12266        }
12267
12268        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12269            // If the install is being performed by a regular app (i.e. neither system app nor
12270            // device or profile owner), we have no reason to believe that the app is acting on
12271            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12272            // change it to unknown instead.
12273            return PackageManager.INSTALL_REASON_UNKNOWN;
12274        }
12275
12276        // If the install is being performed by a regular app and the install reason was set to any
12277        // value but enterprise policy, leave the install reason unchanged.
12278        return installReason;
12279    }
12280
12281    void installStage(String packageName, File stagedDir, String stagedCid,
12282            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12283            String installerPackageName, int installerUid, UserHandle user,
12284            Certificate[][] certificates) {
12285        if (DEBUG_EPHEMERAL) {
12286            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12287                Slog.d(TAG, "Ephemeral install of " + packageName);
12288            }
12289        }
12290        final VerificationInfo verificationInfo = new VerificationInfo(
12291                sessionParams.originatingUri, sessionParams.referrerUri,
12292                sessionParams.originatingUid, installerUid);
12293
12294        final OriginInfo origin;
12295        if (stagedDir != null) {
12296            origin = OriginInfo.fromStagedFile(stagedDir);
12297        } else {
12298            origin = OriginInfo.fromStagedContainer(stagedCid);
12299        }
12300
12301        final Message msg = mHandler.obtainMessage(INIT_COPY);
12302        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
12303                sessionParams.installReason);
12304        final InstallParams params = new InstallParams(origin, null, observer,
12305                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12306                verificationInfo, user, sessionParams.abiOverride,
12307                sessionParams.grantedRuntimePermissions, certificates, installReason);
12308        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12309        msg.obj = params;
12310
12311        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12312                System.identityHashCode(msg.obj));
12313        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12314                System.identityHashCode(msg.obj));
12315
12316        mHandler.sendMessage(msg);
12317    }
12318
12319    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12320            int userId) {
12321        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12322        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12323    }
12324
12325    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12326            int appId, int... userIds) {
12327        if (ArrayUtils.isEmpty(userIds)) {
12328            return;
12329        }
12330        Bundle extras = new Bundle(1);
12331        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12332        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12333
12334        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12335                packageName, extras, 0, null, null, userIds);
12336        if (isSystem) {
12337            mHandler.post(() -> {
12338                        for (int userId : userIds) {
12339                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12340                        }
12341                    }
12342            );
12343        }
12344    }
12345
12346    /**
12347     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12348     * automatically without needing an explicit launch.
12349     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12350     */
12351    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12352        // If user is not running, the app didn't miss any broadcast
12353        if (!mUserManagerInternal.isUserRunning(userId)) {
12354            return;
12355        }
12356        final IActivityManager am = ActivityManager.getService();
12357        try {
12358            // Deliver LOCKED_BOOT_COMPLETED first
12359            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12360                    .setPackage(packageName);
12361            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12362            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12363                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12364
12365            // Deliver BOOT_COMPLETED only if user is unlocked
12366            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12367                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12368                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12369                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12370            }
12371        } catch (RemoteException e) {
12372            throw e.rethrowFromSystemServer();
12373        }
12374    }
12375
12376    @Override
12377    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12378            int userId) {
12379        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12380        PackageSetting pkgSetting;
12381        final int uid = Binder.getCallingUid();
12382        enforceCrossUserPermission(uid, userId,
12383                true /* requireFullPermission */, true /* checkShell */,
12384                "setApplicationHiddenSetting for user " + userId);
12385
12386        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12387            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12388            return false;
12389        }
12390
12391        long callingId = Binder.clearCallingIdentity();
12392        try {
12393            boolean sendAdded = false;
12394            boolean sendRemoved = false;
12395            // writer
12396            synchronized (mPackages) {
12397                pkgSetting = mSettings.mPackages.get(packageName);
12398                if (pkgSetting == null) {
12399                    return false;
12400                }
12401                // Do not allow "android" is being disabled
12402                if ("android".equals(packageName)) {
12403                    Slog.w(TAG, "Cannot hide package: android");
12404                    return false;
12405                }
12406                // Only allow protected packages to hide themselves.
12407                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12408                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12409                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12410                    return false;
12411                }
12412
12413                if (pkgSetting.getHidden(userId) != hidden) {
12414                    pkgSetting.setHidden(hidden, userId);
12415                    mSettings.writePackageRestrictionsLPr(userId);
12416                    if (hidden) {
12417                        sendRemoved = true;
12418                    } else {
12419                        sendAdded = true;
12420                    }
12421                }
12422            }
12423            if (sendAdded) {
12424                sendPackageAddedForUser(packageName, pkgSetting, userId);
12425                return true;
12426            }
12427            if (sendRemoved) {
12428                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12429                        "hiding pkg");
12430                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12431                return true;
12432            }
12433        } finally {
12434            Binder.restoreCallingIdentity(callingId);
12435        }
12436        return false;
12437    }
12438
12439    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12440            int userId) {
12441        final PackageRemovedInfo info = new PackageRemovedInfo();
12442        info.removedPackage = packageName;
12443        info.removedUsers = new int[] {userId};
12444        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12445        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12446    }
12447
12448    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12449        if (pkgList.length > 0) {
12450            Bundle extras = new Bundle(1);
12451            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12452
12453            sendPackageBroadcast(
12454                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12455                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12456                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12457                    new int[] {userId});
12458        }
12459    }
12460
12461    /**
12462     * Returns true if application is not found or there was an error. Otherwise it returns
12463     * the hidden state of the package for the given user.
12464     */
12465    @Override
12466    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12467        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12469                true /* requireFullPermission */, false /* checkShell */,
12470                "getApplicationHidden for user " + userId);
12471        PackageSetting pkgSetting;
12472        long callingId = Binder.clearCallingIdentity();
12473        try {
12474            // writer
12475            synchronized (mPackages) {
12476                pkgSetting = mSettings.mPackages.get(packageName);
12477                if (pkgSetting == null) {
12478                    return true;
12479                }
12480                return pkgSetting.getHidden(userId);
12481            }
12482        } finally {
12483            Binder.restoreCallingIdentity(callingId);
12484        }
12485    }
12486
12487    /**
12488     * @hide
12489     */
12490    @Override
12491    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
12492        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12493                null);
12494        PackageSetting pkgSetting;
12495        final int uid = Binder.getCallingUid();
12496        enforceCrossUserPermission(uid, userId,
12497                true /* requireFullPermission */, true /* checkShell */,
12498                "installExistingPackage for user " + userId);
12499        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12500            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12501        }
12502
12503        long callingId = Binder.clearCallingIdentity();
12504        try {
12505            boolean installed = false;
12506
12507            // writer
12508            synchronized (mPackages) {
12509                pkgSetting = mSettings.mPackages.get(packageName);
12510                if (pkgSetting == null) {
12511                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12512                }
12513                if (!pkgSetting.getInstalled(userId)) {
12514                    pkgSetting.setInstalled(true, userId);
12515                    pkgSetting.setHidden(false, userId);
12516                    pkgSetting.setInstallReason(installReason, userId);
12517                    mSettings.writePackageRestrictionsLPr(userId);
12518                    installed = true;
12519                }
12520            }
12521
12522            if (installed) {
12523                if (pkgSetting.pkg != null) {
12524                    synchronized (mInstallLock) {
12525                        // We don't need to freeze for a brand new install
12526                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12527                    }
12528                }
12529                sendPackageAddedForUser(packageName, pkgSetting, userId);
12530            }
12531        } finally {
12532            Binder.restoreCallingIdentity(callingId);
12533        }
12534
12535        return PackageManager.INSTALL_SUCCEEDED;
12536    }
12537
12538    boolean isUserRestricted(int userId, String restrictionKey) {
12539        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12540        if (restrictions.getBoolean(restrictionKey, false)) {
12541            Log.w(TAG, "User is restricted: " + restrictionKey);
12542            return true;
12543        }
12544        return false;
12545    }
12546
12547    @Override
12548    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12549            int userId) {
12550        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12552                true /* requireFullPermission */, true /* checkShell */,
12553                "setPackagesSuspended for user " + userId);
12554
12555        if (ArrayUtils.isEmpty(packageNames)) {
12556            return packageNames;
12557        }
12558
12559        // List of package names for whom the suspended state has changed.
12560        List<String> changedPackages = new ArrayList<>(packageNames.length);
12561        // List of package names for whom the suspended state is not set as requested in this
12562        // method.
12563        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12564        long callingId = Binder.clearCallingIdentity();
12565        try {
12566            for (int i = 0; i < packageNames.length; i++) {
12567                String packageName = packageNames[i];
12568                boolean changed = false;
12569                final int appId;
12570                synchronized (mPackages) {
12571                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12572                    if (pkgSetting == null) {
12573                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12574                                + "\". Skipping suspending/un-suspending.");
12575                        unactionedPackages.add(packageName);
12576                        continue;
12577                    }
12578                    appId = pkgSetting.appId;
12579                    if (pkgSetting.getSuspended(userId) != suspended) {
12580                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12581                            unactionedPackages.add(packageName);
12582                            continue;
12583                        }
12584                        pkgSetting.setSuspended(suspended, userId);
12585                        mSettings.writePackageRestrictionsLPr(userId);
12586                        changed = true;
12587                        changedPackages.add(packageName);
12588                    }
12589                }
12590
12591                if (changed && suspended) {
12592                    killApplication(packageName, UserHandle.getUid(userId, appId),
12593                            "suspending package");
12594                }
12595            }
12596        } finally {
12597            Binder.restoreCallingIdentity(callingId);
12598        }
12599
12600        if (!changedPackages.isEmpty()) {
12601            sendPackagesSuspendedForUser(changedPackages.toArray(
12602                    new String[changedPackages.size()]), userId, suspended);
12603        }
12604
12605        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12606    }
12607
12608    @Override
12609    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12610        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12611                true /* requireFullPermission */, false /* checkShell */,
12612                "isPackageSuspendedForUser for user " + userId);
12613        synchronized (mPackages) {
12614            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12615            if (pkgSetting == null) {
12616                throw new IllegalArgumentException("Unknown target package: " + packageName);
12617            }
12618            return pkgSetting.getSuspended(userId);
12619        }
12620    }
12621
12622    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12623        if (isPackageDeviceAdmin(packageName, userId)) {
12624            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12625                    + "\": has an active device admin");
12626            return false;
12627        }
12628
12629        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12630        if (packageName.equals(activeLauncherPackageName)) {
12631            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12632                    + "\": contains the active launcher");
12633            return false;
12634        }
12635
12636        if (packageName.equals(mRequiredInstallerPackage)) {
12637            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12638                    + "\": required for package installation");
12639            return false;
12640        }
12641
12642        if (packageName.equals(mRequiredUninstallerPackage)) {
12643            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12644                    + "\": required for package uninstallation");
12645            return false;
12646        }
12647
12648        if (packageName.equals(mRequiredVerifierPackage)) {
12649            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12650                    + "\": required for package verification");
12651            return false;
12652        }
12653
12654        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12655            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12656                    + "\": is the default dialer");
12657            return false;
12658        }
12659
12660        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12661            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12662                    + "\": protected package");
12663            return false;
12664        }
12665
12666        return true;
12667    }
12668
12669    private String getActiveLauncherPackageName(int userId) {
12670        Intent intent = new Intent(Intent.ACTION_MAIN);
12671        intent.addCategory(Intent.CATEGORY_HOME);
12672        ResolveInfo resolveInfo = resolveIntent(
12673                intent,
12674                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12675                PackageManager.MATCH_DEFAULT_ONLY,
12676                userId);
12677
12678        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12679    }
12680
12681    private String getDefaultDialerPackageName(int userId) {
12682        synchronized (mPackages) {
12683            return mSettings.getDefaultDialerPackageNameLPw(userId);
12684        }
12685    }
12686
12687    @Override
12688    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12689        mContext.enforceCallingOrSelfPermission(
12690                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12691                "Only package verification agents can verify applications");
12692
12693        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12694        final PackageVerificationResponse response = new PackageVerificationResponse(
12695                verificationCode, Binder.getCallingUid());
12696        msg.arg1 = id;
12697        msg.obj = response;
12698        mHandler.sendMessage(msg);
12699    }
12700
12701    @Override
12702    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12703            long millisecondsToDelay) {
12704        mContext.enforceCallingOrSelfPermission(
12705                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12706                "Only package verification agents can extend verification timeouts");
12707
12708        final PackageVerificationState state = mPendingVerification.get(id);
12709        final PackageVerificationResponse response = new PackageVerificationResponse(
12710                verificationCodeAtTimeout, Binder.getCallingUid());
12711
12712        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12713            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12714        }
12715        if (millisecondsToDelay < 0) {
12716            millisecondsToDelay = 0;
12717        }
12718        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12719                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12720            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12721        }
12722
12723        if ((state != null) && !state.timeoutExtended()) {
12724            state.extendTimeout();
12725
12726            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12727            msg.arg1 = id;
12728            msg.obj = response;
12729            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12730        }
12731    }
12732
12733    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12734            int verificationCode, UserHandle user) {
12735        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12736        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12737        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12738        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12739        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12740
12741        mContext.sendBroadcastAsUser(intent, user,
12742                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12743    }
12744
12745    private ComponentName matchComponentForVerifier(String packageName,
12746            List<ResolveInfo> receivers) {
12747        ActivityInfo targetReceiver = null;
12748
12749        final int NR = receivers.size();
12750        for (int i = 0; i < NR; i++) {
12751            final ResolveInfo info = receivers.get(i);
12752            if (info.activityInfo == null) {
12753                continue;
12754            }
12755
12756            if (packageName.equals(info.activityInfo.packageName)) {
12757                targetReceiver = info.activityInfo;
12758                break;
12759            }
12760        }
12761
12762        if (targetReceiver == null) {
12763            return null;
12764        }
12765
12766        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12767    }
12768
12769    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12770            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12771        if (pkgInfo.verifiers.length == 0) {
12772            return null;
12773        }
12774
12775        final int N = pkgInfo.verifiers.length;
12776        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12777        for (int i = 0; i < N; i++) {
12778            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12779
12780            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12781                    receivers);
12782            if (comp == null) {
12783                continue;
12784            }
12785
12786            final int verifierUid = getUidForVerifier(verifierInfo);
12787            if (verifierUid == -1) {
12788                continue;
12789            }
12790
12791            if (DEBUG_VERIFY) {
12792                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12793                        + " with the correct signature");
12794            }
12795            sufficientVerifiers.add(comp);
12796            verificationState.addSufficientVerifier(verifierUid);
12797        }
12798
12799        return sufficientVerifiers;
12800    }
12801
12802    private int getUidForVerifier(VerifierInfo verifierInfo) {
12803        synchronized (mPackages) {
12804            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12805            if (pkg == null) {
12806                return -1;
12807            } else if (pkg.mSignatures.length != 1) {
12808                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12809                        + " has more than one signature; ignoring");
12810                return -1;
12811            }
12812
12813            /*
12814             * If the public key of the package's signature does not match
12815             * our expected public key, then this is a different package and
12816             * we should skip.
12817             */
12818
12819            final byte[] expectedPublicKey;
12820            try {
12821                final Signature verifierSig = pkg.mSignatures[0];
12822                final PublicKey publicKey = verifierSig.getPublicKey();
12823                expectedPublicKey = publicKey.getEncoded();
12824            } catch (CertificateException e) {
12825                return -1;
12826            }
12827
12828            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12829
12830            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12831                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12832                        + " does not have the expected public key; ignoring");
12833                return -1;
12834            }
12835
12836            return pkg.applicationInfo.uid;
12837        }
12838    }
12839
12840    @Override
12841    public void finishPackageInstall(int token, boolean didLaunch) {
12842        enforceSystemOrRoot("Only the system is allowed to finish installs");
12843
12844        if (DEBUG_INSTALL) {
12845            Slog.v(TAG, "BM finishing package install for " + token);
12846        }
12847        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12848
12849        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12850        mHandler.sendMessage(msg);
12851    }
12852
12853    /**
12854     * Get the verification agent timeout.
12855     *
12856     * @return verification timeout in milliseconds
12857     */
12858    private long getVerificationTimeout() {
12859        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12860                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12861                DEFAULT_VERIFICATION_TIMEOUT);
12862    }
12863
12864    /**
12865     * Get the default verification agent response code.
12866     *
12867     * @return default verification response code
12868     */
12869    private int getDefaultVerificationResponse() {
12870        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12871                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12872                DEFAULT_VERIFICATION_RESPONSE);
12873    }
12874
12875    /**
12876     * Check whether or not package verification has been enabled.
12877     *
12878     * @return true if verification should be performed
12879     */
12880    private boolean isVerificationEnabled(int userId, int installFlags) {
12881        if (!DEFAULT_VERIFY_ENABLE) {
12882            return false;
12883        }
12884        // Ephemeral apps don't get the full verification treatment
12885        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12886            if (DEBUG_EPHEMERAL) {
12887                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12888            }
12889            return false;
12890        }
12891
12892        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12893
12894        // Check if installing from ADB
12895        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12896            // Do not run verification in a test harness environment
12897            if (ActivityManager.isRunningInTestHarness()) {
12898                return false;
12899            }
12900            if (ensureVerifyAppsEnabled) {
12901                return true;
12902            }
12903            // Check if the developer does not want package verification for ADB installs
12904            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12905                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12906                return false;
12907            }
12908        }
12909
12910        if (ensureVerifyAppsEnabled) {
12911            return true;
12912        }
12913
12914        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12915                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12916    }
12917
12918    @Override
12919    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12920            throws RemoteException {
12921        mContext.enforceCallingOrSelfPermission(
12922                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12923                "Only intentfilter verification agents can verify applications");
12924
12925        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12926        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12927                Binder.getCallingUid(), verificationCode, failedDomains);
12928        msg.arg1 = id;
12929        msg.obj = response;
12930        mHandler.sendMessage(msg);
12931    }
12932
12933    @Override
12934    public int getIntentVerificationStatus(String packageName, int userId) {
12935        synchronized (mPackages) {
12936            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12937        }
12938    }
12939
12940    @Override
12941    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12942        mContext.enforceCallingOrSelfPermission(
12943                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12944
12945        boolean result = false;
12946        synchronized (mPackages) {
12947            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12948        }
12949        if (result) {
12950            scheduleWritePackageRestrictionsLocked(userId);
12951        }
12952        return result;
12953    }
12954
12955    @Override
12956    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12957            String packageName) {
12958        synchronized (mPackages) {
12959            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12960        }
12961    }
12962
12963    @Override
12964    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12965        if (TextUtils.isEmpty(packageName)) {
12966            return ParceledListSlice.emptyList();
12967        }
12968        synchronized (mPackages) {
12969            PackageParser.Package pkg = mPackages.get(packageName);
12970            if (pkg == null || pkg.activities == null) {
12971                return ParceledListSlice.emptyList();
12972            }
12973            final int count = pkg.activities.size();
12974            ArrayList<IntentFilter> result = new ArrayList<>();
12975            for (int n=0; n<count; n++) {
12976                PackageParser.Activity activity = pkg.activities.get(n);
12977                if (activity.intents != null && activity.intents.size() > 0) {
12978                    result.addAll(activity.intents);
12979                }
12980            }
12981            return new ParceledListSlice<>(result);
12982        }
12983    }
12984
12985    @Override
12986    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12987        mContext.enforceCallingOrSelfPermission(
12988                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12989
12990        synchronized (mPackages) {
12991            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12992            if (packageName != null) {
12993                result |= updateIntentVerificationStatus(packageName,
12994                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12995                        userId);
12996                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12997                        packageName, userId);
12998            }
12999            return result;
13000        }
13001    }
13002
13003    @Override
13004    public String getDefaultBrowserPackageName(int userId) {
13005        synchronized (mPackages) {
13006            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13007        }
13008    }
13009
13010    /**
13011     * Get the "allow unknown sources" setting.
13012     *
13013     * @return the current "allow unknown sources" setting
13014     */
13015    private int getUnknownSourcesSettings() {
13016        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13017                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13018                -1);
13019    }
13020
13021    @Override
13022    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13023        final int uid = Binder.getCallingUid();
13024        // writer
13025        synchronized (mPackages) {
13026            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13027            if (targetPackageSetting == null) {
13028                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13029            }
13030
13031            PackageSetting installerPackageSetting;
13032            if (installerPackageName != null) {
13033                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13034                if (installerPackageSetting == null) {
13035                    throw new IllegalArgumentException("Unknown installer package: "
13036                            + installerPackageName);
13037                }
13038            } else {
13039                installerPackageSetting = null;
13040            }
13041
13042            Signature[] callerSignature;
13043            Object obj = mSettings.getUserIdLPr(uid);
13044            if (obj != null) {
13045                if (obj instanceof SharedUserSetting) {
13046                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13047                } else if (obj instanceof PackageSetting) {
13048                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13049                } else {
13050                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13051                }
13052            } else {
13053                throw new SecurityException("Unknown calling UID: " + uid);
13054            }
13055
13056            // Verify: can't set installerPackageName to a package that is
13057            // not signed with the same cert as the caller.
13058            if (installerPackageSetting != null) {
13059                if (compareSignatures(callerSignature,
13060                        installerPackageSetting.signatures.mSignatures)
13061                        != PackageManager.SIGNATURE_MATCH) {
13062                    throw new SecurityException(
13063                            "Caller does not have same cert as new installer package "
13064                            + installerPackageName);
13065                }
13066            }
13067
13068            // Verify: if target already has an installer package, it must
13069            // be signed with the same cert as the caller.
13070            if (targetPackageSetting.installerPackageName != null) {
13071                PackageSetting setting = mSettings.mPackages.get(
13072                        targetPackageSetting.installerPackageName);
13073                // If the currently set package isn't valid, then it's always
13074                // okay to change it.
13075                if (setting != null) {
13076                    if (compareSignatures(callerSignature,
13077                            setting.signatures.mSignatures)
13078                            != PackageManager.SIGNATURE_MATCH) {
13079                        throw new SecurityException(
13080                                "Caller does not have same cert as old installer package "
13081                                + targetPackageSetting.installerPackageName);
13082                    }
13083                }
13084            }
13085
13086            // Okay!
13087            targetPackageSetting.installerPackageName = installerPackageName;
13088            if (installerPackageName != null) {
13089                mSettings.mInstallerPackages.add(installerPackageName);
13090            }
13091            scheduleWriteSettingsLocked();
13092        }
13093    }
13094
13095    @Override
13096    public void setApplicationCategoryHint(String packageName, int categoryHint,
13097            String callerPackageName) {
13098        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13099                callerPackageName);
13100        synchronized (mPackages) {
13101            PackageSetting ps = mSettings.mPackages.get(packageName);
13102            if (ps == null) {
13103                throw new IllegalArgumentException("Unknown target package " + packageName);
13104            }
13105
13106            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13107                throw new IllegalArgumentException("Calling package " + callerPackageName
13108                        + " is not installer for " + packageName);
13109            }
13110
13111            if (ps.categoryHint != categoryHint) {
13112                ps.categoryHint = categoryHint;
13113                scheduleWriteSettingsLocked();
13114            }
13115        }
13116    }
13117
13118    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13119        // Queue up an async operation since the package installation may take a little while.
13120        mHandler.post(new Runnable() {
13121            public void run() {
13122                mHandler.removeCallbacks(this);
13123                 // Result object to be returned
13124                PackageInstalledInfo res = new PackageInstalledInfo();
13125                res.setReturnCode(currentStatus);
13126                res.uid = -1;
13127                res.pkg = null;
13128                res.removedInfo = null;
13129                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13130                    args.doPreInstall(res.returnCode);
13131                    synchronized (mInstallLock) {
13132                        installPackageTracedLI(args, res);
13133                    }
13134                    args.doPostInstall(res.returnCode, res.uid);
13135                }
13136
13137                // A restore should be performed at this point if (a) the install
13138                // succeeded, (b) the operation is not an update, and (c) the new
13139                // package has not opted out of backup participation.
13140                final boolean update = res.removedInfo != null
13141                        && res.removedInfo.removedPackage != null;
13142                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13143                boolean doRestore = !update
13144                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13145
13146                // Set up the post-install work request bookkeeping.  This will be used
13147                // and cleaned up by the post-install event handling regardless of whether
13148                // there's a restore pass performed.  Token values are >= 1.
13149                int token;
13150                if (mNextInstallToken < 0) mNextInstallToken = 1;
13151                token = mNextInstallToken++;
13152
13153                PostInstallData data = new PostInstallData(args, res);
13154                mRunningInstalls.put(token, data);
13155                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13156
13157                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13158                    // Pass responsibility to the Backup Manager.  It will perform a
13159                    // restore if appropriate, then pass responsibility back to the
13160                    // Package Manager to run the post-install observer callbacks
13161                    // and broadcasts.
13162                    IBackupManager bm = IBackupManager.Stub.asInterface(
13163                            ServiceManager.getService(Context.BACKUP_SERVICE));
13164                    if (bm != null) {
13165                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13166                                + " to BM for possible restore");
13167                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13168                        try {
13169                            // TODO: http://b/22388012
13170                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13171                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13172                            } else {
13173                                doRestore = false;
13174                            }
13175                        } catch (RemoteException e) {
13176                            // can't happen; the backup manager is local
13177                        } catch (Exception e) {
13178                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13179                            doRestore = false;
13180                        }
13181                    } else {
13182                        Slog.e(TAG, "Backup Manager not found!");
13183                        doRestore = false;
13184                    }
13185                }
13186
13187                if (!doRestore) {
13188                    // No restore possible, or the Backup Manager was mysteriously not
13189                    // available -- just fire the post-install work request directly.
13190                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13191
13192                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13193
13194                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13195                    mHandler.sendMessage(msg);
13196                }
13197            }
13198        });
13199    }
13200
13201    /**
13202     * Callback from PackageSettings whenever an app is first transitioned out of the
13203     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13204     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13205     * here whether the app is the target of an ongoing install, and only send the
13206     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13207     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13208     * handling.
13209     */
13210    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13211        // Serialize this with the rest of the install-process message chain.  In the
13212        // restore-at-install case, this Runnable will necessarily run before the
13213        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13214        // are coherent.  In the non-restore case, the app has already completed install
13215        // and been launched through some other means, so it is not in a problematic
13216        // state for observers to see the FIRST_LAUNCH signal.
13217        mHandler.post(new Runnable() {
13218            @Override
13219            public void run() {
13220                for (int i = 0; i < mRunningInstalls.size(); i++) {
13221                    final PostInstallData data = mRunningInstalls.valueAt(i);
13222                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13223                        continue;
13224                    }
13225                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13226                        // right package; but is it for the right user?
13227                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13228                            if (userId == data.res.newUsers[uIndex]) {
13229                                if (DEBUG_BACKUP) {
13230                                    Slog.i(TAG, "Package " + pkgName
13231                                            + " being restored so deferring FIRST_LAUNCH");
13232                                }
13233                                return;
13234                            }
13235                        }
13236                    }
13237                }
13238                // didn't find it, so not being restored
13239                if (DEBUG_BACKUP) {
13240                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13241                }
13242                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13243            }
13244        });
13245    }
13246
13247    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13248        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13249                installerPkg, null, userIds);
13250    }
13251
13252    private abstract class HandlerParams {
13253        private static final int MAX_RETRIES = 4;
13254
13255        /**
13256         * Number of times startCopy() has been attempted and had a non-fatal
13257         * error.
13258         */
13259        private int mRetries = 0;
13260
13261        /** User handle for the user requesting the information or installation. */
13262        private final UserHandle mUser;
13263        String traceMethod;
13264        int traceCookie;
13265
13266        HandlerParams(UserHandle user) {
13267            mUser = user;
13268        }
13269
13270        UserHandle getUser() {
13271            return mUser;
13272        }
13273
13274        HandlerParams setTraceMethod(String traceMethod) {
13275            this.traceMethod = traceMethod;
13276            return this;
13277        }
13278
13279        HandlerParams setTraceCookie(int traceCookie) {
13280            this.traceCookie = traceCookie;
13281            return this;
13282        }
13283
13284        final boolean startCopy() {
13285            boolean res;
13286            try {
13287                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13288
13289                if (++mRetries > MAX_RETRIES) {
13290                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13291                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13292                    handleServiceError();
13293                    return false;
13294                } else {
13295                    handleStartCopy();
13296                    res = true;
13297                }
13298            } catch (RemoteException e) {
13299                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13300                mHandler.sendEmptyMessage(MCS_RECONNECT);
13301                res = false;
13302            }
13303            handleReturnCode();
13304            return res;
13305        }
13306
13307        final void serviceError() {
13308            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13309            handleServiceError();
13310            handleReturnCode();
13311        }
13312
13313        abstract void handleStartCopy() throws RemoteException;
13314        abstract void handleServiceError();
13315        abstract void handleReturnCode();
13316    }
13317
13318    class MeasureParams extends HandlerParams {
13319        private final PackageStats mStats;
13320        private boolean mSuccess;
13321
13322        private final IPackageStatsObserver mObserver;
13323
13324        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13325            super(new UserHandle(stats.userHandle));
13326            mObserver = observer;
13327            mStats = stats;
13328        }
13329
13330        @Override
13331        public String toString() {
13332            return "MeasureParams{"
13333                + Integer.toHexString(System.identityHashCode(this))
13334                + " " + mStats.packageName + "}";
13335        }
13336
13337        @Override
13338        void handleStartCopy() throws RemoteException {
13339            synchronized (mInstallLock) {
13340                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13341            }
13342
13343            if (mSuccess) {
13344                boolean mounted = false;
13345                try {
13346                    final String status = Environment.getExternalStorageState();
13347                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13348                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13349                } catch (Exception e) {
13350                }
13351
13352                if (mounted) {
13353                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13354
13355                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13356                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13357
13358                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13359                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13360
13361                    // Always subtract cache size, since it's a subdirectory
13362                    mStats.externalDataSize -= mStats.externalCacheSize;
13363
13364                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13365                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13366
13367                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13368                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13369                }
13370            }
13371        }
13372
13373        @Override
13374        void handleReturnCode() {
13375            if (mObserver != null) {
13376                try {
13377                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13378                } catch (RemoteException e) {
13379                    Slog.i(TAG, "Observer no longer exists.");
13380                }
13381            }
13382        }
13383
13384        @Override
13385        void handleServiceError() {
13386            Slog.e(TAG, "Could not measure application " + mStats.packageName
13387                            + " external storage");
13388        }
13389    }
13390
13391    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13392            throws RemoteException {
13393        long result = 0;
13394        for (File path : paths) {
13395            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13396        }
13397        return result;
13398    }
13399
13400    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13401        for (File path : paths) {
13402            try {
13403                mcs.clearDirectory(path.getAbsolutePath());
13404            } catch (RemoteException e) {
13405            }
13406        }
13407    }
13408
13409    static class OriginInfo {
13410        /**
13411         * Location where install is coming from, before it has been
13412         * copied/renamed into place. This could be a single monolithic APK
13413         * file, or a cluster directory. This location may be untrusted.
13414         */
13415        final File file;
13416        final String cid;
13417
13418        /**
13419         * Flag indicating that {@link #file} or {@link #cid} has already been
13420         * staged, meaning downstream users don't need to defensively copy the
13421         * contents.
13422         */
13423        final boolean staged;
13424
13425        /**
13426         * Flag indicating that {@link #file} or {@link #cid} is an already
13427         * installed app that is being moved.
13428         */
13429        final boolean existing;
13430
13431        final String resolvedPath;
13432        final File resolvedFile;
13433
13434        static OriginInfo fromNothing() {
13435            return new OriginInfo(null, null, false, false);
13436        }
13437
13438        static OriginInfo fromUntrustedFile(File file) {
13439            return new OriginInfo(file, null, false, false);
13440        }
13441
13442        static OriginInfo fromExistingFile(File file) {
13443            return new OriginInfo(file, null, false, true);
13444        }
13445
13446        static OriginInfo fromStagedFile(File file) {
13447            return new OriginInfo(file, null, true, false);
13448        }
13449
13450        static OriginInfo fromStagedContainer(String cid) {
13451            return new OriginInfo(null, cid, true, false);
13452        }
13453
13454        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13455            this.file = file;
13456            this.cid = cid;
13457            this.staged = staged;
13458            this.existing = existing;
13459
13460            if (cid != null) {
13461                resolvedPath = PackageHelper.getSdDir(cid);
13462                resolvedFile = new File(resolvedPath);
13463            } else if (file != null) {
13464                resolvedPath = file.getAbsolutePath();
13465                resolvedFile = file;
13466            } else {
13467                resolvedPath = null;
13468                resolvedFile = null;
13469            }
13470        }
13471    }
13472
13473    static class MoveInfo {
13474        final int moveId;
13475        final String fromUuid;
13476        final String toUuid;
13477        final String packageName;
13478        final String dataAppName;
13479        final int appId;
13480        final String seinfo;
13481        final int targetSdkVersion;
13482
13483        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13484                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13485            this.moveId = moveId;
13486            this.fromUuid = fromUuid;
13487            this.toUuid = toUuid;
13488            this.packageName = packageName;
13489            this.dataAppName = dataAppName;
13490            this.appId = appId;
13491            this.seinfo = seinfo;
13492            this.targetSdkVersion = targetSdkVersion;
13493        }
13494    }
13495
13496    static class VerificationInfo {
13497        /** A constant used to indicate that a uid value is not present. */
13498        public static final int NO_UID = -1;
13499
13500        /** URI referencing where the package was downloaded from. */
13501        final Uri originatingUri;
13502
13503        /** HTTP referrer URI associated with the originatingURI. */
13504        final Uri referrer;
13505
13506        /** UID of the application that the install request originated from. */
13507        final int originatingUid;
13508
13509        /** UID of application requesting the install */
13510        final int installerUid;
13511
13512        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13513            this.originatingUri = originatingUri;
13514            this.referrer = referrer;
13515            this.originatingUid = originatingUid;
13516            this.installerUid = installerUid;
13517        }
13518    }
13519
13520    class InstallParams extends HandlerParams {
13521        final OriginInfo origin;
13522        final MoveInfo move;
13523        final IPackageInstallObserver2 observer;
13524        int installFlags;
13525        final String installerPackageName;
13526        final String volumeUuid;
13527        private InstallArgs mArgs;
13528        private int mRet;
13529        final String packageAbiOverride;
13530        final String[] grantedRuntimePermissions;
13531        final VerificationInfo verificationInfo;
13532        final Certificate[][] certificates;
13533        final int installReason;
13534
13535        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13536                int installFlags, String installerPackageName, String volumeUuid,
13537                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13538                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
13539            super(user);
13540            this.origin = origin;
13541            this.move = move;
13542            this.observer = observer;
13543            this.installFlags = installFlags;
13544            this.installerPackageName = installerPackageName;
13545            this.volumeUuid = volumeUuid;
13546            this.verificationInfo = verificationInfo;
13547            this.packageAbiOverride = packageAbiOverride;
13548            this.grantedRuntimePermissions = grantedPermissions;
13549            this.certificates = certificates;
13550            this.installReason = installReason;
13551        }
13552
13553        @Override
13554        public String toString() {
13555            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13556                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13557        }
13558
13559        private int installLocationPolicy(PackageInfoLite pkgLite) {
13560            String packageName = pkgLite.packageName;
13561            int installLocation = pkgLite.installLocation;
13562            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13563            // reader
13564            synchronized (mPackages) {
13565                // Currently installed package which the new package is attempting to replace or
13566                // null if no such package is installed.
13567                PackageParser.Package installedPkg = mPackages.get(packageName);
13568                // Package which currently owns the data which the new package will own if installed.
13569                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13570                // will be null whereas dataOwnerPkg will contain information about the package
13571                // which was uninstalled while keeping its data.
13572                PackageParser.Package dataOwnerPkg = installedPkg;
13573                if (dataOwnerPkg  == null) {
13574                    PackageSetting ps = mSettings.mPackages.get(packageName);
13575                    if (ps != null) {
13576                        dataOwnerPkg = ps.pkg;
13577                    }
13578                }
13579
13580                if (dataOwnerPkg != null) {
13581                    // If installed, the package will get access to data left on the device by its
13582                    // predecessor. As a security measure, this is permited only if this is not a
13583                    // version downgrade or if the predecessor package is marked as debuggable and
13584                    // a downgrade is explicitly requested.
13585                    //
13586                    // On debuggable platform builds, downgrades are permitted even for
13587                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13588                    // not offer security guarantees and thus it's OK to disable some security
13589                    // mechanisms to make debugging/testing easier on those builds. However, even on
13590                    // debuggable builds downgrades of packages are permitted only if requested via
13591                    // installFlags. This is because we aim to keep the behavior of debuggable
13592                    // platform builds as close as possible to the behavior of non-debuggable
13593                    // platform builds.
13594                    final boolean downgradeRequested =
13595                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13596                    final boolean packageDebuggable =
13597                                (dataOwnerPkg.applicationInfo.flags
13598                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13599                    final boolean downgradePermitted =
13600                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13601                    if (!downgradePermitted) {
13602                        try {
13603                            checkDowngrade(dataOwnerPkg, pkgLite);
13604                        } catch (PackageManagerException e) {
13605                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13606                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13607                        }
13608                    }
13609                }
13610
13611                if (installedPkg != null) {
13612                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13613                        // Check for updated system application.
13614                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13615                            if (onSd) {
13616                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13617                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13618                            }
13619                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13620                        } else {
13621                            if (onSd) {
13622                                // Install flag overrides everything.
13623                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13624                            }
13625                            // If current upgrade specifies particular preference
13626                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13627                                // Application explicitly specified internal.
13628                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13629                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13630                                // App explictly prefers external. Let policy decide
13631                            } else {
13632                                // Prefer previous location
13633                                if (isExternal(installedPkg)) {
13634                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13635                                }
13636                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13637                            }
13638                        }
13639                    } else {
13640                        // Invalid install. Return error code
13641                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13642                    }
13643                }
13644            }
13645            // All the special cases have been taken care of.
13646            // Return result based on recommended install location.
13647            if (onSd) {
13648                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13649            }
13650            return pkgLite.recommendedInstallLocation;
13651        }
13652
13653        /*
13654         * Invoke remote method to get package information and install
13655         * location values. Override install location based on default
13656         * policy if needed and then create install arguments based
13657         * on the install location.
13658         */
13659        public void handleStartCopy() throws RemoteException {
13660            int ret = PackageManager.INSTALL_SUCCEEDED;
13661
13662            // If we're already staged, we've firmly committed to an install location
13663            if (origin.staged) {
13664                if (origin.file != null) {
13665                    installFlags |= PackageManager.INSTALL_INTERNAL;
13666                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13667                } else if (origin.cid != null) {
13668                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13669                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13670                } else {
13671                    throw new IllegalStateException("Invalid stage location");
13672                }
13673            }
13674
13675            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13676            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13677            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13678            PackageInfoLite pkgLite = null;
13679
13680            if (onInt && onSd) {
13681                // Check if both bits are set.
13682                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13683                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13684            } else if (onSd && ephemeral) {
13685                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13686                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13687            } else {
13688                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13689                        packageAbiOverride);
13690
13691                if (DEBUG_EPHEMERAL && ephemeral) {
13692                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13693                }
13694
13695                /*
13696                 * If we have too little free space, try to free cache
13697                 * before giving up.
13698                 */
13699                if (!origin.staged && pkgLite.recommendedInstallLocation
13700                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13701                    // TODO: focus freeing disk space on the target device
13702                    final StorageManager storage = StorageManager.from(mContext);
13703                    final long lowThreshold = storage.getStorageLowBytes(
13704                            Environment.getDataDirectory());
13705
13706                    final long sizeBytes = mContainerService.calculateInstalledSize(
13707                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13708
13709                    try {
13710                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13711                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13712                                installFlags, packageAbiOverride);
13713                    } catch (InstallerException e) {
13714                        Slog.w(TAG, "Failed to free cache", e);
13715                    }
13716
13717                    /*
13718                     * The cache free must have deleted the file we
13719                     * downloaded to install.
13720                     *
13721                     * TODO: fix the "freeCache" call to not delete
13722                     *       the file we care about.
13723                     */
13724                    if (pkgLite.recommendedInstallLocation
13725                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13726                        pkgLite.recommendedInstallLocation
13727                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13728                    }
13729                }
13730            }
13731
13732            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13733                int loc = pkgLite.recommendedInstallLocation;
13734                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13735                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13736                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13737                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13738                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13739                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13740                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13741                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13742                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13743                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13744                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13745                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13746                } else {
13747                    // Override with defaults if needed.
13748                    loc = installLocationPolicy(pkgLite);
13749                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13750                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13751                    } else if (!onSd && !onInt) {
13752                        // Override install location with flags
13753                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13754                            // Set the flag to install on external media.
13755                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13756                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13757                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13758                            if (DEBUG_EPHEMERAL) {
13759                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13760                            }
13761                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13762                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13763                                    |PackageManager.INSTALL_INTERNAL);
13764                        } else {
13765                            // Make sure the flag for installing on external
13766                            // media is unset
13767                            installFlags |= PackageManager.INSTALL_INTERNAL;
13768                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13769                        }
13770                    }
13771                }
13772            }
13773
13774            final InstallArgs args = createInstallArgs(this);
13775            mArgs = args;
13776
13777            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13778                // TODO: http://b/22976637
13779                // Apps installed for "all" users use the device owner to verify the app
13780                UserHandle verifierUser = getUser();
13781                if (verifierUser == UserHandle.ALL) {
13782                    verifierUser = UserHandle.SYSTEM;
13783                }
13784
13785                /*
13786                 * Determine if we have any installed package verifiers. If we
13787                 * do, then we'll defer to them to verify the packages.
13788                 */
13789                final int requiredUid = mRequiredVerifierPackage == null ? -1
13790                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13791                                verifierUser.getIdentifier());
13792                if (!origin.existing && requiredUid != -1
13793                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13794                    final Intent verification = new Intent(
13795                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13796                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13797                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13798                            PACKAGE_MIME_TYPE);
13799                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13800
13801                    // Query all live verifiers based on current user state
13802                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13803                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13804
13805                    if (DEBUG_VERIFY) {
13806                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13807                                + verification.toString() + " with " + pkgLite.verifiers.length
13808                                + " optional verifiers");
13809                    }
13810
13811                    final int verificationId = mPendingVerificationToken++;
13812
13813                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13814
13815                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13816                            installerPackageName);
13817
13818                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13819                            installFlags);
13820
13821                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13822                            pkgLite.packageName);
13823
13824                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13825                            pkgLite.versionCode);
13826
13827                    if (verificationInfo != null) {
13828                        if (verificationInfo.originatingUri != null) {
13829                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13830                                    verificationInfo.originatingUri);
13831                        }
13832                        if (verificationInfo.referrer != null) {
13833                            verification.putExtra(Intent.EXTRA_REFERRER,
13834                                    verificationInfo.referrer);
13835                        }
13836                        if (verificationInfo.originatingUid >= 0) {
13837                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13838                                    verificationInfo.originatingUid);
13839                        }
13840                        if (verificationInfo.installerUid >= 0) {
13841                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13842                                    verificationInfo.installerUid);
13843                        }
13844                    }
13845
13846                    final PackageVerificationState verificationState = new PackageVerificationState(
13847                            requiredUid, args);
13848
13849                    mPendingVerification.append(verificationId, verificationState);
13850
13851                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13852                            receivers, verificationState);
13853
13854                    /*
13855                     * If any sufficient verifiers were listed in the package
13856                     * manifest, attempt to ask them.
13857                     */
13858                    if (sufficientVerifiers != null) {
13859                        final int N = sufficientVerifiers.size();
13860                        if (N == 0) {
13861                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13862                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13863                        } else {
13864                            for (int i = 0; i < N; i++) {
13865                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13866
13867                                final Intent sufficientIntent = new Intent(verification);
13868                                sufficientIntent.setComponent(verifierComponent);
13869                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13870                            }
13871                        }
13872                    }
13873
13874                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13875                            mRequiredVerifierPackage, receivers);
13876                    if (ret == PackageManager.INSTALL_SUCCEEDED
13877                            && mRequiredVerifierPackage != null) {
13878                        Trace.asyncTraceBegin(
13879                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13880                        /*
13881                         * Send the intent to the required verification agent,
13882                         * but only start the verification timeout after the
13883                         * target BroadcastReceivers have run.
13884                         */
13885                        verification.setComponent(requiredVerifierComponent);
13886                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13887                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13888                                new BroadcastReceiver() {
13889                                    @Override
13890                                    public void onReceive(Context context, Intent intent) {
13891                                        final Message msg = mHandler
13892                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13893                                        msg.arg1 = verificationId;
13894                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13895                                    }
13896                                }, null, 0, null, null);
13897
13898                        /*
13899                         * We don't want the copy to proceed until verification
13900                         * succeeds, so null out this field.
13901                         */
13902                        mArgs = null;
13903                    }
13904                } else {
13905                    /*
13906                     * No package verification is enabled, so immediately start
13907                     * the remote call to initiate copy using temporary file.
13908                     */
13909                    ret = args.copyApk(mContainerService, true);
13910                }
13911            }
13912
13913            mRet = ret;
13914        }
13915
13916        @Override
13917        void handleReturnCode() {
13918            // If mArgs is null, then MCS couldn't be reached. When it
13919            // reconnects, it will try again to install. At that point, this
13920            // will succeed.
13921            if (mArgs != null) {
13922                processPendingInstall(mArgs, mRet);
13923            }
13924        }
13925
13926        @Override
13927        void handleServiceError() {
13928            mArgs = createInstallArgs(this);
13929            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13930        }
13931
13932        public boolean isForwardLocked() {
13933            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13934        }
13935    }
13936
13937    /**
13938     * Used during creation of InstallArgs
13939     *
13940     * @param installFlags package installation flags
13941     * @return true if should be installed on external storage
13942     */
13943    private static boolean installOnExternalAsec(int installFlags) {
13944        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13945            return false;
13946        }
13947        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13948            return true;
13949        }
13950        return false;
13951    }
13952
13953    /**
13954     * Used during creation of InstallArgs
13955     *
13956     * @param installFlags package installation flags
13957     * @return true if should be installed as forward locked
13958     */
13959    private static boolean installForwardLocked(int installFlags) {
13960        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13961    }
13962
13963    private InstallArgs createInstallArgs(InstallParams params) {
13964        if (params.move != null) {
13965            return new MoveInstallArgs(params);
13966        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13967            return new AsecInstallArgs(params);
13968        } else {
13969            return new FileInstallArgs(params);
13970        }
13971    }
13972
13973    /**
13974     * Create args that describe an existing installed package. Typically used
13975     * when cleaning up old installs, or used as a move source.
13976     */
13977    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13978            String resourcePath, String[] instructionSets) {
13979        final boolean isInAsec;
13980        if (installOnExternalAsec(installFlags)) {
13981            /* Apps on SD card are always in ASEC containers. */
13982            isInAsec = true;
13983        } else if (installForwardLocked(installFlags)
13984                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13985            /*
13986             * Forward-locked apps are only in ASEC containers if they're the
13987             * new style
13988             */
13989            isInAsec = true;
13990        } else {
13991            isInAsec = false;
13992        }
13993
13994        if (isInAsec) {
13995            return new AsecInstallArgs(codePath, instructionSets,
13996                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13997        } else {
13998            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13999        }
14000    }
14001
14002    static abstract class InstallArgs {
14003        /** @see InstallParams#origin */
14004        final OriginInfo origin;
14005        /** @see InstallParams#move */
14006        final MoveInfo move;
14007
14008        final IPackageInstallObserver2 observer;
14009        // Always refers to PackageManager flags only
14010        final int installFlags;
14011        final String installerPackageName;
14012        final String volumeUuid;
14013        final UserHandle user;
14014        final String abiOverride;
14015        final String[] installGrantPermissions;
14016        /** If non-null, drop an async trace when the install completes */
14017        final String traceMethod;
14018        final int traceCookie;
14019        final Certificate[][] certificates;
14020        final int installReason;
14021
14022        // The list of instruction sets supported by this app. This is currently
14023        // only used during the rmdex() phase to clean up resources. We can get rid of this
14024        // if we move dex files under the common app path.
14025        /* nullable */ String[] instructionSets;
14026
14027        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14028                int installFlags, String installerPackageName, String volumeUuid,
14029                UserHandle user, String[] instructionSets,
14030                String abiOverride, String[] installGrantPermissions,
14031                String traceMethod, int traceCookie, Certificate[][] certificates,
14032                int installReason) {
14033            this.origin = origin;
14034            this.move = move;
14035            this.installFlags = installFlags;
14036            this.observer = observer;
14037            this.installerPackageName = installerPackageName;
14038            this.volumeUuid = volumeUuid;
14039            this.user = user;
14040            this.instructionSets = instructionSets;
14041            this.abiOverride = abiOverride;
14042            this.installGrantPermissions = installGrantPermissions;
14043            this.traceMethod = traceMethod;
14044            this.traceCookie = traceCookie;
14045            this.certificates = certificates;
14046            this.installReason = installReason;
14047        }
14048
14049        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14050        abstract int doPreInstall(int status);
14051
14052        /**
14053         * Rename package into final resting place. All paths on the given
14054         * scanned package should be updated to reflect the rename.
14055         */
14056        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14057        abstract int doPostInstall(int status, int uid);
14058
14059        /** @see PackageSettingBase#codePathString */
14060        abstract String getCodePath();
14061        /** @see PackageSettingBase#resourcePathString */
14062        abstract String getResourcePath();
14063
14064        // Need installer lock especially for dex file removal.
14065        abstract void cleanUpResourcesLI();
14066        abstract boolean doPostDeleteLI(boolean delete);
14067
14068        /**
14069         * Called before the source arguments are copied. This is used mostly
14070         * for MoveParams when it needs to read the source file to put it in the
14071         * destination.
14072         */
14073        int doPreCopy() {
14074            return PackageManager.INSTALL_SUCCEEDED;
14075        }
14076
14077        /**
14078         * Called after the source arguments are copied. This is used mostly for
14079         * MoveParams when it needs to read the source file to put it in the
14080         * destination.
14081         */
14082        int doPostCopy(int uid) {
14083            return PackageManager.INSTALL_SUCCEEDED;
14084        }
14085
14086        protected boolean isFwdLocked() {
14087            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14088        }
14089
14090        protected boolean isExternalAsec() {
14091            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14092        }
14093
14094        protected boolean isEphemeral() {
14095            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14096        }
14097
14098        UserHandle getUser() {
14099            return user;
14100        }
14101    }
14102
14103    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14104        if (!allCodePaths.isEmpty()) {
14105            if (instructionSets == null) {
14106                throw new IllegalStateException("instructionSet == null");
14107            }
14108            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14109            for (String codePath : allCodePaths) {
14110                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14111                    try {
14112                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14113                    } catch (InstallerException ignored) {
14114                    }
14115                }
14116            }
14117        }
14118    }
14119
14120    /**
14121     * Logic to handle installation of non-ASEC applications, including copying
14122     * and renaming logic.
14123     */
14124    class FileInstallArgs extends InstallArgs {
14125        private File codeFile;
14126        private File resourceFile;
14127
14128        // Example topology:
14129        // /data/app/com.example/base.apk
14130        // /data/app/com.example/split_foo.apk
14131        // /data/app/com.example/lib/arm/libfoo.so
14132        // /data/app/com.example/lib/arm64/libfoo.so
14133        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14134
14135        /** New install */
14136        FileInstallArgs(InstallParams params) {
14137            super(params.origin, params.move, params.observer, params.installFlags,
14138                    params.installerPackageName, params.volumeUuid,
14139                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14140                    params.grantedRuntimePermissions,
14141                    params.traceMethod, params.traceCookie, params.certificates,
14142                    params.installReason);
14143            if (isFwdLocked()) {
14144                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14145            }
14146        }
14147
14148        /** Existing install */
14149        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14150            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14151                    null, null, null, 0, null /*certificates*/,
14152                    PackageManager.INSTALL_REASON_UNKNOWN);
14153            this.codeFile = (codePath != null) ? new File(codePath) : null;
14154            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14155        }
14156
14157        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14158            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14159            try {
14160                return doCopyApk(imcs, temp);
14161            } finally {
14162                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14163            }
14164        }
14165
14166        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14167            if (origin.staged) {
14168                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14169                codeFile = origin.file;
14170                resourceFile = origin.file;
14171                return PackageManager.INSTALL_SUCCEEDED;
14172            }
14173
14174            try {
14175                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14176                final File tempDir =
14177                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14178                codeFile = tempDir;
14179                resourceFile = tempDir;
14180            } catch (IOException e) {
14181                Slog.w(TAG, "Failed to create copy file: " + e);
14182                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14183            }
14184
14185            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14186                @Override
14187                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14188                    if (!FileUtils.isValidExtFilename(name)) {
14189                        throw new IllegalArgumentException("Invalid filename: " + name);
14190                    }
14191                    try {
14192                        final File file = new File(codeFile, name);
14193                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14194                                O_RDWR | O_CREAT, 0644);
14195                        Os.chmod(file.getAbsolutePath(), 0644);
14196                        return new ParcelFileDescriptor(fd);
14197                    } catch (ErrnoException e) {
14198                        throw new RemoteException("Failed to open: " + e.getMessage());
14199                    }
14200                }
14201            };
14202
14203            int ret = PackageManager.INSTALL_SUCCEEDED;
14204            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14205            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14206                Slog.e(TAG, "Failed to copy package");
14207                return ret;
14208            }
14209
14210            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14211            NativeLibraryHelper.Handle handle = null;
14212            try {
14213                handle = NativeLibraryHelper.Handle.create(codeFile);
14214                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14215                        abiOverride);
14216            } catch (IOException e) {
14217                Slog.e(TAG, "Copying native libraries failed", e);
14218                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14219            } finally {
14220                IoUtils.closeQuietly(handle);
14221            }
14222
14223            return ret;
14224        }
14225
14226        int doPreInstall(int status) {
14227            if (status != PackageManager.INSTALL_SUCCEEDED) {
14228                cleanUp();
14229            }
14230            return status;
14231        }
14232
14233        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14234            if (status != PackageManager.INSTALL_SUCCEEDED) {
14235                cleanUp();
14236                return false;
14237            }
14238
14239            final File targetDir = codeFile.getParentFile();
14240            final File beforeCodeFile = codeFile;
14241            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14242
14243            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14244            try {
14245                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14246            } catch (ErrnoException e) {
14247                Slog.w(TAG, "Failed to rename", e);
14248                return false;
14249            }
14250
14251            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14252                Slog.w(TAG, "Failed to restorecon");
14253                return false;
14254            }
14255
14256            // Reflect the rename internally
14257            codeFile = afterCodeFile;
14258            resourceFile = afterCodeFile;
14259
14260            // Reflect the rename in scanned details
14261            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14262            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14263                    afterCodeFile, pkg.baseCodePath));
14264            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14265                    afterCodeFile, pkg.splitCodePaths));
14266
14267            // Reflect the rename in app info
14268            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14269            pkg.setApplicationInfoCodePath(pkg.codePath);
14270            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14271            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14272            pkg.setApplicationInfoResourcePath(pkg.codePath);
14273            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14274            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14275
14276            return true;
14277        }
14278
14279        int doPostInstall(int status, int uid) {
14280            if (status != PackageManager.INSTALL_SUCCEEDED) {
14281                cleanUp();
14282            }
14283            return status;
14284        }
14285
14286        @Override
14287        String getCodePath() {
14288            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14289        }
14290
14291        @Override
14292        String getResourcePath() {
14293            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14294        }
14295
14296        private boolean cleanUp() {
14297            if (codeFile == null || !codeFile.exists()) {
14298                return false;
14299            }
14300
14301            removeCodePathLI(codeFile);
14302
14303            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14304                resourceFile.delete();
14305            }
14306
14307            return true;
14308        }
14309
14310        void cleanUpResourcesLI() {
14311            // Try enumerating all code paths before deleting
14312            List<String> allCodePaths = Collections.EMPTY_LIST;
14313            if (codeFile != null && codeFile.exists()) {
14314                try {
14315                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14316                    allCodePaths = pkg.getAllCodePaths();
14317                } catch (PackageParserException e) {
14318                    // Ignored; we tried our best
14319                }
14320            }
14321
14322            cleanUp();
14323            removeDexFiles(allCodePaths, instructionSets);
14324        }
14325
14326        boolean doPostDeleteLI(boolean delete) {
14327            // XXX err, shouldn't we respect the delete flag?
14328            cleanUpResourcesLI();
14329            return true;
14330        }
14331    }
14332
14333    private boolean isAsecExternal(String cid) {
14334        final String asecPath = PackageHelper.getSdFilesystem(cid);
14335        return !asecPath.startsWith(mAsecInternalPath);
14336    }
14337
14338    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14339            PackageManagerException {
14340        if (copyRet < 0) {
14341            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14342                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14343                throw new PackageManagerException(copyRet, message);
14344            }
14345        }
14346    }
14347
14348    /**
14349     * Extract the StorageManagerService "container ID" from the full code path of an
14350     * .apk.
14351     */
14352    static String cidFromCodePath(String fullCodePath) {
14353        int eidx = fullCodePath.lastIndexOf("/");
14354        String subStr1 = fullCodePath.substring(0, eidx);
14355        int sidx = subStr1.lastIndexOf("/");
14356        return subStr1.substring(sidx+1, eidx);
14357    }
14358
14359    /**
14360     * Logic to handle installation of ASEC applications, including copying and
14361     * renaming logic.
14362     */
14363    class AsecInstallArgs extends InstallArgs {
14364        static final String RES_FILE_NAME = "pkg.apk";
14365        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14366
14367        String cid;
14368        String packagePath;
14369        String resourcePath;
14370
14371        /** New install */
14372        AsecInstallArgs(InstallParams params) {
14373            super(params.origin, params.move, params.observer, params.installFlags,
14374                    params.installerPackageName, params.volumeUuid,
14375                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14376                    params.grantedRuntimePermissions,
14377                    params.traceMethod, params.traceCookie, params.certificates,
14378                    params.installReason);
14379        }
14380
14381        /** Existing install */
14382        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14383                        boolean isExternal, boolean isForwardLocked) {
14384            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14385                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14386                    instructionSets, null, null, null, 0, null /*certificates*/,
14387                    PackageManager.INSTALL_REASON_UNKNOWN);
14388            // Hackily pretend we're still looking at a full code path
14389            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14390                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14391            }
14392
14393            // Extract cid from fullCodePath
14394            int eidx = fullCodePath.lastIndexOf("/");
14395            String subStr1 = fullCodePath.substring(0, eidx);
14396            int sidx = subStr1.lastIndexOf("/");
14397            cid = subStr1.substring(sidx+1, eidx);
14398            setMountPath(subStr1);
14399        }
14400
14401        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14402            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14403                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14404                    instructionSets, null, null, null, 0, null /*certificates*/,
14405                    PackageManager.INSTALL_REASON_UNKNOWN);
14406            this.cid = cid;
14407            setMountPath(PackageHelper.getSdDir(cid));
14408        }
14409
14410        void createCopyFile() {
14411            cid = mInstallerService.allocateExternalStageCidLegacy();
14412        }
14413
14414        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14415            if (origin.staged && origin.cid != null) {
14416                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14417                cid = origin.cid;
14418                setMountPath(PackageHelper.getSdDir(cid));
14419                return PackageManager.INSTALL_SUCCEEDED;
14420            }
14421
14422            if (temp) {
14423                createCopyFile();
14424            } else {
14425                /*
14426                 * Pre-emptively destroy the container since it's destroyed if
14427                 * copying fails due to it existing anyway.
14428                 */
14429                PackageHelper.destroySdDir(cid);
14430            }
14431
14432            final String newMountPath = imcs.copyPackageToContainer(
14433                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14434                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14435
14436            if (newMountPath != null) {
14437                setMountPath(newMountPath);
14438                return PackageManager.INSTALL_SUCCEEDED;
14439            } else {
14440                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14441            }
14442        }
14443
14444        @Override
14445        String getCodePath() {
14446            return packagePath;
14447        }
14448
14449        @Override
14450        String getResourcePath() {
14451            return resourcePath;
14452        }
14453
14454        int doPreInstall(int status) {
14455            if (status != PackageManager.INSTALL_SUCCEEDED) {
14456                // Destroy container
14457                PackageHelper.destroySdDir(cid);
14458            } else {
14459                boolean mounted = PackageHelper.isContainerMounted(cid);
14460                if (!mounted) {
14461                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14462                            Process.SYSTEM_UID);
14463                    if (newMountPath != null) {
14464                        setMountPath(newMountPath);
14465                    } else {
14466                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14467                    }
14468                }
14469            }
14470            return status;
14471        }
14472
14473        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14474            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14475            String newMountPath = null;
14476            if (PackageHelper.isContainerMounted(cid)) {
14477                // Unmount the container
14478                if (!PackageHelper.unMountSdDir(cid)) {
14479                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14480                    return false;
14481                }
14482            }
14483            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14484                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14485                        " which might be stale. Will try to clean up.");
14486                // Clean up the stale container and proceed to recreate.
14487                if (!PackageHelper.destroySdDir(newCacheId)) {
14488                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14489                    return false;
14490                }
14491                // Successfully cleaned up stale container. Try to rename again.
14492                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14493                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14494                            + " inspite of cleaning it up.");
14495                    return false;
14496                }
14497            }
14498            if (!PackageHelper.isContainerMounted(newCacheId)) {
14499                Slog.w(TAG, "Mounting container " + newCacheId);
14500                newMountPath = PackageHelper.mountSdDir(newCacheId,
14501                        getEncryptKey(), Process.SYSTEM_UID);
14502            } else {
14503                newMountPath = PackageHelper.getSdDir(newCacheId);
14504            }
14505            if (newMountPath == null) {
14506                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14507                return false;
14508            }
14509            Log.i(TAG, "Succesfully renamed " + cid +
14510                    " to " + newCacheId +
14511                    " at new path: " + newMountPath);
14512            cid = newCacheId;
14513
14514            final File beforeCodeFile = new File(packagePath);
14515            setMountPath(newMountPath);
14516            final File afterCodeFile = new File(packagePath);
14517
14518            // Reflect the rename in scanned details
14519            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14520            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14521                    afterCodeFile, pkg.baseCodePath));
14522            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14523                    afterCodeFile, pkg.splitCodePaths));
14524
14525            // Reflect the rename in app info
14526            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14527            pkg.setApplicationInfoCodePath(pkg.codePath);
14528            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14529            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14530            pkg.setApplicationInfoResourcePath(pkg.codePath);
14531            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14532            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14533
14534            return true;
14535        }
14536
14537        private void setMountPath(String mountPath) {
14538            final File mountFile = new File(mountPath);
14539
14540            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14541            if (monolithicFile.exists()) {
14542                packagePath = monolithicFile.getAbsolutePath();
14543                if (isFwdLocked()) {
14544                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14545                } else {
14546                    resourcePath = packagePath;
14547                }
14548            } else {
14549                packagePath = mountFile.getAbsolutePath();
14550                resourcePath = packagePath;
14551            }
14552        }
14553
14554        int doPostInstall(int status, int uid) {
14555            if (status != PackageManager.INSTALL_SUCCEEDED) {
14556                cleanUp();
14557            } else {
14558                final int groupOwner;
14559                final String protectedFile;
14560                if (isFwdLocked()) {
14561                    groupOwner = UserHandle.getSharedAppGid(uid);
14562                    protectedFile = RES_FILE_NAME;
14563                } else {
14564                    groupOwner = -1;
14565                    protectedFile = null;
14566                }
14567
14568                if (uid < Process.FIRST_APPLICATION_UID
14569                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14570                    Slog.e(TAG, "Failed to finalize " + cid);
14571                    PackageHelper.destroySdDir(cid);
14572                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14573                }
14574
14575                boolean mounted = PackageHelper.isContainerMounted(cid);
14576                if (!mounted) {
14577                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14578                }
14579            }
14580            return status;
14581        }
14582
14583        private void cleanUp() {
14584            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14585
14586            // Destroy secure container
14587            PackageHelper.destroySdDir(cid);
14588        }
14589
14590        private List<String> getAllCodePaths() {
14591            final File codeFile = new File(getCodePath());
14592            if (codeFile != null && codeFile.exists()) {
14593                try {
14594                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14595                    return pkg.getAllCodePaths();
14596                } catch (PackageParserException e) {
14597                    // Ignored; we tried our best
14598                }
14599            }
14600            return Collections.EMPTY_LIST;
14601        }
14602
14603        void cleanUpResourcesLI() {
14604            // Enumerate all code paths before deleting
14605            cleanUpResourcesLI(getAllCodePaths());
14606        }
14607
14608        private void cleanUpResourcesLI(List<String> allCodePaths) {
14609            cleanUp();
14610            removeDexFiles(allCodePaths, instructionSets);
14611        }
14612
14613        String getPackageName() {
14614            return getAsecPackageName(cid);
14615        }
14616
14617        boolean doPostDeleteLI(boolean delete) {
14618            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14619            final List<String> allCodePaths = getAllCodePaths();
14620            boolean mounted = PackageHelper.isContainerMounted(cid);
14621            if (mounted) {
14622                // Unmount first
14623                if (PackageHelper.unMountSdDir(cid)) {
14624                    mounted = false;
14625                }
14626            }
14627            if (!mounted && delete) {
14628                cleanUpResourcesLI(allCodePaths);
14629            }
14630            return !mounted;
14631        }
14632
14633        @Override
14634        int doPreCopy() {
14635            if (isFwdLocked()) {
14636                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14637                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14638                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14639                }
14640            }
14641
14642            return PackageManager.INSTALL_SUCCEEDED;
14643        }
14644
14645        @Override
14646        int doPostCopy(int uid) {
14647            if (isFwdLocked()) {
14648                if (uid < Process.FIRST_APPLICATION_UID
14649                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14650                                RES_FILE_NAME)) {
14651                    Slog.e(TAG, "Failed to finalize " + cid);
14652                    PackageHelper.destroySdDir(cid);
14653                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14654                }
14655            }
14656
14657            return PackageManager.INSTALL_SUCCEEDED;
14658        }
14659    }
14660
14661    /**
14662     * Logic to handle movement of existing installed applications.
14663     */
14664    class MoveInstallArgs extends InstallArgs {
14665        private File codeFile;
14666        private File resourceFile;
14667
14668        /** New install */
14669        MoveInstallArgs(InstallParams params) {
14670            super(params.origin, params.move, params.observer, params.installFlags,
14671                    params.installerPackageName, params.volumeUuid,
14672                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14673                    params.grantedRuntimePermissions,
14674                    params.traceMethod, params.traceCookie, params.certificates,
14675                    params.installReason);
14676        }
14677
14678        int copyApk(IMediaContainerService imcs, boolean temp) {
14679            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14680                    + move.fromUuid + " to " + move.toUuid);
14681            synchronized (mInstaller) {
14682                try {
14683                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14684                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14685                } catch (InstallerException e) {
14686                    Slog.w(TAG, "Failed to move app", e);
14687                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14688                }
14689            }
14690
14691            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14692            resourceFile = codeFile;
14693            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14694
14695            return PackageManager.INSTALL_SUCCEEDED;
14696        }
14697
14698        int doPreInstall(int status) {
14699            if (status != PackageManager.INSTALL_SUCCEEDED) {
14700                cleanUp(move.toUuid);
14701            }
14702            return status;
14703        }
14704
14705        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14706            if (status != PackageManager.INSTALL_SUCCEEDED) {
14707                cleanUp(move.toUuid);
14708                return false;
14709            }
14710
14711            // Reflect the move in app info
14712            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14713            pkg.setApplicationInfoCodePath(pkg.codePath);
14714            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14715            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14716            pkg.setApplicationInfoResourcePath(pkg.codePath);
14717            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14718            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14719
14720            return true;
14721        }
14722
14723        int doPostInstall(int status, int uid) {
14724            if (status == PackageManager.INSTALL_SUCCEEDED) {
14725                cleanUp(move.fromUuid);
14726            } else {
14727                cleanUp(move.toUuid);
14728            }
14729            return status;
14730        }
14731
14732        @Override
14733        String getCodePath() {
14734            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14735        }
14736
14737        @Override
14738        String getResourcePath() {
14739            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14740        }
14741
14742        private boolean cleanUp(String volumeUuid) {
14743            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14744                    move.dataAppName);
14745            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14746            final int[] userIds = sUserManager.getUserIds();
14747            synchronized (mInstallLock) {
14748                // Clean up both app data and code
14749                // All package moves are frozen until finished
14750                for (int userId : userIds) {
14751                    try {
14752                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14753                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14754                    } catch (InstallerException e) {
14755                        Slog.w(TAG, String.valueOf(e));
14756                    }
14757                }
14758                removeCodePathLI(codeFile);
14759            }
14760            return true;
14761        }
14762
14763        void cleanUpResourcesLI() {
14764            throw new UnsupportedOperationException();
14765        }
14766
14767        boolean doPostDeleteLI(boolean delete) {
14768            throw new UnsupportedOperationException();
14769        }
14770    }
14771
14772    static String getAsecPackageName(String packageCid) {
14773        int idx = packageCid.lastIndexOf("-");
14774        if (idx == -1) {
14775            return packageCid;
14776        }
14777        return packageCid.substring(0, idx);
14778    }
14779
14780    // Utility method used to create code paths based on package name and available index.
14781    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14782        String idxStr = "";
14783        int idx = 1;
14784        // Fall back to default value of idx=1 if prefix is not
14785        // part of oldCodePath
14786        if (oldCodePath != null) {
14787            String subStr = oldCodePath;
14788            // Drop the suffix right away
14789            if (suffix != null && subStr.endsWith(suffix)) {
14790                subStr = subStr.substring(0, subStr.length() - suffix.length());
14791            }
14792            // If oldCodePath already contains prefix find out the
14793            // ending index to either increment or decrement.
14794            int sidx = subStr.lastIndexOf(prefix);
14795            if (sidx != -1) {
14796                subStr = subStr.substring(sidx + prefix.length());
14797                if (subStr != null) {
14798                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14799                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14800                    }
14801                    try {
14802                        idx = Integer.parseInt(subStr);
14803                        if (idx <= 1) {
14804                            idx++;
14805                        } else {
14806                            idx--;
14807                        }
14808                    } catch(NumberFormatException e) {
14809                    }
14810                }
14811            }
14812        }
14813        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14814        return prefix + idxStr;
14815    }
14816
14817    private File getNextCodePath(File targetDir, String packageName) {
14818        File result;
14819        SecureRandom random = new SecureRandom();
14820        byte[] bytes = new byte[16];
14821        do {
14822            random.nextBytes(bytes);
14823            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14824            result = new File(targetDir, packageName + "-" + suffix);
14825        } while (result.exists());
14826        return result;
14827    }
14828
14829    // Utility method that returns the relative package path with respect
14830    // to the installation directory. Like say for /data/data/com.test-1.apk
14831    // string com.test-1 is returned.
14832    static String deriveCodePathName(String codePath) {
14833        if (codePath == null) {
14834            return null;
14835        }
14836        final File codeFile = new File(codePath);
14837        final String name = codeFile.getName();
14838        if (codeFile.isDirectory()) {
14839            return name;
14840        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14841            final int lastDot = name.lastIndexOf('.');
14842            return name.substring(0, lastDot);
14843        } else {
14844            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14845            return null;
14846        }
14847    }
14848
14849    static class PackageInstalledInfo {
14850        String name;
14851        int uid;
14852        // The set of users that originally had this package installed.
14853        int[] origUsers;
14854        // The set of users that now have this package installed.
14855        int[] newUsers;
14856        PackageParser.Package pkg;
14857        int returnCode;
14858        String returnMsg;
14859        PackageRemovedInfo removedInfo;
14860        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14861
14862        public void setError(int code, String msg) {
14863            setReturnCode(code);
14864            setReturnMessage(msg);
14865            Slog.w(TAG, msg);
14866        }
14867
14868        public void setError(String msg, PackageParserException e) {
14869            setReturnCode(e.error);
14870            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14871            Slog.w(TAG, msg, e);
14872        }
14873
14874        public void setError(String msg, PackageManagerException e) {
14875            returnCode = e.error;
14876            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14877            Slog.w(TAG, msg, e);
14878        }
14879
14880        public void setReturnCode(int returnCode) {
14881            this.returnCode = returnCode;
14882            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14883            for (int i = 0; i < childCount; i++) {
14884                addedChildPackages.valueAt(i).returnCode = returnCode;
14885            }
14886        }
14887
14888        private void setReturnMessage(String returnMsg) {
14889            this.returnMsg = returnMsg;
14890            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14891            for (int i = 0; i < childCount; i++) {
14892                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14893            }
14894        }
14895
14896        // In some error cases we want to convey more info back to the observer
14897        String origPackage;
14898        String origPermission;
14899    }
14900
14901    /*
14902     * Install a non-existing package.
14903     */
14904    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14905            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14906            PackageInstalledInfo res, int installReason) {
14907        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14908
14909        // Remember this for later, in case we need to rollback this install
14910        String pkgName = pkg.packageName;
14911
14912        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14913
14914        synchronized(mPackages) {
14915            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14916            if (renamedPackage != null) {
14917                // A package with the same name is already installed, though
14918                // it has been renamed to an older name.  The package we
14919                // are trying to install should be installed as an update to
14920                // the existing one, but that has not been requested, so bail.
14921                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14922                        + " without first uninstalling package running as "
14923                        + renamedPackage);
14924                return;
14925            }
14926            if (mPackages.containsKey(pkgName)) {
14927                // Don't allow installation over an existing package with the same name.
14928                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14929                        + " without first uninstalling.");
14930                return;
14931            }
14932        }
14933
14934        try {
14935            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14936                    System.currentTimeMillis(), user);
14937
14938            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
14939
14940            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14941                prepareAppDataAfterInstallLIF(newPackage);
14942
14943            } else {
14944                // Remove package from internal structures, but keep around any
14945                // data that might have already existed
14946                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14947                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14948            }
14949        } catch (PackageManagerException e) {
14950            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14951        }
14952
14953        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14954    }
14955
14956    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14957        // Can't rotate keys during boot or if sharedUser.
14958        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14959                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14960            return false;
14961        }
14962        // app is using upgradeKeySets; make sure all are valid
14963        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14964        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14965        for (int i = 0; i < upgradeKeySets.length; i++) {
14966            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14967                Slog.wtf(TAG, "Package "
14968                         + (oldPs.name != null ? oldPs.name : "<null>")
14969                         + " contains upgrade-key-set reference to unknown key-set: "
14970                         + upgradeKeySets[i]
14971                         + " reverting to signatures check.");
14972                return false;
14973            }
14974        }
14975        return true;
14976    }
14977
14978    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14979        // Upgrade keysets are being used.  Determine if new package has a superset of the
14980        // required keys.
14981        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14982        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14983        for (int i = 0; i < upgradeKeySets.length; i++) {
14984            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14985            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14986                return true;
14987            }
14988        }
14989        return false;
14990    }
14991
14992    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14993        try (DigestInputStream digestStream =
14994                new DigestInputStream(new FileInputStream(file), digest)) {
14995            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14996        }
14997    }
14998
14999    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15000            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15001            int installReason) {
15002        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15003
15004        final PackageParser.Package oldPackage;
15005        final String pkgName = pkg.packageName;
15006        final int[] allUsers;
15007        final int[] installedUsers;
15008
15009        synchronized(mPackages) {
15010            oldPackage = mPackages.get(pkgName);
15011            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15012
15013            // don't allow upgrade to target a release SDK from a pre-release SDK
15014            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15015                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15016            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15017                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15018            if (oldTargetsPreRelease
15019                    && !newTargetsPreRelease
15020                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15021                Slog.w(TAG, "Can't install package targeting released sdk");
15022                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15023                return;
15024            }
15025
15026            // don't allow an upgrade from full to ephemeral
15027            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
15028            if (isEphemeral && !oldIsEphemeral) {
15029                // can't downgrade from full to ephemeral
15030                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15031                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15032                return;
15033            }
15034
15035            // verify signatures are valid
15036            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15037            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15038                if (!checkUpgradeKeySetLP(ps, pkg)) {
15039                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15040                            "New package not signed by keys specified by upgrade-keysets: "
15041                                    + pkgName);
15042                    return;
15043                }
15044            } else {
15045                // default to original signature matching
15046                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15047                        != PackageManager.SIGNATURE_MATCH) {
15048                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15049                            "New package has a different signature: " + pkgName);
15050                    return;
15051                }
15052            }
15053
15054            // don't allow a system upgrade unless the upgrade hash matches
15055            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15056                byte[] digestBytes = null;
15057                try {
15058                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15059                    updateDigest(digest, new File(pkg.baseCodePath));
15060                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15061                        for (String path : pkg.splitCodePaths) {
15062                            updateDigest(digest, new File(path));
15063                        }
15064                    }
15065                    digestBytes = digest.digest();
15066                } catch (NoSuchAlgorithmException | IOException e) {
15067                    res.setError(INSTALL_FAILED_INVALID_APK,
15068                            "Could not compute hash: " + pkgName);
15069                    return;
15070                }
15071                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15072                    res.setError(INSTALL_FAILED_INVALID_APK,
15073                            "New package fails restrict-update check: " + pkgName);
15074                    return;
15075                }
15076                // retain upgrade restriction
15077                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15078            }
15079
15080            // Check for shared user id changes
15081            String invalidPackageName =
15082                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15083            if (invalidPackageName != null) {
15084                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15085                        "Package " + invalidPackageName + " tried to change user "
15086                                + oldPackage.mSharedUserId);
15087                return;
15088            }
15089
15090            // In case of rollback, remember per-user/profile install state
15091            allUsers = sUserManager.getUserIds();
15092            installedUsers = ps.queryInstalledUsers(allUsers, true);
15093        }
15094
15095        // Update what is removed
15096        res.removedInfo = new PackageRemovedInfo();
15097        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15098        res.removedInfo.removedPackage = oldPackage.packageName;
15099        res.removedInfo.isUpdate = true;
15100        res.removedInfo.origUsers = installedUsers;
15101        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15102        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15103        for (int i = 0; i < installedUsers.length; i++) {
15104            final int userId = installedUsers[i];
15105            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15106        }
15107
15108        final int childCount = (oldPackage.childPackages != null)
15109                ? oldPackage.childPackages.size() : 0;
15110        for (int i = 0; i < childCount; i++) {
15111            boolean childPackageUpdated = false;
15112            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15113            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15114            if (res.addedChildPackages != null) {
15115                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15116                if (childRes != null) {
15117                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15118                    childRes.removedInfo.removedPackage = childPkg.packageName;
15119                    childRes.removedInfo.isUpdate = true;
15120                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15121                    childPackageUpdated = true;
15122                }
15123            }
15124            if (!childPackageUpdated) {
15125                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15126                childRemovedRes.removedPackage = childPkg.packageName;
15127                childRemovedRes.isUpdate = false;
15128                childRemovedRes.dataRemoved = true;
15129                synchronized (mPackages) {
15130                    if (childPs != null) {
15131                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15132                    }
15133                }
15134                if (res.removedInfo.removedChildPackages == null) {
15135                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15136                }
15137                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15138            }
15139        }
15140
15141        boolean sysPkg = (isSystemApp(oldPackage));
15142        if (sysPkg) {
15143            // Set the system/privileged flags as needed
15144            final boolean privileged =
15145                    (oldPackage.applicationInfo.privateFlags
15146                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15147            final int systemPolicyFlags = policyFlags
15148                    | PackageParser.PARSE_IS_SYSTEM
15149                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15150
15151            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15152                    user, allUsers, installerPackageName, res, installReason);
15153        } else {
15154            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15155                    user, allUsers, installerPackageName, res, installReason);
15156        }
15157    }
15158
15159    public List<String> getPreviousCodePaths(String packageName) {
15160        final PackageSetting ps = mSettings.mPackages.get(packageName);
15161        final List<String> result = new ArrayList<String>();
15162        if (ps != null && ps.oldCodePaths != null) {
15163            result.addAll(ps.oldCodePaths);
15164        }
15165        return result;
15166    }
15167
15168    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15169            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15170            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15171            int installReason) {
15172        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15173                + deletedPackage);
15174
15175        String pkgName = deletedPackage.packageName;
15176        boolean deletedPkg = true;
15177        boolean addedPkg = false;
15178        boolean updatedSettings = false;
15179        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15180        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15181                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15182
15183        final long origUpdateTime = (pkg.mExtras != null)
15184                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15185
15186        // First delete the existing package while retaining the data directory
15187        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15188                res.removedInfo, true, pkg)) {
15189            // If the existing package wasn't successfully deleted
15190            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15191            deletedPkg = false;
15192        } else {
15193            // Successfully deleted the old package; proceed with replace.
15194
15195            // If deleted package lived in a container, give users a chance to
15196            // relinquish resources before killing.
15197            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15198                if (DEBUG_INSTALL) {
15199                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15200                }
15201                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15202                final ArrayList<String> pkgList = new ArrayList<String>(1);
15203                pkgList.add(deletedPackage.applicationInfo.packageName);
15204                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15205            }
15206
15207            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15208                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15209            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15210
15211            try {
15212                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15213                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15214                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15215                        installReason);
15216
15217                // Update the in-memory copy of the previous code paths.
15218                PackageSetting ps = mSettings.mPackages.get(pkgName);
15219                if (!killApp) {
15220                    if (ps.oldCodePaths == null) {
15221                        ps.oldCodePaths = new ArraySet<>();
15222                    }
15223                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15224                    if (deletedPackage.splitCodePaths != null) {
15225                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15226                    }
15227                } else {
15228                    ps.oldCodePaths = null;
15229                }
15230                if (ps.childPackageNames != null) {
15231                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15232                        final String childPkgName = ps.childPackageNames.get(i);
15233                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15234                        childPs.oldCodePaths = ps.oldCodePaths;
15235                    }
15236                }
15237                prepareAppDataAfterInstallLIF(newPackage);
15238                addedPkg = true;
15239            } catch (PackageManagerException e) {
15240                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15241            }
15242        }
15243
15244        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15245            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15246
15247            // Revert all internal state mutations and added folders for the failed install
15248            if (addedPkg) {
15249                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15250                        res.removedInfo, true, null);
15251            }
15252
15253            // Restore the old package
15254            if (deletedPkg) {
15255                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15256                File restoreFile = new File(deletedPackage.codePath);
15257                // Parse old package
15258                boolean oldExternal = isExternal(deletedPackage);
15259                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15260                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15261                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15262                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15263                try {
15264                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15265                            null);
15266                } catch (PackageManagerException e) {
15267                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15268                            + e.getMessage());
15269                    return;
15270                }
15271
15272                synchronized (mPackages) {
15273                    // Ensure the installer package name up to date
15274                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15275
15276                    // Update permissions for restored package
15277                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15278
15279                    mSettings.writeLPr();
15280                }
15281
15282                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15283            }
15284        } else {
15285            synchronized (mPackages) {
15286                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15287                if (ps != null) {
15288                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15289                    if (res.removedInfo.removedChildPackages != null) {
15290                        final int childCount = res.removedInfo.removedChildPackages.size();
15291                        // Iterate in reverse as we may modify the collection
15292                        for (int i = childCount - 1; i >= 0; i--) {
15293                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15294                            if (res.addedChildPackages.containsKey(childPackageName)) {
15295                                res.removedInfo.removedChildPackages.removeAt(i);
15296                            } else {
15297                                PackageRemovedInfo childInfo = res.removedInfo
15298                                        .removedChildPackages.valueAt(i);
15299                                childInfo.removedForAllUsers = mPackages.get(
15300                                        childInfo.removedPackage) == null;
15301                            }
15302                        }
15303                    }
15304                }
15305            }
15306        }
15307    }
15308
15309    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15310            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15311            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15312            int installReason) {
15313        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15314                + ", old=" + deletedPackage);
15315
15316        final boolean disabledSystem;
15317
15318        // Remove existing system package
15319        removePackageLI(deletedPackage, true);
15320
15321        synchronized (mPackages) {
15322            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15323        }
15324        if (!disabledSystem) {
15325            // We didn't need to disable the .apk as a current system package,
15326            // which means we are replacing another update that is already
15327            // installed.  We need to make sure to delete the older one's .apk.
15328            res.removedInfo.args = createInstallArgsForExisting(0,
15329                    deletedPackage.applicationInfo.getCodePath(),
15330                    deletedPackage.applicationInfo.getResourcePath(),
15331                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15332        } else {
15333            res.removedInfo.args = null;
15334        }
15335
15336        // Successfully disabled the old package. Now proceed with re-installation
15337        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15338                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15339        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15340
15341        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15342        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15343                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15344
15345        PackageParser.Package newPackage = null;
15346        try {
15347            // Add the package to the internal data structures
15348            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15349
15350            // Set the update and install times
15351            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15352            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15353                    System.currentTimeMillis());
15354
15355            // Update the package dynamic state if succeeded
15356            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15357                // Now that the install succeeded make sure we remove data
15358                // directories for any child package the update removed.
15359                final int deletedChildCount = (deletedPackage.childPackages != null)
15360                        ? deletedPackage.childPackages.size() : 0;
15361                final int newChildCount = (newPackage.childPackages != null)
15362                        ? newPackage.childPackages.size() : 0;
15363                for (int i = 0; i < deletedChildCount; i++) {
15364                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15365                    boolean childPackageDeleted = true;
15366                    for (int j = 0; j < newChildCount; j++) {
15367                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15368                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15369                            childPackageDeleted = false;
15370                            break;
15371                        }
15372                    }
15373                    if (childPackageDeleted) {
15374                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15375                                deletedChildPkg.packageName);
15376                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15377                            PackageRemovedInfo removedChildRes = res.removedInfo
15378                                    .removedChildPackages.get(deletedChildPkg.packageName);
15379                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15380                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15381                        }
15382                    }
15383                }
15384
15385                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15386                        installReason);
15387                prepareAppDataAfterInstallLIF(newPackage);
15388            }
15389        } catch (PackageManagerException e) {
15390            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15391            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15392        }
15393
15394        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15395            // Re installation failed. Restore old information
15396            // Remove new pkg information
15397            if (newPackage != null) {
15398                removeInstalledPackageLI(newPackage, true);
15399            }
15400            // Add back the old system package
15401            try {
15402                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15403            } catch (PackageManagerException e) {
15404                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15405            }
15406
15407            synchronized (mPackages) {
15408                if (disabledSystem) {
15409                    enableSystemPackageLPw(deletedPackage);
15410                }
15411
15412                // Ensure the installer package name up to date
15413                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15414
15415                // Update permissions for restored package
15416                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15417
15418                mSettings.writeLPr();
15419            }
15420
15421            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15422                    + " after failed upgrade");
15423        }
15424    }
15425
15426    /**
15427     * Checks whether the parent or any of the child packages have a change shared
15428     * user. For a package to be a valid update the shred users of the parent and
15429     * the children should match. We may later support changing child shared users.
15430     * @param oldPkg The updated package.
15431     * @param newPkg The update package.
15432     * @return The shared user that change between the versions.
15433     */
15434    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15435            PackageParser.Package newPkg) {
15436        // Check parent shared user
15437        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15438            return newPkg.packageName;
15439        }
15440        // Check child shared users
15441        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15442        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15443        for (int i = 0; i < newChildCount; i++) {
15444            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15445            // If this child was present, did it have the same shared user?
15446            for (int j = 0; j < oldChildCount; j++) {
15447                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15448                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15449                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15450                    return newChildPkg.packageName;
15451                }
15452            }
15453        }
15454        return null;
15455    }
15456
15457    private void removeNativeBinariesLI(PackageSetting ps) {
15458        // Remove the lib path for the parent package
15459        if (ps != null) {
15460            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15461            // Remove the lib path for the child packages
15462            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15463            for (int i = 0; i < childCount; i++) {
15464                PackageSetting childPs = null;
15465                synchronized (mPackages) {
15466                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15467                }
15468                if (childPs != null) {
15469                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15470                            .legacyNativeLibraryPathString);
15471                }
15472            }
15473        }
15474    }
15475
15476    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15477        // Enable the parent package
15478        mSettings.enableSystemPackageLPw(pkg.packageName);
15479        // Enable the child packages
15480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15481        for (int i = 0; i < childCount; i++) {
15482            PackageParser.Package childPkg = pkg.childPackages.get(i);
15483            mSettings.enableSystemPackageLPw(childPkg.packageName);
15484        }
15485    }
15486
15487    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15488            PackageParser.Package newPkg) {
15489        // Disable the parent package (parent always replaced)
15490        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15491        // Disable the child packages
15492        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15493        for (int i = 0; i < childCount; i++) {
15494            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15495            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15496            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15497        }
15498        return disabled;
15499    }
15500
15501    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15502            String installerPackageName) {
15503        // Enable the parent package
15504        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15505        // Enable the child packages
15506        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15507        for (int i = 0; i < childCount; i++) {
15508            PackageParser.Package childPkg = pkg.childPackages.get(i);
15509            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15510        }
15511    }
15512
15513    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15514        // Collect all used permissions in the UID
15515        ArraySet<String> usedPermissions = new ArraySet<>();
15516        final int packageCount = su.packages.size();
15517        for (int i = 0; i < packageCount; i++) {
15518            PackageSetting ps = su.packages.valueAt(i);
15519            if (ps.pkg == null) {
15520                continue;
15521            }
15522            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15523            for (int j = 0; j < requestedPermCount; j++) {
15524                String permission = ps.pkg.requestedPermissions.get(j);
15525                BasePermission bp = mSettings.mPermissions.get(permission);
15526                if (bp != null) {
15527                    usedPermissions.add(permission);
15528                }
15529            }
15530        }
15531
15532        PermissionsState permissionsState = su.getPermissionsState();
15533        // Prune install permissions
15534        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15535        final int installPermCount = installPermStates.size();
15536        for (int i = installPermCount - 1; i >= 0;  i--) {
15537            PermissionState permissionState = installPermStates.get(i);
15538            if (!usedPermissions.contains(permissionState.getName())) {
15539                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15540                if (bp != null) {
15541                    permissionsState.revokeInstallPermission(bp);
15542                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15543                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15544                }
15545            }
15546        }
15547
15548        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15549
15550        // Prune runtime permissions
15551        for (int userId : allUserIds) {
15552            List<PermissionState> runtimePermStates = permissionsState
15553                    .getRuntimePermissionStates(userId);
15554            final int runtimePermCount = runtimePermStates.size();
15555            for (int i = runtimePermCount - 1; i >= 0; i--) {
15556                PermissionState permissionState = runtimePermStates.get(i);
15557                if (!usedPermissions.contains(permissionState.getName())) {
15558                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15559                    if (bp != null) {
15560                        permissionsState.revokeRuntimePermission(bp, userId);
15561                        permissionsState.updatePermissionFlags(bp, userId,
15562                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15563                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15564                                runtimePermissionChangedUserIds, userId);
15565                    }
15566                }
15567            }
15568        }
15569
15570        return runtimePermissionChangedUserIds;
15571    }
15572
15573    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15574            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15575        // Update the parent package setting
15576        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15577                res, user, installReason);
15578        // Update the child packages setting
15579        final int childCount = (newPackage.childPackages != null)
15580                ? newPackage.childPackages.size() : 0;
15581        for (int i = 0; i < childCount; i++) {
15582            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15583            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15584            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15585                    childRes.origUsers, childRes, user, installReason);
15586        }
15587    }
15588
15589    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15590            String installerPackageName, int[] allUsers, int[] installedForUsers,
15591            PackageInstalledInfo res, UserHandle user, int installReason) {
15592        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15593
15594        String pkgName = newPackage.packageName;
15595        synchronized (mPackages) {
15596            //write settings. the installStatus will be incomplete at this stage.
15597            //note that the new package setting would have already been
15598            //added to mPackages. It hasn't been persisted yet.
15599            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15600            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15601            mSettings.writeLPr();
15602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15603        }
15604
15605        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15606        synchronized (mPackages) {
15607            updatePermissionsLPw(newPackage.packageName, newPackage,
15608                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15609                            ? UPDATE_PERMISSIONS_ALL : 0));
15610            // For system-bundled packages, we assume that installing an upgraded version
15611            // of the package implies that the user actually wants to run that new code,
15612            // so we enable the package.
15613            PackageSetting ps = mSettings.mPackages.get(pkgName);
15614            final int userId = user.getIdentifier();
15615            if (ps != null) {
15616                if (isSystemApp(newPackage)) {
15617                    if (DEBUG_INSTALL) {
15618                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15619                    }
15620                    // Enable system package for requested users
15621                    if (res.origUsers != null) {
15622                        for (int origUserId : res.origUsers) {
15623                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15624                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15625                                        origUserId, installerPackageName);
15626                            }
15627                        }
15628                    }
15629                    // Also convey the prior install/uninstall state
15630                    if (allUsers != null && installedForUsers != null) {
15631                        for (int currentUserId : allUsers) {
15632                            final boolean installed = ArrayUtils.contains(
15633                                    installedForUsers, currentUserId);
15634                            if (DEBUG_INSTALL) {
15635                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15636                            }
15637                            ps.setInstalled(installed, currentUserId);
15638                        }
15639                        // these install state changes will be persisted in the
15640                        // upcoming call to mSettings.writeLPr().
15641                    }
15642                }
15643                // It's implied that when a user requests installation, they want the app to be
15644                // installed and enabled.
15645                if (userId != UserHandle.USER_ALL) {
15646                    ps.setInstalled(true, userId);
15647                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15648                }
15649
15650                // When replacing an existing package, preserve the original install reason for all
15651                // users that had the package installed before.
15652                final Set<Integer> previousUserIds = new ArraySet<>();
15653                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15654                    final int installReasonCount = res.removedInfo.installReasons.size();
15655                    for (int i = 0; i < installReasonCount; i++) {
15656                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15657                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15658                        ps.setInstallReason(previousInstallReason, previousUserId);
15659                        previousUserIds.add(previousUserId);
15660                    }
15661                }
15662
15663                // Set install reason for users that are having the package newly installed.
15664                if (userId == UserHandle.USER_ALL) {
15665                    for (int currentUserId : sUserManager.getUserIds()) {
15666                        if (!previousUserIds.contains(currentUserId)) {
15667                            ps.setInstallReason(installReason, currentUserId);
15668                        }
15669                    }
15670                } else if (!previousUserIds.contains(userId)) {
15671                    ps.setInstallReason(installReason, userId);
15672                }
15673            }
15674            res.name = pkgName;
15675            res.uid = newPackage.applicationInfo.uid;
15676            res.pkg = newPackage;
15677            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15678            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15679            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15680            //to update install status
15681            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15682            mSettings.writeLPr();
15683            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15684        }
15685
15686        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15687    }
15688
15689    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15690        try {
15691            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15692            installPackageLI(args, res);
15693        } finally {
15694            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15695        }
15696    }
15697
15698    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15699        final int installFlags = args.installFlags;
15700        final String installerPackageName = args.installerPackageName;
15701        final String volumeUuid = args.volumeUuid;
15702        final File tmpPackageFile = new File(args.getCodePath());
15703        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15704        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15705                || (args.volumeUuid != null));
15706        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15707        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15708        boolean replace = false;
15709        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15710        if (args.move != null) {
15711            // moving a complete application; perform an initial scan on the new install location
15712            scanFlags |= SCAN_INITIAL;
15713        }
15714        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15715            scanFlags |= SCAN_DONT_KILL_APP;
15716        }
15717
15718        // Result object to be returned
15719        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15720
15721        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15722
15723        // Sanity check
15724        if (ephemeral && (forwardLocked || onExternal)) {
15725            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15726                    + " external=" + onExternal);
15727            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15728            return;
15729        }
15730
15731        // Retrieve PackageSettings and parse package
15732        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15733                | PackageParser.PARSE_ENFORCE_CODE
15734                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15735                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15736                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15737                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15738        PackageParser pp = new PackageParser();
15739        pp.setSeparateProcesses(mSeparateProcesses);
15740        pp.setDisplayMetrics(mMetrics);
15741
15742        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15743        final PackageParser.Package pkg;
15744        try {
15745            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15746        } catch (PackageParserException e) {
15747            res.setError("Failed parse during installPackageLI", e);
15748            return;
15749        } finally {
15750            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15751        }
15752
15753        // Ephemeral apps must have target SDK >= O.
15754        // TODO: Update conditional and error message when O gets locked down
15755        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15756            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15757                    "Ephemeral apps must have target SDK version of at least O");
15758            return;
15759        }
15760
15761        // If we are installing a clustered package add results for the children
15762        if (pkg.childPackages != null) {
15763            synchronized (mPackages) {
15764                final int childCount = pkg.childPackages.size();
15765                for (int i = 0; i < childCount; i++) {
15766                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15767                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15768                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15769                    childRes.pkg = childPkg;
15770                    childRes.name = childPkg.packageName;
15771                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15772                    if (childPs != null) {
15773                        childRes.origUsers = childPs.queryInstalledUsers(
15774                                sUserManager.getUserIds(), true);
15775                    }
15776                    if ((mPackages.containsKey(childPkg.packageName))) {
15777                        childRes.removedInfo = new PackageRemovedInfo();
15778                        childRes.removedInfo.removedPackage = childPkg.packageName;
15779                    }
15780                    if (res.addedChildPackages == null) {
15781                        res.addedChildPackages = new ArrayMap<>();
15782                    }
15783                    res.addedChildPackages.put(childPkg.packageName, childRes);
15784                }
15785            }
15786        }
15787
15788        // If package doesn't declare API override, mark that we have an install
15789        // time CPU ABI override.
15790        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15791            pkg.cpuAbiOverride = args.abiOverride;
15792        }
15793
15794        String pkgName = res.name = pkg.packageName;
15795        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15796            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15797                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15798                return;
15799            }
15800        }
15801
15802        try {
15803            // either use what we've been given or parse directly from the APK
15804            if (args.certificates != null) {
15805                try {
15806                    PackageParser.populateCertificates(pkg, args.certificates);
15807                } catch (PackageParserException e) {
15808                    // there was something wrong with the certificates we were given;
15809                    // try to pull them from the APK
15810                    PackageParser.collectCertificates(pkg, parseFlags);
15811                }
15812            } else {
15813                PackageParser.collectCertificates(pkg, parseFlags);
15814            }
15815        } catch (PackageParserException e) {
15816            res.setError("Failed collect during installPackageLI", e);
15817            return;
15818        }
15819
15820        // Get rid of all references to package scan path via parser.
15821        pp = null;
15822        String oldCodePath = null;
15823        boolean systemApp = false;
15824        synchronized (mPackages) {
15825            // Check if installing already existing package
15826            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15827                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15828                if (pkg.mOriginalPackages != null
15829                        && pkg.mOriginalPackages.contains(oldName)
15830                        && mPackages.containsKey(oldName)) {
15831                    // This package is derived from an original package,
15832                    // and this device has been updating from that original
15833                    // name.  We must continue using the original name, so
15834                    // rename the new package here.
15835                    pkg.setPackageName(oldName);
15836                    pkgName = pkg.packageName;
15837                    replace = true;
15838                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15839                            + oldName + " pkgName=" + pkgName);
15840                } else if (mPackages.containsKey(pkgName)) {
15841                    // This package, under its official name, already exists
15842                    // on the device; we should replace it.
15843                    replace = true;
15844                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15845                }
15846
15847                // Child packages are installed through the parent package
15848                if (pkg.parentPackage != null) {
15849                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15850                            "Package " + pkg.packageName + " is child of package "
15851                                    + pkg.parentPackage.parentPackage + ". Child packages "
15852                                    + "can be updated only through the parent package.");
15853                    return;
15854                }
15855
15856                if (replace) {
15857                    // Prevent apps opting out from runtime permissions
15858                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15859                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15860                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15861                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15862                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15863                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15864                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15865                                        + " doesn't support runtime permissions but the old"
15866                                        + " target SDK " + oldTargetSdk + " does.");
15867                        return;
15868                    }
15869
15870                    // Prevent installing of child packages
15871                    if (oldPackage.parentPackage != null) {
15872                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15873                                "Package " + pkg.packageName + " is child of package "
15874                                        + oldPackage.parentPackage + ". Child packages "
15875                                        + "can be updated only through the parent package.");
15876                        return;
15877                    }
15878                }
15879            }
15880
15881            PackageSetting ps = mSettings.mPackages.get(pkgName);
15882            if (ps != null) {
15883                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15884
15885                // Quick sanity check that we're signed correctly if updating;
15886                // we'll check this again later when scanning, but we want to
15887                // bail early here before tripping over redefined permissions.
15888                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15889                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15890                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15891                                + pkg.packageName + " upgrade keys do not match the "
15892                                + "previously installed version");
15893                        return;
15894                    }
15895                } else {
15896                    try {
15897                        verifySignaturesLP(ps, pkg);
15898                    } catch (PackageManagerException e) {
15899                        res.setError(e.error, e.getMessage());
15900                        return;
15901                    }
15902                }
15903
15904                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15905                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15906                    systemApp = (ps.pkg.applicationInfo.flags &
15907                            ApplicationInfo.FLAG_SYSTEM) != 0;
15908                }
15909                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15910            }
15911
15912            // Check whether the newly-scanned package wants to define an already-defined perm
15913            int N = pkg.permissions.size();
15914            for (int i = N-1; i >= 0; i--) {
15915                PackageParser.Permission perm = pkg.permissions.get(i);
15916                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15917                if (bp != null) {
15918                    // If the defining package is signed with our cert, it's okay.  This
15919                    // also includes the "updating the same package" case, of course.
15920                    // "updating same package" could also involve key-rotation.
15921                    final boolean sigsOk;
15922                    if (bp.sourcePackage.equals(pkg.packageName)
15923                            && (bp.packageSetting instanceof PackageSetting)
15924                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15925                                    scanFlags))) {
15926                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15927                    } else {
15928                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15929                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15930                    }
15931                    if (!sigsOk) {
15932                        // If the owning package is the system itself, we log but allow
15933                        // install to proceed; we fail the install on all other permission
15934                        // redefinitions.
15935                        if (!bp.sourcePackage.equals("android")) {
15936                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15937                                    + pkg.packageName + " attempting to redeclare permission "
15938                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15939                            res.origPermission = perm.info.name;
15940                            res.origPackage = bp.sourcePackage;
15941                            return;
15942                        } else {
15943                            Slog.w(TAG, "Package " + pkg.packageName
15944                                    + " attempting to redeclare system permission "
15945                                    + perm.info.name + "; ignoring new declaration");
15946                            pkg.permissions.remove(i);
15947                        }
15948                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15949                        // Prevent apps to change protection level to dangerous from any other
15950                        // type as this would allow a privilege escalation where an app adds a
15951                        // normal/signature permission in other app's group and later redefines
15952                        // it as dangerous leading to the group auto-grant.
15953                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15954                                == PermissionInfo.PROTECTION_DANGEROUS) {
15955                            if (bp != null && !bp.isRuntime()) {
15956                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15957                                        + "non-runtime permission " + perm.info.name
15958                                        + " to runtime; keeping old protection level");
15959                                perm.info.protectionLevel = bp.protectionLevel;
15960                            }
15961                        }
15962                    }
15963                }
15964            }
15965        }
15966
15967        if (systemApp) {
15968            if (onExternal) {
15969                // Abort update; system app can't be replaced with app on sdcard
15970                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15971                        "Cannot install updates to system apps on sdcard");
15972                return;
15973            } else if (ephemeral) {
15974                // Abort update; system app can't be replaced with an ephemeral app
15975                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15976                        "Cannot update a system app with an ephemeral app");
15977                return;
15978            }
15979        }
15980
15981        if (args.move != null) {
15982            // We did an in-place move, so dex is ready to roll
15983            scanFlags |= SCAN_NO_DEX;
15984            scanFlags |= SCAN_MOVE;
15985
15986            synchronized (mPackages) {
15987                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15988                if (ps == null) {
15989                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15990                            "Missing settings for moved package " + pkgName);
15991                }
15992
15993                // We moved the entire application as-is, so bring over the
15994                // previously derived ABI information.
15995                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15996                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15997            }
15998
15999        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16000            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16001            scanFlags |= SCAN_NO_DEX;
16002
16003            try {
16004                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16005                    args.abiOverride : pkg.cpuAbiOverride);
16006                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16007                        true /*extractLibs*/, mAppLib32InstallDir);
16008            } catch (PackageManagerException pme) {
16009                Slog.e(TAG, "Error deriving application ABI", pme);
16010                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16011                return;
16012            }
16013
16014            // Shared libraries for the package need to be updated.
16015            synchronized (mPackages) {
16016                try {
16017                    updateSharedLibrariesLPr(pkg, null);
16018                } catch (PackageManagerException e) {
16019                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
16020                }
16021            }
16022            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16023            // Do not run PackageDexOptimizer through the local performDexOpt
16024            // method because `pkg` may not be in `mPackages` yet.
16025            //
16026            // Also, don't fail application installs if the dexopt step fails.
16027            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16028                    null /* instructionSets */, false /* checkProfiles */,
16029                    getCompilerFilterForReason(REASON_INSTALL),
16030                    getOrCreateCompilerPackageStats(pkg));
16031            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16032
16033            // Notify BackgroundDexOptService that the package has been changed.
16034            // If this is an update of a package which used to fail to compile,
16035            // BDOS will remove it from its blacklist.
16036            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16037        }
16038
16039        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16040            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16041            return;
16042        }
16043
16044        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16045
16046        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16047                "installPackageLI")) {
16048            if (replace) {
16049                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16050                        installerPackageName, res, args.installReason);
16051            } else {
16052                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16053                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16054            }
16055        }
16056        synchronized (mPackages) {
16057            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16058            if (ps != null) {
16059                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16060            }
16061
16062            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16063            for (int i = 0; i < childCount; i++) {
16064                PackageParser.Package childPkg = pkg.childPackages.get(i);
16065                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16066                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16067                if (childPs != null) {
16068                    childRes.newUsers = childPs.queryInstalledUsers(
16069                            sUserManager.getUserIds(), true);
16070                }
16071            }
16072        }
16073    }
16074
16075    private void startIntentFilterVerifications(int userId, boolean replacing,
16076            PackageParser.Package pkg) {
16077        if (mIntentFilterVerifierComponent == null) {
16078            Slog.w(TAG, "No IntentFilter verification will not be done as "
16079                    + "there is no IntentFilterVerifier available!");
16080            return;
16081        }
16082
16083        final int verifierUid = getPackageUid(
16084                mIntentFilterVerifierComponent.getPackageName(),
16085                MATCH_DEBUG_TRIAGED_MISSING,
16086                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16087
16088        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16089        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16090        mHandler.sendMessage(msg);
16091
16092        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16093        for (int i = 0; i < childCount; i++) {
16094            PackageParser.Package childPkg = pkg.childPackages.get(i);
16095            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16096            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16097            mHandler.sendMessage(msg);
16098        }
16099    }
16100
16101    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16102            PackageParser.Package pkg) {
16103        int size = pkg.activities.size();
16104        if (size == 0) {
16105            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16106                    "No activity, so no need to verify any IntentFilter!");
16107            return;
16108        }
16109
16110        final boolean hasDomainURLs = hasDomainURLs(pkg);
16111        if (!hasDomainURLs) {
16112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16113                    "No domain URLs, so no need to verify any IntentFilter!");
16114            return;
16115        }
16116
16117        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16118                + " if any IntentFilter from the " + size
16119                + " Activities needs verification ...");
16120
16121        int count = 0;
16122        final String packageName = pkg.packageName;
16123
16124        synchronized (mPackages) {
16125            // If this is a new install and we see that we've already run verification for this
16126            // package, we have nothing to do: it means the state was restored from backup.
16127            if (!replacing) {
16128                IntentFilterVerificationInfo ivi =
16129                        mSettings.getIntentFilterVerificationLPr(packageName);
16130                if (ivi != null) {
16131                    if (DEBUG_DOMAIN_VERIFICATION) {
16132                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16133                                + ivi.getStatusString());
16134                    }
16135                    return;
16136                }
16137            }
16138
16139            // If any filters need to be verified, then all need to be.
16140            boolean needToVerify = false;
16141            for (PackageParser.Activity a : pkg.activities) {
16142                for (ActivityIntentInfo filter : a.intents) {
16143                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16144                        if (DEBUG_DOMAIN_VERIFICATION) {
16145                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16146                        }
16147                        needToVerify = true;
16148                        break;
16149                    }
16150                }
16151            }
16152
16153            if (needToVerify) {
16154                final int verificationId = mIntentFilterVerificationToken++;
16155                for (PackageParser.Activity a : pkg.activities) {
16156                    for (ActivityIntentInfo filter : a.intents) {
16157                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16158                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16159                                    "Verification needed for IntentFilter:" + filter.toString());
16160                            mIntentFilterVerifier.addOneIntentFilterVerification(
16161                                    verifierUid, userId, verificationId, filter, packageName);
16162                            count++;
16163                        }
16164                    }
16165                }
16166            }
16167        }
16168
16169        if (count > 0) {
16170            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16171                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16172                    +  " for userId:" + userId);
16173            mIntentFilterVerifier.startVerifications(userId);
16174        } else {
16175            if (DEBUG_DOMAIN_VERIFICATION) {
16176                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16177            }
16178        }
16179    }
16180
16181    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16182        final ComponentName cn  = filter.activity.getComponentName();
16183        final String packageName = cn.getPackageName();
16184
16185        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16186                packageName);
16187        if (ivi == null) {
16188            return true;
16189        }
16190        int status = ivi.getStatus();
16191        switch (status) {
16192            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16193            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16194                return true;
16195
16196            default:
16197                // Nothing to do
16198                return false;
16199        }
16200    }
16201
16202    private static boolean isMultiArch(ApplicationInfo info) {
16203        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16204    }
16205
16206    private static boolean isExternal(PackageParser.Package pkg) {
16207        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16208    }
16209
16210    private static boolean isExternal(PackageSetting ps) {
16211        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16212    }
16213
16214    private static boolean isEphemeral(PackageParser.Package pkg) {
16215        return pkg.applicationInfo.isEphemeralApp();
16216    }
16217
16218    private static boolean isEphemeral(PackageSetting ps) {
16219        return ps.pkg != null && isEphemeral(ps.pkg);
16220    }
16221
16222    private static boolean isSystemApp(PackageParser.Package pkg) {
16223        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16224    }
16225
16226    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16227        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16228    }
16229
16230    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16231        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16232    }
16233
16234    private static boolean isSystemApp(PackageSetting ps) {
16235        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16236    }
16237
16238    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16239        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16240    }
16241
16242    private int packageFlagsToInstallFlags(PackageSetting ps) {
16243        int installFlags = 0;
16244        if (isEphemeral(ps)) {
16245            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16246        }
16247        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16248            // This existing package was an external ASEC install when we have
16249            // the external flag without a UUID
16250            installFlags |= PackageManager.INSTALL_EXTERNAL;
16251        }
16252        if (ps.isForwardLocked()) {
16253            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16254        }
16255        return installFlags;
16256    }
16257
16258    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16259        if (isExternal(pkg)) {
16260            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16261                return StorageManager.UUID_PRIMARY_PHYSICAL;
16262            } else {
16263                return pkg.volumeUuid;
16264            }
16265        } else {
16266            return StorageManager.UUID_PRIVATE_INTERNAL;
16267        }
16268    }
16269
16270    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16271        if (isExternal(pkg)) {
16272            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16273                return mSettings.getExternalVersion();
16274            } else {
16275                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16276            }
16277        } else {
16278            return mSettings.getInternalVersion();
16279        }
16280    }
16281
16282    private void deleteTempPackageFiles() {
16283        final FilenameFilter filter = new FilenameFilter() {
16284            public boolean accept(File dir, String name) {
16285                return name.startsWith("vmdl") && name.endsWith(".tmp");
16286            }
16287        };
16288        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16289            file.delete();
16290        }
16291    }
16292
16293    @Override
16294    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16295            int flags) {
16296        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16297                flags);
16298    }
16299
16300    @Override
16301    public void deletePackage(final String packageName,
16302            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16303        mContext.enforceCallingOrSelfPermission(
16304                android.Manifest.permission.DELETE_PACKAGES, null);
16305        Preconditions.checkNotNull(packageName);
16306        Preconditions.checkNotNull(observer);
16307        final int uid = Binder.getCallingUid();
16308        if (!isOrphaned(packageName)
16309                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16310            try {
16311                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16312                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16313                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16314                observer.onUserActionRequired(intent);
16315            } catch (RemoteException re) {
16316            }
16317            return;
16318        }
16319        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16320        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16321        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16322            mContext.enforceCallingOrSelfPermission(
16323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16324                    "deletePackage for user " + userId);
16325        }
16326
16327        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16328            try {
16329                observer.onPackageDeleted(packageName,
16330                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16331            } catch (RemoteException re) {
16332            }
16333            return;
16334        }
16335
16336        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16337            try {
16338                observer.onPackageDeleted(packageName,
16339                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16340            } catch (RemoteException re) {
16341            }
16342            return;
16343        }
16344
16345        if (DEBUG_REMOVE) {
16346            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16347                    + " deleteAllUsers: " + deleteAllUsers );
16348        }
16349        // Queue up an async operation since the package deletion may take a little while.
16350        mHandler.post(new Runnable() {
16351            public void run() {
16352                mHandler.removeCallbacks(this);
16353                int returnCode;
16354                if (!deleteAllUsers) {
16355                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16356                } else {
16357                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16358                    // If nobody is blocking uninstall, proceed with delete for all users
16359                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16360                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16361                    } else {
16362                        // Otherwise uninstall individually for users with blockUninstalls=false
16363                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16364                        for (int userId : users) {
16365                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16366                                returnCode = deletePackageX(packageName, userId, userFlags);
16367                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16368                                    Slog.w(TAG, "Package delete failed for user " + userId
16369                                            + ", returnCode " + returnCode);
16370                                }
16371                            }
16372                        }
16373                        // The app has only been marked uninstalled for certain users.
16374                        // We still need to report that delete was blocked
16375                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16376                    }
16377                }
16378                try {
16379                    observer.onPackageDeleted(packageName, returnCode, null);
16380                } catch (RemoteException e) {
16381                    Log.i(TAG, "Observer no longer exists.");
16382                } //end catch
16383            } //end run
16384        });
16385    }
16386
16387    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16388        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16389              || callingUid == Process.SYSTEM_UID) {
16390            return true;
16391        }
16392        final int callingUserId = UserHandle.getUserId(callingUid);
16393        // If the caller installed the pkgName, then allow it to silently uninstall.
16394        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16395            return true;
16396        }
16397
16398        // Allow package verifier to silently uninstall.
16399        if (mRequiredVerifierPackage != null &&
16400                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16401            return true;
16402        }
16403
16404        // Allow package uninstaller to silently uninstall.
16405        if (mRequiredUninstallerPackage != null &&
16406                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16407            return true;
16408        }
16409
16410        // Allow storage manager to silently uninstall.
16411        if (mStorageManagerPackage != null &&
16412                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16413            return true;
16414        }
16415        return false;
16416    }
16417
16418    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16419        int[] result = EMPTY_INT_ARRAY;
16420        for (int userId : userIds) {
16421            if (getBlockUninstallForUser(packageName, userId)) {
16422                result = ArrayUtils.appendInt(result, userId);
16423            }
16424        }
16425        return result;
16426    }
16427
16428    @Override
16429    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16430        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16431    }
16432
16433    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16434        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16435                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16436        try {
16437            if (dpm != null) {
16438                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16439                        /* callingUserOnly =*/ false);
16440                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16441                        : deviceOwnerComponentName.getPackageName();
16442                // Does the package contains the device owner?
16443                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16444                // this check is probably not needed, since DO should be registered as a device
16445                // admin on some user too. (Original bug for this: b/17657954)
16446                if (packageName.equals(deviceOwnerPackageName)) {
16447                    return true;
16448                }
16449                // Does it contain a device admin for any user?
16450                int[] users;
16451                if (userId == UserHandle.USER_ALL) {
16452                    users = sUserManager.getUserIds();
16453                } else {
16454                    users = new int[]{userId};
16455                }
16456                for (int i = 0; i < users.length; ++i) {
16457                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16458                        return true;
16459                    }
16460                }
16461            }
16462        } catch (RemoteException e) {
16463        }
16464        return false;
16465    }
16466
16467    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16468        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16469    }
16470
16471    /**
16472     *  This method is an internal method that could be get invoked either
16473     *  to delete an installed package or to clean up a failed installation.
16474     *  After deleting an installed package, a broadcast is sent to notify any
16475     *  listeners that the package has been removed. For cleaning up a failed
16476     *  installation, the broadcast is not necessary since the package's
16477     *  installation wouldn't have sent the initial broadcast either
16478     *  The key steps in deleting a package are
16479     *  deleting the package information in internal structures like mPackages,
16480     *  deleting the packages base directories through installd
16481     *  updating mSettings to reflect current status
16482     *  persisting settings for later use
16483     *  sending a broadcast if necessary
16484     */
16485    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16486        final PackageRemovedInfo info = new PackageRemovedInfo();
16487        final boolean res;
16488
16489        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16490                ? UserHandle.USER_ALL : userId;
16491
16492        if (isPackageDeviceAdmin(packageName, removeUser)) {
16493            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16494            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16495        }
16496
16497        PackageSetting uninstalledPs = null;
16498
16499        // for the uninstall-updates case and restricted profiles, remember the per-
16500        // user handle installed state
16501        int[] allUsers;
16502        synchronized (mPackages) {
16503            uninstalledPs = mSettings.mPackages.get(packageName);
16504            if (uninstalledPs == null) {
16505                Slog.w(TAG, "Not removing non-existent package " + packageName);
16506                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16507            }
16508            allUsers = sUserManager.getUserIds();
16509            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16510        }
16511
16512        final int freezeUser;
16513        if (isUpdatedSystemApp(uninstalledPs)
16514                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16515            // We're downgrading a system app, which will apply to all users, so
16516            // freeze them all during the downgrade
16517            freezeUser = UserHandle.USER_ALL;
16518        } else {
16519            freezeUser = removeUser;
16520        }
16521
16522        synchronized (mInstallLock) {
16523            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16524            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16525                    deleteFlags, "deletePackageX")) {
16526                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16527                        deleteFlags | REMOVE_CHATTY, info, true, null);
16528            }
16529            synchronized (mPackages) {
16530                if (res) {
16531                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16532                }
16533            }
16534        }
16535
16536        if (res) {
16537            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16538            info.sendPackageRemovedBroadcasts(killApp);
16539            info.sendSystemPackageUpdatedBroadcasts();
16540            info.sendSystemPackageAppearedBroadcasts();
16541        }
16542        // Force a gc here.
16543        Runtime.getRuntime().gc();
16544        // Delete the resources here after sending the broadcast to let
16545        // other processes clean up before deleting resources.
16546        if (info.args != null) {
16547            synchronized (mInstallLock) {
16548                info.args.doPostDeleteLI(true);
16549            }
16550        }
16551
16552        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16553    }
16554
16555    class PackageRemovedInfo {
16556        String removedPackage;
16557        int uid = -1;
16558        int removedAppId = -1;
16559        int[] origUsers;
16560        int[] removedUsers = null;
16561        SparseArray<Integer> installReasons;
16562        boolean isRemovedPackageSystemUpdate = false;
16563        boolean isUpdate;
16564        boolean dataRemoved;
16565        boolean removedForAllUsers;
16566        // Clean up resources deleted packages.
16567        InstallArgs args = null;
16568        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16569        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16570
16571        void sendPackageRemovedBroadcasts(boolean killApp) {
16572            sendPackageRemovedBroadcastInternal(killApp);
16573            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16574            for (int i = 0; i < childCount; i++) {
16575                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16576                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16577            }
16578        }
16579
16580        void sendSystemPackageUpdatedBroadcasts() {
16581            if (isRemovedPackageSystemUpdate) {
16582                sendSystemPackageUpdatedBroadcastsInternal();
16583                final int childCount = (removedChildPackages != null)
16584                        ? removedChildPackages.size() : 0;
16585                for (int i = 0; i < childCount; i++) {
16586                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16587                    if (childInfo.isRemovedPackageSystemUpdate) {
16588                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16589                    }
16590                }
16591            }
16592        }
16593
16594        void sendSystemPackageAppearedBroadcasts() {
16595            final int packageCount = (appearedChildPackages != null)
16596                    ? appearedChildPackages.size() : 0;
16597            for (int i = 0; i < packageCount; i++) {
16598                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16599                sendPackageAddedForNewUsers(installedInfo.name, true,
16600                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16601            }
16602        }
16603
16604        private void sendSystemPackageUpdatedBroadcastsInternal() {
16605            Bundle extras = new Bundle(2);
16606            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16607            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16608            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16609                    extras, 0, null, null, null);
16610            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16611                    extras, 0, null, null, null);
16612            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16613                    null, 0, removedPackage, null, null);
16614        }
16615
16616        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16617            Bundle extras = new Bundle(2);
16618            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16619            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16620            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16621            if (isUpdate || isRemovedPackageSystemUpdate) {
16622                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16623            }
16624            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16625            if (removedPackage != null) {
16626                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16627                        extras, 0, null, null, removedUsers);
16628                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16629                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16630                            removedPackage, extras, 0, null, null, removedUsers);
16631                }
16632            }
16633            if (removedAppId >= 0) {
16634                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16635                        removedUsers);
16636            }
16637        }
16638    }
16639
16640    /*
16641     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16642     * flag is not set, the data directory is removed as well.
16643     * make sure this flag is set for partially installed apps. If not its meaningless to
16644     * delete a partially installed application.
16645     */
16646    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16647            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16648        String packageName = ps.name;
16649        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16650        // Retrieve object to delete permissions for shared user later on
16651        final PackageParser.Package deletedPkg;
16652        final PackageSetting deletedPs;
16653        // reader
16654        synchronized (mPackages) {
16655            deletedPkg = mPackages.get(packageName);
16656            deletedPs = mSettings.mPackages.get(packageName);
16657            if (outInfo != null) {
16658                outInfo.removedPackage = packageName;
16659                outInfo.removedUsers = deletedPs != null
16660                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16661                        : null;
16662            }
16663        }
16664
16665        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16666
16667        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16668            final PackageParser.Package resolvedPkg;
16669            if (deletedPkg != null) {
16670                resolvedPkg = deletedPkg;
16671            } else {
16672                // We don't have a parsed package when it lives on an ejected
16673                // adopted storage device, so fake something together
16674                resolvedPkg = new PackageParser.Package(ps.name);
16675                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16676            }
16677            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16678                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16679            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16680            if (outInfo != null) {
16681                outInfo.dataRemoved = true;
16682            }
16683            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16684        }
16685
16686        // writer
16687        synchronized (mPackages) {
16688            if (deletedPs != null) {
16689                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16690                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16691                    clearDefaultBrowserIfNeeded(packageName);
16692                    if (outInfo != null) {
16693                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16694                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16695                    }
16696                    updatePermissionsLPw(deletedPs.name, null, 0);
16697                    if (deletedPs.sharedUser != null) {
16698                        // Remove permissions associated with package. Since runtime
16699                        // permissions are per user we have to kill the removed package
16700                        // or packages running under the shared user of the removed
16701                        // package if revoking the permissions requested only by the removed
16702                        // package is successful and this causes a change in gids.
16703                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16704                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16705                                    userId);
16706                            if (userIdToKill == UserHandle.USER_ALL
16707                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16708                                // If gids changed for this user, kill all affected packages.
16709                                mHandler.post(new Runnable() {
16710                                    @Override
16711                                    public void run() {
16712                                        // This has to happen with no lock held.
16713                                        killApplication(deletedPs.name, deletedPs.appId,
16714                                                KILL_APP_REASON_GIDS_CHANGED);
16715                                    }
16716                                });
16717                                break;
16718                            }
16719                        }
16720                    }
16721                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16722                }
16723                // make sure to preserve per-user disabled state if this removal was just
16724                // a downgrade of a system app to the factory package
16725                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16726                    if (DEBUG_REMOVE) {
16727                        Slog.d(TAG, "Propagating install state across downgrade");
16728                    }
16729                    for (int userId : allUserHandles) {
16730                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16731                        if (DEBUG_REMOVE) {
16732                            Slog.d(TAG, "    user " + userId + " => " + installed);
16733                        }
16734                        ps.setInstalled(installed, userId);
16735                    }
16736                }
16737            }
16738            // can downgrade to reader
16739            if (writeSettings) {
16740                // Save settings now
16741                mSettings.writeLPr();
16742            }
16743        }
16744        if (outInfo != null) {
16745            // A user ID was deleted here. Go through all users and remove it
16746            // from KeyStore.
16747            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16748        }
16749    }
16750
16751    static boolean locationIsPrivileged(File path) {
16752        try {
16753            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16754                    .getCanonicalPath();
16755            return path.getCanonicalPath().startsWith(privilegedAppDir);
16756        } catch (IOException e) {
16757            Slog.e(TAG, "Unable to access code path " + path);
16758        }
16759        return false;
16760    }
16761
16762    /*
16763     * Tries to delete system package.
16764     */
16765    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16766            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16767            boolean writeSettings) {
16768        if (deletedPs.parentPackageName != null) {
16769            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16770            return false;
16771        }
16772
16773        final boolean applyUserRestrictions
16774                = (allUserHandles != null) && (outInfo.origUsers != null);
16775        final PackageSetting disabledPs;
16776        // Confirm if the system package has been updated
16777        // An updated system app can be deleted. This will also have to restore
16778        // the system pkg from system partition
16779        // reader
16780        synchronized (mPackages) {
16781            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16782        }
16783
16784        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16785                + " disabledPs=" + disabledPs);
16786
16787        if (disabledPs == null) {
16788            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16789            return false;
16790        } else if (DEBUG_REMOVE) {
16791            Slog.d(TAG, "Deleting system pkg from data partition");
16792        }
16793
16794        if (DEBUG_REMOVE) {
16795            if (applyUserRestrictions) {
16796                Slog.d(TAG, "Remembering install states:");
16797                for (int userId : allUserHandles) {
16798                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16799                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16800                }
16801            }
16802        }
16803
16804        // Delete the updated package
16805        outInfo.isRemovedPackageSystemUpdate = true;
16806        if (outInfo.removedChildPackages != null) {
16807            final int childCount = (deletedPs.childPackageNames != null)
16808                    ? deletedPs.childPackageNames.size() : 0;
16809            for (int i = 0; i < childCount; i++) {
16810                String childPackageName = deletedPs.childPackageNames.get(i);
16811                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16812                        .contains(childPackageName)) {
16813                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16814                            childPackageName);
16815                    if (childInfo != null) {
16816                        childInfo.isRemovedPackageSystemUpdate = true;
16817                    }
16818                }
16819            }
16820        }
16821
16822        if (disabledPs.versionCode < deletedPs.versionCode) {
16823            // Delete data for downgrades
16824            flags &= ~PackageManager.DELETE_KEEP_DATA;
16825        } else {
16826            // Preserve data by setting flag
16827            flags |= PackageManager.DELETE_KEEP_DATA;
16828        }
16829
16830        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16831                outInfo, writeSettings, disabledPs.pkg);
16832        if (!ret) {
16833            return false;
16834        }
16835
16836        // writer
16837        synchronized (mPackages) {
16838            // Reinstate the old system package
16839            enableSystemPackageLPw(disabledPs.pkg);
16840            // Remove any native libraries from the upgraded package.
16841            removeNativeBinariesLI(deletedPs);
16842        }
16843
16844        // Install the system package
16845        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16846        int parseFlags = mDefParseFlags
16847                | PackageParser.PARSE_MUST_BE_APK
16848                | PackageParser.PARSE_IS_SYSTEM
16849                | PackageParser.PARSE_IS_SYSTEM_DIR;
16850        if (locationIsPrivileged(disabledPs.codePath)) {
16851            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16852        }
16853
16854        final PackageParser.Package newPkg;
16855        try {
16856            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16857                0 /* currentTime */, null);
16858        } catch (PackageManagerException e) {
16859            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16860                    + e.getMessage());
16861            return false;
16862        }
16863        try {
16864            // update shared libraries for the newly re-installed system package
16865            updateSharedLibrariesLPr(newPkg, null);
16866        } catch (PackageManagerException e) {
16867            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16868        }
16869
16870        prepareAppDataAfterInstallLIF(newPkg);
16871
16872        // writer
16873        synchronized (mPackages) {
16874            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16875
16876            // Propagate the permissions state as we do not want to drop on the floor
16877            // runtime permissions. The update permissions method below will take
16878            // care of removing obsolete permissions and grant install permissions.
16879            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16880            updatePermissionsLPw(newPkg.packageName, newPkg,
16881                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16882
16883            if (applyUserRestrictions) {
16884                if (DEBUG_REMOVE) {
16885                    Slog.d(TAG, "Propagating install state across reinstall");
16886                }
16887                for (int userId : allUserHandles) {
16888                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16889                    if (DEBUG_REMOVE) {
16890                        Slog.d(TAG, "    user " + userId + " => " + installed);
16891                    }
16892                    ps.setInstalled(installed, userId);
16893
16894                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16895                }
16896                // Regardless of writeSettings we need to ensure that this restriction
16897                // state propagation is persisted
16898                mSettings.writeAllUsersPackageRestrictionsLPr();
16899            }
16900            // can downgrade to reader here
16901            if (writeSettings) {
16902                mSettings.writeLPr();
16903            }
16904        }
16905        return true;
16906    }
16907
16908    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16909            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16910            PackageRemovedInfo outInfo, boolean writeSettings,
16911            PackageParser.Package replacingPackage) {
16912        synchronized (mPackages) {
16913            if (outInfo != null) {
16914                outInfo.uid = ps.appId;
16915            }
16916
16917            if (outInfo != null && outInfo.removedChildPackages != null) {
16918                final int childCount = (ps.childPackageNames != null)
16919                        ? ps.childPackageNames.size() : 0;
16920                for (int i = 0; i < childCount; i++) {
16921                    String childPackageName = ps.childPackageNames.get(i);
16922                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16923                    if (childPs == null) {
16924                        return false;
16925                    }
16926                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16927                            childPackageName);
16928                    if (childInfo != null) {
16929                        childInfo.uid = childPs.appId;
16930                    }
16931                }
16932            }
16933        }
16934
16935        // Delete package data from internal structures and also remove data if flag is set
16936        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16937
16938        // Delete the child packages data
16939        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16940        for (int i = 0; i < childCount; i++) {
16941            PackageSetting childPs;
16942            synchronized (mPackages) {
16943                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16944            }
16945            if (childPs != null) {
16946                PackageRemovedInfo childOutInfo = (outInfo != null
16947                        && outInfo.removedChildPackages != null)
16948                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16949                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16950                        && (replacingPackage != null
16951                        && !replacingPackage.hasChildPackage(childPs.name))
16952                        ? flags & ~DELETE_KEEP_DATA : flags;
16953                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16954                        deleteFlags, writeSettings);
16955            }
16956        }
16957
16958        // Delete application code and resources only for parent packages
16959        if (ps.parentPackageName == null) {
16960            if (deleteCodeAndResources && (outInfo != null)) {
16961                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16962                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16963                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16964            }
16965        }
16966
16967        return true;
16968    }
16969
16970    @Override
16971    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16972            int userId) {
16973        mContext.enforceCallingOrSelfPermission(
16974                android.Manifest.permission.DELETE_PACKAGES, null);
16975        synchronized (mPackages) {
16976            PackageSetting ps = mSettings.mPackages.get(packageName);
16977            if (ps == null) {
16978                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16979                return false;
16980            }
16981            if (!ps.getInstalled(userId)) {
16982                // Can't block uninstall for an app that is not installed or enabled.
16983                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16984                return false;
16985            }
16986            ps.setBlockUninstall(blockUninstall, userId);
16987            mSettings.writePackageRestrictionsLPr(userId);
16988        }
16989        return true;
16990    }
16991
16992    @Override
16993    public boolean getBlockUninstallForUser(String packageName, int userId) {
16994        synchronized (mPackages) {
16995            PackageSetting ps = mSettings.mPackages.get(packageName);
16996            if (ps == null) {
16997                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16998                return false;
16999            }
17000            return ps.getBlockUninstall(userId);
17001        }
17002    }
17003
17004    @Override
17005    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17006        int callingUid = Binder.getCallingUid();
17007        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17008            throw new SecurityException(
17009                    "setRequiredForSystemUser can only be run by the system or root");
17010        }
17011        synchronized (mPackages) {
17012            PackageSetting ps = mSettings.mPackages.get(packageName);
17013            if (ps == null) {
17014                Log.w(TAG, "Package doesn't exist: " + packageName);
17015                return false;
17016            }
17017            if (systemUserApp) {
17018                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17019            } else {
17020                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17021            }
17022            mSettings.writeLPr();
17023        }
17024        return true;
17025    }
17026
17027    /*
17028     * This method handles package deletion in general
17029     */
17030    private boolean deletePackageLIF(String packageName, UserHandle user,
17031            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17032            PackageRemovedInfo outInfo, boolean writeSettings,
17033            PackageParser.Package replacingPackage) {
17034        if (packageName == null) {
17035            Slog.w(TAG, "Attempt to delete null packageName.");
17036            return false;
17037        }
17038
17039        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17040
17041        PackageSetting ps;
17042
17043        synchronized (mPackages) {
17044            ps = mSettings.mPackages.get(packageName);
17045            if (ps == null) {
17046                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17047                return false;
17048            }
17049
17050            if (ps.parentPackageName != null && (!isSystemApp(ps)
17051                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17052                if (DEBUG_REMOVE) {
17053                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17054                            + ((user == null) ? UserHandle.USER_ALL : user));
17055                }
17056                final int removedUserId = (user != null) ? user.getIdentifier()
17057                        : UserHandle.USER_ALL;
17058                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17059                    return false;
17060                }
17061                markPackageUninstalledForUserLPw(ps, user);
17062                scheduleWritePackageRestrictionsLocked(user);
17063                return true;
17064            }
17065        }
17066
17067        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17068                && user.getIdentifier() != UserHandle.USER_ALL)) {
17069            // The caller is asking that the package only be deleted for a single
17070            // user.  To do this, we just mark its uninstalled state and delete
17071            // its data. If this is a system app, we only allow this to happen if
17072            // they have set the special DELETE_SYSTEM_APP which requests different
17073            // semantics than normal for uninstalling system apps.
17074            markPackageUninstalledForUserLPw(ps, user);
17075
17076            if (!isSystemApp(ps)) {
17077                // Do not uninstall the APK if an app should be cached
17078                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17079                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17080                    // Other user still have this package installed, so all
17081                    // we need to do is clear this user's data and save that
17082                    // it is uninstalled.
17083                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17084                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17085                        return false;
17086                    }
17087                    scheduleWritePackageRestrictionsLocked(user);
17088                    return true;
17089                } else {
17090                    // We need to set it back to 'installed' so the uninstall
17091                    // broadcasts will be sent correctly.
17092                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17093                    ps.setInstalled(true, user.getIdentifier());
17094                }
17095            } else {
17096                // This is a system app, so we assume that the
17097                // other users still have this package installed, so all
17098                // we need to do is clear this user's data and save that
17099                // it is uninstalled.
17100                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17101                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17102                    return false;
17103                }
17104                scheduleWritePackageRestrictionsLocked(user);
17105                return true;
17106            }
17107        }
17108
17109        // If we are deleting a composite package for all users, keep track
17110        // of result for each child.
17111        if (ps.childPackageNames != null && outInfo != null) {
17112            synchronized (mPackages) {
17113                final int childCount = ps.childPackageNames.size();
17114                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17115                for (int i = 0; i < childCount; i++) {
17116                    String childPackageName = ps.childPackageNames.get(i);
17117                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17118                    childInfo.removedPackage = childPackageName;
17119                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17120                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17121                    if (childPs != null) {
17122                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17123                    }
17124                }
17125            }
17126        }
17127
17128        boolean ret = false;
17129        if (isSystemApp(ps)) {
17130            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17131            // When an updated system application is deleted we delete the existing resources
17132            // as well and fall back to existing code in system partition
17133            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17134        } else {
17135            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17136            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17137                    outInfo, writeSettings, replacingPackage);
17138        }
17139
17140        // Take a note whether we deleted the package for all users
17141        if (outInfo != null) {
17142            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17143            if (outInfo.removedChildPackages != null) {
17144                synchronized (mPackages) {
17145                    final int childCount = outInfo.removedChildPackages.size();
17146                    for (int i = 0; i < childCount; i++) {
17147                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17148                        if (childInfo != null) {
17149                            childInfo.removedForAllUsers = mPackages.get(
17150                                    childInfo.removedPackage) == null;
17151                        }
17152                    }
17153                }
17154            }
17155            // If we uninstalled an update to a system app there may be some
17156            // child packages that appeared as they are declared in the system
17157            // app but were not declared in the update.
17158            if (isSystemApp(ps)) {
17159                synchronized (mPackages) {
17160                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17161                    final int childCount = (updatedPs.childPackageNames != null)
17162                            ? updatedPs.childPackageNames.size() : 0;
17163                    for (int i = 0; i < childCount; i++) {
17164                        String childPackageName = updatedPs.childPackageNames.get(i);
17165                        if (outInfo.removedChildPackages == null
17166                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17167                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17168                            if (childPs == null) {
17169                                continue;
17170                            }
17171                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17172                            installRes.name = childPackageName;
17173                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17174                            installRes.pkg = mPackages.get(childPackageName);
17175                            installRes.uid = childPs.pkg.applicationInfo.uid;
17176                            if (outInfo.appearedChildPackages == null) {
17177                                outInfo.appearedChildPackages = new ArrayMap<>();
17178                            }
17179                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17180                        }
17181                    }
17182                }
17183            }
17184        }
17185
17186        return ret;
17187    }
17188
17189    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17190        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17191                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17192        for (int nextUserId : userIds) {
17193            if (DEBUG_REMOVE) {
17194                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17195            }
17196            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17197                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
17198                    false /*hidden*/, false /*suspended*/, null, null, null,
17199                    false /*blockUninstall*/,
17200                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
17201                    PackageManager.INSTALL_REASON_UNKNOWN);
17202        }
17203    }
17204
17205    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17206            PackageRemovedInfo outInfo) {
17207        final PackageParser.Package pkg;
17208        synchronized (mPackages) {
17209            pkg = mPackages.get(ps.name);
17210        }
17211
17212        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17213                : new int[] {userId};
17214        for (int nextUserId : userIds) {
17215            if (DEBUG_REMOVE) {
17216                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17217                        + nextUserId);
17218            }
17219
17220            destroyAppDataLIF(pkg, userId,
17221                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17222            destroyAppProfilesLIF(pkg, userId);
17223            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17224            schedulePackageCleaning(ps.name, nextUserId, false);
17225            synchronized (mPackages) {
17226                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17227                    scheduleWritePackageRestrictionsLocked(nextUserId);
17228                }
17229                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17230            }
17231        }
17232
17233        if (outInfo != null) {
17234            outInfo.removedPackage = ps.name;
17235            outInfo.removedAppId = ps.appId;
17236            outInfo.removedUsers = userIds;
17237        }
17238
17239        return true;
17240    }
17241
17242    private final class ClearStorageConnection implements ServiceConnection {
17243        IMediaContainerService mContainerService;
17244
17245        @Override
17246        public void onServiceConnected(ComponentName name, IBinder service) {
17247            synchronized (this) {
17248                mContainerService = IMediaContainerService.Stub
17249                        .asInterface(Binder.allowBlocking(service));
17250                notifyAll();
17251            }
17252        }
17253
17254        @Override
17255        public void onServiceDisconnected(ComponentName name) {
17256        }
17257    }
17258
17259    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17260        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17261
17262        final boolean mounted;
17263        if (Environment.isExternalStorageEmulated()) {
17264            mounted = true;
17265        } else {
17266            final String status = Environment.getExternalStorageState();
17267
17268            mounted = status.equals(Environment.MEDIA_MOUNTED)
17269                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17270        }
17271
17272        if (!mounted) {
17273            return;
17274        }
17275
17276        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17277        int[] users;
17278        if (userId == UserHandle.USER_ALL) {
17279            users = sUserManager.getUserIds();
17280        } else {
17281            users = new int[] { userId };
17282        }
17283        final ClearStorageConnection conn = new ClearStorageConnection();
17284        if (mContext.bindServiceAsUser(
17285                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17286            try {
17287                for (int curUser : users) {
17288                    long timeout = SystemClock.uptimeMillis() + 5000;
17289                    synchronized (conn) {
17290                        long now;
17291                        while (conn.mContainerService == null &&
17292                                (now = SystemClock.uptimeMillis()) < timeout) {
17293                            try {
17294                                conn.wait(timeout - now);
17295                            } catch (InterruptedException e) {
17296                            }
17297                        }
17298                    }
17299                    if (conn.mContainerService == null) {
17300                        return;
17301                    }
17302
17303                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17304                    clearDirectory(conn.mContainerService,
17305                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17306                    if (allData) {
17307                        clearDirectory(conn.mContainerService,
17308                                userEnv.buildExternalStorageAppDataDirs(packageName));
17309                        clearDirectory(conn.mContainerService,
17310                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17311                    }
17312                }
17313            } finally {
17314                mContext.unbindService(conn);
17315            }
17316        }
17317    }
17318
17319    @Override
17320    public void clearApplicationProfileData(String packageName) {
17321        enforceSystemOrRoot("Only the system can clear all profile data");
17322
17323        final PackageParser.Package pkg;
17324        synchronized (mPackages) {
17325            pkg = mPackages.get(packageName);
17326        }
17327
17328        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17329            synchronized (mInstallLock) {
17330                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17331                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17332                        true /* removeBaseMarker */);
17333            }
17334        }
17335    }
17336
17337    @Override
17338    public void clearApplicationUserData(final String packageName,
17339            final IPackageDataObserver observer, final int userId) {
17340        mContext.enforceCallingOrSelfPermission(
17341                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17342
17343        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17344                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17345
17346        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17347            throw new SecurityException("Cannot clear data for a protected package: "
17348                    + packageName);
17349        }
17350        // Queue up an async operation since the package deletion may take a little while.
17351        mHandler.post(new Runnable() {
17352            public void run() {
17353                mHandler.removeCallbacks(this);
17354                final boolean succeeded;
17355                try (PackageFreezer freezer = freezePackage(packageName,
17356                        "clearApplicationUserData")) {
17357                    synchronized (mInstallLock) {
17358                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17359                    }
17360                    clearExternalStorageDataSync(packageName, userId, true);
17361                }
17362                if (succeeded) {
17363                    // invoke DeviceStorageMonitor's update method to clear any notifications
17364                    DeviceStorageMonitorInternal dsm = LocalServices
17365                            .getService(DeviceStorageMonitorInternal.class);
17366                    if (dsm != null) {
17367                        dsm.checkMemory();
17368                    }
17369                }
17370                if(observer != null) {
17371                    try {
17372                        observer.onRemoveCompleted(packageName, succeeded);
17373                    } catch (RemoteException e) {
17374                        Log.i(TAG, "Observer no longer exists.");
17375                    }
17376                } //end if observer
17377            } //end run
17378        });
17379    }
17380
17381    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17382        if (packageName == null) {
17383            Slog.w(TAG, "Attempt to delete null packageName.");
17384            return false;
17385        }
17386
17387        // Try finding details about the requested package
17388        PackageParser.Package pkg;
17389        synchronized (mPackages) {
17390            pkg = mPackages.get(packageName);
17391            if (pkg == null) {
17392                final PackageSetting ps = mSettings.mPackages.get(packageName);
17393                if (ps != null) {
17394                    pkg = ps.pkg;
17395                }
17396            }
17397
17398            if (pkg == null) {
17399                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17400                return false;
17401            }
17402
17403            PackageSetting ps = (PackageSetting) pkg.mExtras;
17404            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17405        }
17406
17407        clearAppDataLIF(pkg, userId,
17408                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17409
17410        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17411        removeKeystoreDataIfNeeded(userId, appId);
17412
17413        UserManagerInternal umInternal = getUserManagerInternal();
17414        final int flags;
17415        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17416            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17417        } else if (umInternal.isUserRunning(userId)) {
17418            flags = StorageManager.FLAG_STORAGE_DE;
17419        } else {
17420            flags = 0;
17421        }
17422        prepareAppDataContentsLIF(pkg, userId, flags);
17423
17424        return true;
17425    }
17426
17427    /**
17428     * Reverts user permission state changes (permissions and flags) in
17429     * all packages for a given user.
17430     *
17431     * @param userId The device user for which to do a reset.
17432     */
17433    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17434        final int packageCount = mPackages.size();
17435        for (int i = 0; i < packageCount; i++) {
17436            PackageParser.Package pkg = mPackages.valueAt(i);
17437            PackageSetting ps = (PackageSetting) pkg.mExtras;
17438            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17439        }
17440    }
17441
17442    private void resetNetworkPolicies(int userId) {
17443        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17444    }
17445
17446    /**
17447     * Reverts user permission state changes (permissions and flags).
17448     *
17449     * @param ps The package for which to reset.
17450     * @param userId The device user for which to do a reset.
17451     */
17452    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17453            final PackageSetting ps, final int userId) {
17454        if (ps.pkg == null) {
17455            return;
17456        }
17457
17458        // These are flags that can change base on user actions.
17459        final int userSettableMask = FLAG_PERMISSION_USER_SET
17460                | FLAG_PERMISSION_USER_FIXED
17461                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17462                | FLAG_PERMISSION_REVIEW_REQUIRED;
17463
17464        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17465                | FLAG_PERMISSION_POLICY_FIXED;
17466
17467        boolean writeInstallPermissions = false;
17468        boolean writeRuntimePermissions = false;
17469
17470        final int permissionCount = ps.pkg.requestedPermissions.size();
17471        for (int i = 0; i < permissionCount; i++) {
17472            String permission = ps.pkg.requestedPermissions.get(i);
17473
17474            BasePermission bp = mSettings.mPermissions.get(permission);
17475            if (bp == null) {
17476                continue;
17477            }
17478
17479            // If shared user we just reset the state to which only this app contributed.
17480            if (ps.sharedUser != null) {
17481                boolean used = false;
17482                final int packageCount = ps.sharedUser.packages.size();
17483                for (int j = 0; j < packageCount; j++) {
17484                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17485                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17486                            && pkg.pkg.requestedPermissions.contains(permission)) {
17487                        used = true;
17488                        break;
17489                    }
17490                }
17491                if (used) {
17492                    continue;
17493                }
17494            }
17495
17496            PermissionsState permissionsState = ps.getPermissionsState();
17497
17498            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17499
17500            // Always clear the user settable flags.
17501            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17502                    bp.name) != null;
17503            // If permission review is enabled and this is a legacy app, mark the
17504            // permission as requiring a review as this is the initial state.
17505            int flags = 0;
17506            if (mPermissionReviewRequired
17507                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17508                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17509            }
17510            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17511                if (hasInstallState) {
17512                    writeInstallPermissions = true;
17513                } else {
17514                    writeRuntimePermissions = true;
17515                }
17516            }
17517
17518            // Below is only runtime permission handling.
17519            if (!bp.isRuntime()) {
17520                continue;
17521            }
17522
17523            // Never clobber system or policy.
17524            if ((oldFlags & policyOrSystemFlags) != 0) {
17525                continue;
17526            }
17527
17528            // If this permission was granted by default, make sure it is.
17529            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17530                if (permissionsState.grantRuntimePermission(bp, userId)
17531                        != PERMISSION_OPERATION_FAILURE) {
17532                    writeRuntimePermissions = true;
17533                }
17534            // If permission review is enabled the permissions for a legacy apps
17535            // are represented as constantly granted runtime ones, so don't revoke.
17536            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17537                // Otherwise, reset the permission.
17538                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17539                switch (revokeResult) {
17540                    case PERMISSION_OPERATION_SUCCESS:
17541                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17542                        writeRuntimePermissions = true;
17543                        final int appId = ps.appId;
17544                        mHandler.post(new Runnable() {
17545                            @Override
17546                            public void run() {
17547                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17548                            }
17549                        });
17550                    } break;
17551                }
17552            }
17553        }
17554
17555        // Synchronously write as we are taking permissions away.
17556        if (writeRuntimePermissions) {
17557            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17558        }
17559
17560        // Synchronously write as we are taking permissions away.
17561        if (writeInstallPermissions) {
17562            mSettings.writeLPr();
17563        }
17564    }
17565
17566    /**
17567     * Remove entries from the keystore daemon. Will only remove it if the
17568     * {@code appId} is valid.
17569     */
17570    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17571        if (appId < 0) {
17572            return;
17573        }
17574
17575        final KeyStore keyStore = KeyStore.getInstance();
17576        if (keyStore != null) {
17577            if (userId == UserHandle.USER_ALL) {
17578                for (final int individual : sUserManager.getUserIds()) {
17579                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17580                }
17581            } else {
17582                keyStore.clearUid(UserHandle.getUid(userId, appId));
17583            }
17584        } else {
17585            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17586        }
17587    }
17588
17589    @Override
17590    public void deleteApplicationCacheFiles(final String packageName,
17591            final IPackageDataObserver observer) {
17592        final int userId = UserHandle.getCallingUserId();
17593        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17594    }
17595
17596    @Override
17597    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17598            final IPackageDataObserver observer) {
17599        mContext.enforceCallingOrSelfPermission(
17600                android.Manifest.permission.DELETE_CACHE_FILES, null);
17601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17602                /* requireFullPermission= */ true, /* checkShell= */ false,
17603                "delete application cache files");
17604
17605        final PackageParser.Package pkg;
17606        synchronized (mPackages) {
17607            pkg = mPackages.get(packageName);
17608        }
17609
17610        // Queue up an async operation since the package deletion may take a little while.
17611        mHandler.post(new Runnable() {
17612            public void run() {
17613                synchronized (mInstallLock) {
17614                    final int flags = StorageManager.FLAG_STORAGE_DE
17615                            | StorageManager.FLAG_STORAGE_CE;
17616                    // We're only clearing cache files, so we don't care if the
17617                    // app is unfrozen and still able to run
17618                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17619                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17620                }
17621                clearExternalStorageDataSync(packageName, userId, false);
17622                if (observer != null) {
17623                    try {
17624                        observer.onRemoveCompleted(packageName, true);
17625                    } catch (RemoteException e) {
17626                        Log.i(TAG, "Observer no longer exists.");
17627                    }
17628                }
17629            }
17630        });
17631    }
17632
17633    @Override
17634    public void getPackageSizeInfo(final String packageName, int userHandle,
17635            final IPackageStatsObserver observer) {
17636        mContext.enforceCallingOrSelfPermission(
17637                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17638        if (packageName == null) {
17639            throw new IllegalArgumentException("Attempt to get size of null packageName");
17640        }
17641
17642        PackageStats stats = new PackageStats(packageName, userHandle);
17643
17644        /*
17645         * Queue up an async operation since the package measurement may take a
17646         * little while.
17647         */
17648        Message msg = mHandler.obtainMessage(INIT_COPY);
17649        msg.obj = new MeasureParams(stats, observer);
17650        mHandler.sendMessage(msg);
17651    }
17652
17653    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17654        final PackageSetting ps;
17655        synchronized (mPackages) {
17656            ps = mSettings.mPackages.get(packageName);
17657            if (ps == null) {
17658                Slog.w(TAG, "Failed to find settings for " + packageName);
17659                return false;
17660            }
17661        }
17662
17663        final String[] packageNames = { packageName };
17664        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
17665        final String[] codePaths = { ps.codePathString };
17666
17667        try {
17668            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
17669                    ps.appId, ceDataInodes, codePaths, stats);
17670
17671            // For now, ignore code size of packages on system partition
17672            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17673                stats.codeSize = 0;
17674            }
17675
17676            // External clients expect these to be tracked separately
17677            stats.dataSize -= stats.cacheSize;
17678
17679        } catch (InstallerException e) {
17680            Slog.w(TAG, String.valueOf(e));
17681            return false;
17682        }
17683
17684        return true;
17685    }
17686
17687    private int getUidTargetSdkVersionLockedLPr(int uid) {
17688        Object obj = mSettings.getUserIdLPr(uid);
17689        if (obj instanceof SharedUserSetting) {
17690            final SharedUserSetting sus = (SharedUserSetting) obj;
17691            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17692            final Iterator<PackageSetting> it = sus.packages.iterator();
17693            while (it.hasNext()) {
17694                final PackageSetting ps = it.next();
17695                if (ps.pkg != null) {
17696                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17697                    if (v < vers) vers = v;
17698                }
17699            }
17700            return vers;
17701        } else if (obj instanceof PackageSetting) {
17702            final PackageSetting ps = (PackageSetting) obj;
17703            if (ps.pkg != null) {
17704                return ps.pkg.applicationInfo.targetSdkVersion;
17705            }
17706        }
17707        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17708    }
17709
17710    @Override
17711    public void addPreferredActivity(IntentFilter filter, int match,
17712            ComponentName[] set, ComponentName activity, int userId) {
17713        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17714                "Adding preferred");
17715    }
17716
17717    private void addPreferredActivityInternal(IntentFilter filter, int match,
17718            ComponentName[] set, ComponentName activity, boolean always, int userId,
17719            String opname) {
17720        // writer
17721        int callingUid = Binder.getCallingUid();
17722        enforceCrossUserPermission(callingUid, userId,
17723                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17724        if (filter.countActions() == 0) {
17725            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17726            return;
17727        }
17728        synchronized (mPackages) {
17729            if (mContext.checkCallingOrSelfPermission(
17730                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17731                    != PackageManager.PERMISSION_GRANTED) {
17732                if (getUidTargetSdkVersionLockedLPr(callingUid)
17733                        < Build.VERSION_CODES.FROYO) {
17734                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17735                            + callingUid);
17736                    return;
17737                }
17738                mContext.enforceCallingOrSelfPermission(
17739                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17740            }
17741
17742            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17743            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17744                    + userId + ":");
17745            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17746            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17747            scheduleWritePackageRestrictionsLocked(userId);
17748            postPreferredActivityChangedBroadcast(userId);
17749        }
17750    }
17751
17752    private void postPreferredActivityChangedBroadcast(int userId) {
17753        mHandler.post(() -> {
17754            final IActivityManager am = ActivityManager.getService();
17755            if (am == null) {
17756                return;
17757            }
17758
17759            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17760            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17761            try {
17762                am.broadcastIntent(null, intent, null, null,
17763                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17764                        null, false, false, userId);
17765            } catch (RemoteException e) {
17766            }
17767        });
17768    }
17769
17770    @Override
17771    public void replacePreferredActivity(IntentFilter filter, int match,
17772            ComponentName[] set, ComponentName activity, int userId) {
17773        if (filter.countActions() != 1) {
17774            throw new IllegalArgumentException(
17775                    "replacePreferredActivity expects filter to have only 1 action.");
17776        }
17777        if (filter.countDataAuthorities() != 0
17778                || filter.countDataPaths() != 0
17779                || filter.countDataSchemes() > 1
17780                || filter.countDataTypes() != 0) {
17781            throw new IllegalArgumentException(
17782                    "replacePreferredActivity expects filter to have no data authorities, " +
17783                    "paths, or types; and at most one scheme.");
17784        }
17785
17786        final int callingUid = Binder.getCallingUid();
17787        enforceCrossUserPermission(callingUid, userId,
17788                true /* requireFullPermission */, false /* checkShell */,
17789                "replace preferred activity");
17790        synchronized (mPackages) {
17791            if (mContext.checkCallingOrSelfPermission(
17792                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17793                    != PackageManager.PERMISSION_GRANTED) {
17794                if (getUidTargetSdkVersionLockedLPr(callingUid)
17795                        < Build.VERSION_CODES.FROYO) {
17796                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17797                            + Binder.getCallingUid());
17798                    return;
17799                }
17800                mContext.enforceCallingOrSelfPermission(
17801                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17802            }
17803
17804            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17805            if (pir != null) {
17806                // Get all of the existing entries that exactly match this filter.
17807                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17808                if (existing != null && existing.size() == 1) {
17809                    PreferredActivity cur = existing.get(0);
17810                    if (DEBUG_PREFERRED) {
17811                        Slog.i(TAG, "Checking replace of preferred:");
17812                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17813                        if (!cur.mPref.mAlways) {
17814                            Slog.i(TAG, "  -- CUR; not mAlways!");
17815                        } else {
17816                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17817                            Slog.i(TAG, "  -- CUR: mSet="
17818                                    + Arrays.toString(cur.mPref.mSetComponents));
17819                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17820                            Slog.i(TAG, "  -- NEW: mMatch="
17821                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17822                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17823                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17824                        }
17825                    }
17826                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17827                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17828                            && cur.mPref.sameSet(set)) {
17829                        // Setting the preferred activity to what it happens to be already
17830                        if (DEBUG_PREFERRED) {
17831                            Slog.i(TAG, "Replacing with same preferred activity "
17832                                    + cur.mPref.mShortComponent + " for user "
17833                                    + userId + ":");
17834                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17835                        }
17836                        return;
17837                    }
17838                }
17839
17840                if (existing != null) {
17841                    if (DEBUG_PREFERRED) {
17842                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17843                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17844                    }
17845                    for (int i = 0; i < existing.size(); i++) {
17846                        PreferredActivity pa = existing.get(i);
17847                        if (DEBUG_PREFERRED) {
17848                            Slog.i(TAG, "Removing existing preferred activity "
17849                                    + pa.mPref.mComponent + ":");
17850                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17851                        }
17852                        pir.removeFilter(pa);
17853                    }
17854                }
17855            }
17856            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17857                    "Replacing preferred");
17858        }
17859    }
17860
17861    @Override
17862    public void clearPackagePreferredActivities(String packageName) {
17863        final int uid = Binder.getCallingUid();
17864        // writer
17865        synchronized (mPackages) {
17866            PackageParser.Package pkg = mPackages.get(packageName);
17867            if (pkg == null || pkg.applicationInfo.uid != uid) {
17868                if (mContext.checkCallingOrSelfPermission(
17869                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17870                        != PackageManager.PERMISSION_GRANTED) {
17871                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17872                            < Build.VERSION_CODES.FROYO) {
17873                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17874                                + Binder.getCallingUid());
17875                        return;
17876                    }
17877                    mContext.enforceCallingOrSelfPermission(
17878                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17879                }
17880            }
17881
17882            int user = UserHandle.getCallingUserId();
17883            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17884                scheduleWritePackageRestrictionsLocked(user);
17885            }
17886        }
17887    }
17888
17889    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17890    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17891        ArrayList<PreferredActivity> removed = null;
17892        boolean changed = false;
17893        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17894            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17895            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17896            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17897                continue;
17898            }
17899            Iterator<PreferredActivity> it = pir.filterIterator();
17900            while (it.hasNext()) {
17901                PreferredActivity pa = it.next();
17902                // Mark entry for removal only if it matches the package name
17903                // and the entry is of type "always".
17904                if (packageName == null ||
17905                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17906                                && pa.mPref.mAlways)) {
17907                    if (removed == null) {
17908                        removed = new ArrayList<PreferredActivity>();
17909                    }
17910                    removed.add(pa);
17911                }
17912            }
17913            if (removed != null) {
17914                for (int j=0; j<removed.size(); j++) {
17915                    PreferredActivity pa = removed.get(j);
17916                    pir.removeFilter(pa);
17917                }
17918                changed = true;
17919            }
17920        }
17921        if (changed) {
17922            postPreferredActivityChangedBroadcast(userId);
17923        }
17924        return changed;
17925    }
17926
17927    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17928    private void clearIntentFilterVerificationsLPw(int userId) {
17929        final int packageCount = mPackages.size();
17930        for (int i = 0; i < packageCount; i++) {
17931            PackageParser.Package pkg = mPackages.valueAt(i);
17932            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17933        }
17934    }
17935
17936    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17937    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17938        if (userId == UserHandle.USER_ALL) {
17939            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17940                    sUserManager.getUserIds())) {
17941                for (int oneUserId : sUserManager.getUserIds()) {
17942                    scheduleWritePackageRestrictionsLocked(oneUserId);
17943                }
17944            }
17945        } else {
17946            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17947                scheduleWritePackageRestrictionsLocked(userId);
17948            }
17949        }
17950    }
17951
17952    void clearDefaultBrowserIfNeeded(String packageName) {
17953        for (int oneUserId : sUserManager.getUserIds()) {
17954            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17955            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17956            if (packageName.equals(defaultBrowserPackageName)) {
17957                setDefaultBrowserPackageName(null, oneUserId);
17958            }
17959        }
17960    }
17961
17962    @Override
17963    public void resetApplicationPreferences(int userId) {
17964        mContext.enforceCallingOrSelfPermission(
17965                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17966        final long identity = Binder.clearCallingIdentity();
17967        // writer
17968        try {
17969            synchronized (mPackages) {
17970                clearPackagePreferredActivitiesLPw(null, userId);
17971                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17972                // TODO: We have to reset the default SMS and Phone. This requires
17973                // significant refactoring to keep all default apps in the package
17974                // manager (cleaner but more work) or have the services provide
17975                // callbacks to the package manager to request a default app reset.
17976                applyFactoryDefaultBrowserLPw(userId);
17977                clearIntentFilterVerificationsLPw(userId);
17978                primeDomainVerificationsLPw(userId);
17979                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17980                scheduleWritePackageRestrictionsLocked(userId);
17981            }
17982            resetNetworkPolicies(userId);
17983        } finally {
17984            Binder.restoreCallingIdentity(identity);
17985        }
17986    }
17987
17988    @Override
17989    public int getPreferredActivities(List<IntentFilter> outFilters,
17990            List<ComponentName> outActivities, String packageName) {
17991
17992        int num = 0;
17993        final int userId = UserHandle.getCallingUserId();
17994        // reader
17995        synchronized (mPackages) {
17996            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17997            if (pir != null) {
17998                final Iterator<PreferredActivity> it = pir.filterIterator();
17999                while (it.hasNext()) {
18000                    final PreferredActivity pa = it.next();
18001                    if (packageName == null
18002                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18003                                    && pa.mPref.mAlways)) {
18004                        if (outFilters != null) {
18005                            outFilters.add(new IntentFilter(pa));
18006                        }
18007                        if (outActivities != null) {
18008                            outActivities.add(pa.mPref.mComponent);
18009                        }
18010                    }
18011                }
18012            }
18013        }
18014
18015        return num;
18016    }
18017
18018    @Override
18019    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18020            int userId) {
18021        int callingUid = Binder.getCallingUid();
18022        if (callingUid != Process.SYSTEM_UID) {
18023            throw new SecurityException(
18024                    "addPersistentPreferredActivity can only be run by the system");
18025        }
18026        if (filter.countActions() == 0) {
18027            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18028            return;
18029        }
18030        synchronized (mPackages) {
18031            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18032                    ":");
18033            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18034            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18035                    new PersistentPreferredActivity(filter, activity));
18036            scheduleWritePackageRestrictionsLocked(userId);
18037            postPreferredActivityChangedBroadcast(userId);
18038        }
18039    }
18040
18041    @Override
18042    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18043        int callingUid = Binder.getCallingUid();
18044        if (callingUid != Process.SYSTEM_UID) {
18045            throw new SecurityException(
18046                    "clearPackagePersistentPreferredActivities can only be run by the system");
18047        }
18048        ArrayList<PersistentPreferredActivity> removed = null;
18049        boolean changed = false;
18050        synchronized (mPackages) {
18051            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18052                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18053                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18054                        .valueAt(i);
18055                if (userId != thisUserId) {
18056                    continue;
18057                }
18058                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18059                while (it.hasNext()) {
18060                    PersistentPreferredActivity ppa = it.next();
18061                    // Mark entry for removal only if it matches the package name.
18062                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18063                        if (removed == null) {
18064                            removed = new ArrayList<PersistentPreferredActivity>();
18065                        }
18066                        removed.add(ppa);
18067                    }
18068                }
18069                if (removed != null) {
18070                    for (int j=0; j<removed.size(); j++) {
18071                        PersistentPreferredActivity ppa = removed.get(j);
18072                        ppir.removeFilter(ppa);
18073                    }
18074                    changed = true;
18075                }
18076            }
18077
18078            if (changed) {
18079                scheduleWritePackageRestrictionsLocked(userId);
18080                postPreferredActivityChangedBroadcast(userId);
18081            }
18082        }
18083    }
18084
18085    /**
18086     * Common machinery for picking apart a restored XML blob and passing
18087     * it to a caller-supplied functor to be applied to the running system.
18088     */
18089    private void restoreFromXml(XmlPullParser parser, int userId,
18090            String expectedStartTag, BlobXmlRestorer functor)
18091            throws IOException, XmlPullParserException {
18092        int type;
18093        while ((type = parser.next()) != XmlPullParser.START_TAG
18094                && type != XmlPullParser.END_DOCUMENT) {
18095        }
18096        if (type != XmlPullParser.START_TAG) {
18097            // oops didn't find a start tag?!
18098            if (DEBUG_BACKUP) {
18099                Slog.e(TAG, "Didn't find start tag during restore");
18100            }
18101            return;
18102        }
18103Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18104        // this is supposed to be TAG_PREFERRED_BACKUP
18105        if (!expectedStartTag.equals(parser.getName())) {
18106            if (DEBUG_BACKUP) {
18107                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18108            }
18109            return;
18110        }
18111
18112        // skip interfering stuff, then we're aligned with the backing implementation
18113        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18114Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18115        functor.apply(parser, userId);
18116    }
18117
18118    private interface BlobXmlRestorer {
18119        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18120    }
18121
18122    /**
18123     * Non-Binder method, support for the backup/restore mechanism: write the
18124     * full set of preferred activities in its canonical XML format.  Returns the
18125     * XML output as a byte array, or null if there is none.
18126     */
18127    @Override
18128    public byte[] getPreferredActivityBackup(int userId) {
18129        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18130            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18131        }
18132
18133        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18134        try {
18135            final XmlSerializer serializer = new FastXmlSerializer();
18136            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18137            serializer.startDocument(null, true);
18138            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18139
18140            synchronized (mPackages) {
18141                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18142            }
18143
18144            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18145            serializer.endDocument();
18146            serializer.flush();
18147        } catch (Exception e) {
18148            if (DEBUG_BACKUP) {
18149                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18150            }
18151            return null;
18152        }
18153
18154        return dataStream.toByteArray();
18155    }
18156
18157    @Override
18158    public void restorePreferredActivities(byte[] backup, int userId) {
18159        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18160            throw new SecurityException("Only the system may call restorePreferredActivities()");
18161        }
18162
18163        try {
18164            final XmlPullParser parser = Xml.newPullParser();
18165            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18166            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18167                    new BlobXmlRestorer() {
18168                        @Override
18169                        public void apply(XmlPullParser parser, int userId)
18170                                throws XmlPullParserException, IOException {
18171                            synchronized (mPackages) {
18172                                mSettings.readPreferredActivitiesLPw(parser, userId);
18173                            }
18174                        }
18175                    } );
18176        } catch (Exception e) {
18177            if (DEBUG_BACKUP) {
18178                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18179            }
18180        }
18181    }
18182
18183    /**
18184     * Non-Binder method, support for the backup/restore mechanism: write the
18185     * default browser (etc) settings in its canonical XML format.  Returns the default
18186     * browser XML representation as a byte array, or null if there is none.
18187     */
18188    @Override
18189    public byte[] getDefaultAppsBackup(int userId) {
18190        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18191            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18192        }
18193
18194        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18195        try {
18196            final XmlSerializer serializer = new FastXmlSerializer();
18197            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18198            serializer.startDocument(null, true);
18199            serializer.startTag(null, TAG_DEFAULT_APPS);
18200
18201            synchronized (mPackages) {
18202                mSettings.writeDefaultAppsLPr(serializer, userId);
18203            }
18204
18205            serializer.endTag(null, TAG_DEFAULT_APPS);
18206            serializer.endDocument();
18207            serializer.flush();
18208        } catch (Exception e) {
18209            if (DEBUG_BACKUP) {
18210                Slog.e(TAG, "Unable to write default apps for backup", e);
18211            }
18212            return null;
18213        }
18214
18215        return dataStream.toByteArray();
18216    }
18217
18218    @Override
18219    public void restoreDefaultApps(byte[] backup, int userId) {
18220        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18221            throw new SecurityException("Only the system may call restoreDefaultApps()");
18222        }
18223
18224        try {
18225            final XmlPullParser parser = Xml.newPullParser();
18226            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18227            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18228                    new BlobXmlRestorer() {
18229                        @Override
18230                        public void apply(XmlPullParser parser, int userId)
18231                                throws XmlPullParserException, IOException {
18232                            synchronized (mPackages) {
18233                                mSettings.readDefaultAppsLPw(parser, userId);
18234                            }
18235                        }
18236                    } );
18237        } catch (Exception e) {
18238            if (DEBUG_BACKUP) {
18239                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18240            }
18241        }
18242    }
18243
18244    @Override
18245    public byte[] getIntentFilterVerificationBackup(int userId) {
18246        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18247            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18248        }
18249
18250        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18251        try {
18252            final XmlSerializer serializer = new FastXmlSerializer();
18253            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18254            serializer.startDocument(null, true);
18255            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18256
18257            synchronized (mPackages) {
18258                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18259            }
18260
18261            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18262            serializer.endDocument();
18263            serializer.flush();
18264        } catch (Exception e) {
18265            if (DEBUG_BACKUP) {
18266                Slog.e(TAG, "Unable to write default apps for backup", e);
18267            }
18268            return null;
18269        }
18270
18271        return dataStream.toByteArray();
18272    }
18273
18274    @Override
18275    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18276        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18277            throw new SecurityException("Only the system may call restorePreferredActivities()");
18278        }
18279
18280        try {
18281            final XmlPullParser parser = Xml.newPullParser();
18282            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18283            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18284                    new BlobXmlRestorer() {
18285                        @Override
18286                        public void apply(XmlPullParser parser, int userId)
18287                                throws XmlPullParserException, IOException {
18288                            synchronized (mPackages) {
18289                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18290                                mSettings.writeLPr();
18291                            }
18292                        }
18293                    } );
18294        } catch (Exception e) {
18295            if (DEBUG_BACKUP) {
18296                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18297            }
18298        }
18299    }
18300
18301    @Override
18302    public byte[] getPermissionGrantBackup(int userId) {
18303        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18304            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18305        }
18306
18307        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18308        try {
18309            final XmlSerializer serializer = new FastXmlSerializer();
18310            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18311            serializer.startDocument(null, true);
18312            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18313
18314            synchronized (mPackages) {
18315                serializeRuntimePermissionGrantsLPr(serializer, userId);
18316            }
18317
18318            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18319            serializer.endDocument();
18320            serializer.flush();
18321        } catch (Exception e) {
18322            if (DEBUG_BACKUP) {
18323                Slog.e(TAG, "Unable to write default apps for backup", e);
18324            }
18325            return null;
18326        }
18327
18328        return dataStream.toByteArray();
18329    }
18330
18331    @Override
18332    public void restorePermissionGrants(byte[] backup, int userId) {
18333        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18334            throw new SecurityException("Only the system may call restorePermissionGrants()");
18335        }
18336
18337        try {
18338            final XmlPullParser parser = Xml.newPullParser();
18339            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18340            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18341                    new BlobXmlRestorer() {
18342                        @Override
18343                        public void apply(XmlPullParser parser, int userId)
18344                                throws XmlPullParserException, IOException {
18345                            synchronized (mPackages) {
18346                                processRestoredPermissionGrantsLPr(parser, userId);
18347                            }
18348                        }
18349                    } );
18350        } catch (Exception e) {
18351            if (DEBUG_BACKUP) {
18352                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18353            }
18354        }
18355    }
18356
18357    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18358            throws IOException {
18359        serializer.startTag(null, TAG_ALL_GRANTS);
18360
18361        final int N = mSettings.mPackages.size();
18362        for (int i = 0; i < N; i++) {
18363            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18364            boolean pkgGrantsKnown = false;
18365
18366            PermissionsState packagePerms = ps.getPermissionsState();
18367
18368            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18369                final int grantFlags = state.getFlags();
18370                // only look at grants that are not system/policy fixed
18371                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18372                    final boolean isGranted = state.isGranted();
18373                    // And only back up the user-twiddled state bits
18374                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18375                        final String packageName = mSettings.mPackages.keyAt(i);
18376                        if (!pkgGrantsKnown) {
18377                            serializer.startTag(null, TAG_GRANT);
18378                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18379                            pkgGrantsKnown = true;
18380                        }
18381
18382                        final boolean userSet =
18383                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18384                        final boolean userFixed =
18385                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18386                        final boolean revoke =
18387                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18388
18389                        serializer.startTag(null, TAG_PERMISSION);
18390                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18391                        if (isGranted) {
18392                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18393                        }
18394                        if (userSet) {
18395                            serializer.attribute(null, ATTR_USER_SET, "true");
18396                        }
18397                        if (userFixed) {
18398                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18399                        }
18400                        if (revoke) {
18401                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18402                        }
18403                        serializer.endTag(null, TAG_PERMISSION);
18404                    }
18405                }
18406            }
18407
18408            if (pkgGrantsKnown) {
18409                serializer.endTag(null, TAG_GRANT);
18410            }
18411        }
18412
18413        serializer.endTag(null, TAG_ALL_GRANTS);
18414    }
18415
18416    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18417            throws XmlPullParserException, IOException {
18418        String pkgName = null;
18419        int outerDepth = parser.getDepth();
18420        int type;
18421        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18422                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18423            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18424                continue;
18425            }
18426
18427            final String tagName = parser.getName();
18428            if (tagName.equals(TAG_GRANT)) {
18429                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18430                if (DEBUG_BACKUP) {
18431                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18432                }
18433            } else if (tagName.equals(TAG_PERMISSION)) {
18434
18435                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18436                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18437
18438                int newFlagSet = 0;
18439                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18440                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18441                }
18442                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18443                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18444                }
18445                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18446                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18447                }
18448                if (DEBUG_BACKUP) {
18449                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18450                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18451                }
18452                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18453                if (ps != null) {
18454                    // Already installed so we apply the grant immediately
18455                    if (DEBUG_BACKUP) {
18456                        Slog.v(TAG, "        + already installed; applying");
18457                    }
18458                    PermissionsState perms = ps.getPermissionsState();
18459                    BasePermission bp = mSettings.mPermissions.get(permName);
18460                    if (bp != null) {
18461                        if (isGranted) {
18462                            perms.grantRuntimePermission(bp, userId);
18463                        }
18464                        if (newFlagSet != 0) {
18465                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18466                        }
18467                    }
18468                } else {
18469                    // Need to wait for post-restore install to apply the grant
18470                    if (DEBUG_BACKUP) {
18471                        Slog.v(TAG, "        - not yet installed; saving for later");
18472                    }
18473                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18474                            isGranted, newFlagSet, userId);
18475                }
18476            } else {
18477                PackageManagerService.reportSettingsProblem(Log.WARN,
18478                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18479                XmlUtils.skipCurrentTag(parser);
18480            }
18481        }
18482
18483        scheduleWriteSettingsLocked();
18484        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18485    }
18486
18487    @Override
18488    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18489            int sourceUserId, int targetUserId, int flags) {
18490        mContext.enforceCallingOrSelfPermission(
18491                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18492        int callingUid = Binder.getCallingUid();
18493        enforceOwnerRights(ownerPackage, callingUid);
18494        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18495        if (intentFilter.countActions() == 0) {
18496            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18497            return;
18498        }
18499        synchronized (mPackages) {
18500            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18501                    ownerPackage, targetUserId, flags);
18502            CrossProfileIntentResolver resolver =
18503                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18504            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18505            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18506            if (existing != null) {
18507                int size = existing.size();
18508                for (int i = 0; i < size; i++) {
18509                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18510                        return;
18511                    }
18512                }
18513            }
18514            resolver.addFilter(newFilter);
18515            scheduleWritePackageRestrictionsLocked(sourceUserId);
18516        }
18517    }
18518
18519    @Override
18520    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18521        mContext.enforceCallingOrSelfPermission(
18522                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18523        int callingUid = Binder.getCallingUid();
18524        enforceOwnerRights(ownerPackage, callingUid);
18525        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18526        synchronized (mPackages) {
18527            CrossProfileIntentResolver resolver =
18528                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18529            ArraySet<CrossProfileIntentFilter> set =
18530                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18531            for (CrossProfileIntentFilter filter : set) {
18532                if (filter.getOwnerPackage().equals(ownerPackage)) {
18533                    resolver.removeFilter(filter);
18534                }
18535            }
18536            scheduleWritePackageRestrictionsLocked(sourceUserId);
18537        }
18538    }
18539
18540    // Enforcing that callingUid is owning pkg on userId
18541    private void enforceOwnerRights(String pkg, int callingUid) {
18542        // The system owns everything.
18543        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18544            return;
18545        }
18546        int callingUserId = UserHandle.getUserId(callingUid);
18547        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18548        if (pi == null) {
18549            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18550                    + callingUserId);
18551        }
18552        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18553            throw new SecurityException("Calling uid " + callingUid
18554                    + " does not own package " + pkg);
18555        }
18556    }
18557
18558    @Override
18559    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18560        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18561    }
18562
18563    private Intent getHomeIntent() {
18564        Intent intent = new Intent(Intent.ACTION_MAIN);
18565        intent.addCategory(Intent.CATEGORY_HOME);
18566        intent.addCategory(Intent.CATEGORY_DEFAULT);
18567        return intent;
18568    }
18569
18570    private IntentFilter getHomeFilter() {
18571        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18572        filter.addCategory(Intent.CATEGORY_HOME);
18573        filter.addCategory(Intent.CATEGORY_DEFAULT);
18574        return filter;
18575    }
18576
18577    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18578            int userId) {
18579        Intent intent  = getHomeIntent();
18580        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18581                PackageManager.GET_META_DATA, userId);
18582        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18583                true, false, false, userId);
18584
18585        allHomeCandidates.clear();
18586        if (list != null) {
18587            for (ResolveInfo ri : list) {
18588                allHomeCandidates.add(ri);
18589            }
18590        }
18591        return (preferred == null || preferred.activityInfo == null)
18592                ? null
18593                : new ComponentName(preferred.activityInfo.packageName,
18594                        preferred.activityInfo.name);
18595    }
18596
18597    @Override
18598    public void setHomeActivity(ComponentName comp, int userId) {
18599        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18600        getHomeActivitiesAsUser(homeActivities, userId);
18601
18602        boolean found = false;
18603
18604        final int size = homeActivities.size();
18605        final ComponentName[] set = new ComponentName[size];
18606        for (int i = 0; i < size; i++) {
18607            final ResolveInfo candidate = homeActivities.get(i);
18608            final ActivityInfo info = candidate.activityInfo;
18609            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18610            set[i] = activityName;
18611            if (!found && activityName.equals(comp)) {
18612                found = true;
18613            }
18614        }
18615        if (!found) {
18616            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18617                    + userId);
18618        }
18619        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18620                set, comp, userId);
18621    }
18622
18623    private @Nullable String getSetupWizardPackageName() {
18624        final Intent intent = new Intent(Intent.ACTION_MAIN);
18625        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18626
18627        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18628                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18629                        | MATCH_DISABLED_COMPONENTS,
18630                UserHandle.myUserId());
18631        if (matches.size() == 1) {
18632            return matches.get(0).getComponentInfo().packageName;
18633        } else {
18634            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18635                    + ": matches=" + matches);
18636            return null;
18637        }
18638    }
18639
18640    private @Nullable String getStorageManagerPackageName() {
18641        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18642
18643        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18644                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18645                        | MATCH_DISABLED_COMPONENTS,
18646                UserHandle.myUserId());
18647        if (matches.size() == 1) {
18648            return matches.get(0).getComponentInfo().packageName;
18649        } else {
18650            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18651                    + matches.size() + ": matches=" + matches);
18652            return null;
18653        }
18654    }
18655
18656    @Override
18657    public void setApplicationEnabledSetting(String appPackageName,
18658            int newState, int flags, int userId, String callingPackage) {
18659        if (!sUserManager.exists(userId)) return;
18660        if (callingPackage == null) {
18661            callingPackage = Integer.toString(Binder.getCallingUid());
18662        }
18663        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18664    }
18665
18666    @Override
18667    public void setComponentEnabledSetting(ComponentName componentName,
18668            int newState, int flags, int userId) {
18669        if (!sUserManager.exists(userId)) return;
18670        setEnabledSetting(componentName.getPackageName(),
18671                componentName.getClassName(), newState, flags, userId, null);
18672    }
18673
18674    private void setEnabledSetting(final String packageName, String className, int newState,
18675            final int flags, int userId, String callingPackage) {
18676        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18677              || newState == COMPONENT_ENABLED_STATE_ENABLED
18678              || newState == COMPONENT_ENABLED_STATE_DISABLED
18679              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18680              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18681            throw new IllegalArgumentException("Invalid new component state: "
18682                    + newState);
18683        }
18684        PackageSetting pkgSetting;
18685        final int uid = Binder.getCallingUid();
18686        final int permission;
18687        if (uid == Process.SYSTEM_UID) {
18688            permission = PackageManager.PERMISSION_GRANTED;
18689        } else {
18690            permission = mContext.checkCallingOrSelfPermission(
18691                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18692        }
18693        enforceCrossUserPermission(uid, userId,
18694                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18695        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18696        boolean sendNow = false;
18697        boolean isApp = (className == null);
18698        String componentName = isApp ? packageName : className;
18699        int packageUid = -1;
18700        ArrayList<String> components;
18701
18702        // writer
18703        synchronized (mPackages) {
18704            pkgSetting = mSettings.mPackages.get(packageName);
18705            if (pkgSetting == null) {
18706                if (className == null) {
18707                    throw new IllegalArgumentException("Unknown package: " + packageName);
18708                }
18709                throw new IllegalArgumentException(
18710                        "Unknown component: " + packageName + "/" + className);
18711            }
18712        }
18713
18714        // Limit who can change which apps
18715        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18716            // Don't allow apps that don't have permission to modify other apps
18717            if (!allowedByPermission) {
18718                throw new SecurityException(
18719                        "Permission Denial: attempt to change component state from pid="
18720                        + Binder.getCallingPid()
18721                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18722            }
18723            // Don't allow changing protected packages.
18724            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18725                throw new SecurityException("Cannot disable a protected package: " + packageName);
18726            }
18727        }
18728
18729        synchronized (mPackages) {
18730            if (uid == Process.SHELL_UID
18731                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18732                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18733                // unless it is a test package.
18734                int oldState = pkgSetting.getEnabled(userId);
18735                if (className == null
18736                    &&
18737                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18738                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18739                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18740                    &&
18741                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18742                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18743                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18744                    // ok
18745                } else {
18746                    throw new SecurityException(
18747                            "Shell cannot change component state for " + packageName + "/"
18748                            + className + " to " + newState);
18749                }
18750            }
18751            if (className == null) {
18752                // We're dealing with an application/package level state change
18753                if (pkgSetting.getEnabled(userId) == newState) {
18754                    // Nothing to do
18755                    return;
18756                }
18757                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18758                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18759                    // Don't care about who enables an app.
18760                    callingPackage = null;
18761                }
18762                pkgSetting.setEnabled(newState, userId, callingPackage);
18763                // pkgSetting.pkg.mSetEnabled = newState;
18764            } else {
18765                // We're dealing with a component level state change
18766                // First, verify that this is a valid class name.
18767                PackageParser.Package pkg = pkgSetting.pkg;
18768                if (pkg == null || !pkg.hasComponentClassName(className)) {
18769                    if (pkg != null &&
18770                            pkg.applicationInfo.targetSdkVersion >=
18771                                    Build.VERSION_CODES.JELLY_BEAN) {
18772                        throw new IllegalArgumentException("Component class " + className
18773                                + " does not exist in " + packageName);
18774                    } else {
18775                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18776                                + className + " does not exist in " + packageName);
18777                    }
18778                }
18779                switch (newState) {
18780                case COMPONENT_ENABLED_STATE_ENABLED:
18781                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18782                        return;
18783                    }
18784                    break;
18785                case COMPONENT_ENABLED_STATE_DISABLED:
18786                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18787                        return;
18788                    }
18789                    break;
18790                case COMPONENT_ENABLED_STATE_DEFAULT:
18791                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18792                        return;
18793                    }
18794                    break;
18795                default:
18796                    Slog.e(TAG, "Invalid new component state: " + newState);
18797                    return;
18798                }
18799            }
18800            scheduleWritePackageRestrictionsLocked(userId);
18801            components = mPendingBroadcasts.get(userId, packageName);
18802            final boolean newPackage = components == null;
18803            if (newPackage) {
18804                components = new ArrayList<String>();
18805            }
18806            if (!components.contains(componentName)) {
18807                components.add(componentName);
18808            }
18809            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18810                sendNow = true;
18811                // Purge entry from pending broadcast list if another one exists already
18812                // since we are sending one right away.
18813                mPendingBroadcasts.remove(userId, packageName);
18814            } else {
18815                if (newPackage) {
18816                    mPendingBroadcasts.put(userId, packageName, components);
18817                }
18818                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18819                    // Schedule a message
18820                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18821                }
18822            }
18823        }
18824
18825        long callingId = Binder.clearCallingIdentity();
18826        try {
18827            if (sendNow) {
18828                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18829                sendPackageChangedBroadcast(packageName,
18830                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18831            }
18832        } finally {
18833            Binder.restoreCallingIdentity(callingId);
18834        }
18835    }
18836
18837    @Override
18838    public void flushPackageRestrictionsAsUser(int userId) {
18839        if (!sUserManager.exists(userId)) {
18840            return;
18841        }
18842        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18843                false /* checkShell */, "flushPackageRestrictions");
18844        synchronized (mPackages) {
18845            mSettings.writePackageRestrictionsLPr(userId);
18846            mDirtyUsers.remove(userId);
18847            if (mDirtyUsers.isEmpty()) {
18848                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18849            }
18850        }
18851    }
18852
18853    private void sendPackageChangedBroadcast(String packageName,
18854            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18855        if (DEBUG_INSTALL)
18856            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18857                    + componentNames);
18858        Bundle extras = new Bundle(4);
18859        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18860        String nameList[] = new String[componentNames.size()];
18861        componentNames.toArray(nameList);
18862        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18863        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18864        extras.putInt(Intent.EXTRA_UID, packageUid);
18865        // If this is not reporting a change of the overall package, then only send it
18866        // to registered receivers.  We don't want to launch a swath of apps for every
18867        // little component state change.
18868        final int flags = !componentNames.contains(packageName)
18869                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18870        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18871                new int[] {UserHandle.getUserId(packageUid)});
18872    }
18873
18874    @Override
18875    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18876        if (!sUserManager.exists(userId)) return;
18877        final int uid = Binder.getCallingUid();
18878        final int permission = mContext.checkCallingOrSelfPermission(
18879                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18880        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18881        enforceCrossUserPermission(uid, userId,
18882                true /* requireFullPermission */, true /* checkShell */, "stop package");
18883        // writer
18884        synchronized (mPackages) {
18885            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18886                    allowedByPermission, uid, userId)) {
18887                scheduleWritePackageRestrictionsLocked(userId);
18888            }
18889        }
18890    }
18891
18892    @Override
18893    public String getInstallerPackageName(String packageName) {
18894        // reader
18895        synchronized (mPackages) {
18896            return mSettings.getInstallerPackageNameLPr(packageName);
18897        }
18898    }
18899
18900    public boolean isOrphaned(String packageName) {
18901        // reader
18902        synchronized (mPackages) {
18903            return mSettings.isOrphaned(packageName);
18904        }
18905    }
18906
18907    @Override
18908    public int getApplicationEnabledSetting(String packageName, int userId) {
18909        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18910        int uid = Binder.getCallingUid();
18911        enforceCrossUserPermission(uid, userId,
18912                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18913        // reader
18914        synchronized (mPackages) {
18915            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18916        }
18917    }
18918
18919    @Override
18920    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18921        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18922        int uid = Binder.getCallingUid();
18923        enforceCrossUserPermission(uid, userId,
18924                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18925        // reader
18926        synchronized (mPackages) {
18927            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18928        }
18929    }
18930
18931    @Override
18932    public void enterSafeMode() {
18933        enforceSystemOrRoot("Only the system can request entering safe mode");
18934
18935        if (!mSystemReady) {
18936            mSafeMode = true;
18937        }
18938    }
18939
18940    @Override
18941    public void systemReady() {
18942        mSystemReady = true;
18943
18944        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18945        // disabled after already being started.
18946        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18947                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18948
18949        // Read the compatibilty setting when the system is ready.
18950        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18951                mContext.getContentResolver(),
18952                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18953        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18954        if (DEBUG_SETTINGS) {
18955            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18956        }
18957
18958        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18959
18960        synchronized (mPackages) {
18961            // Verify that all of the preferred activity components actually
18962            // exist.  It is possible for applications to be updated and at
18963            // that point remove a previously declared activity component that
18964            // had been set as a preferred activity.  We try to clean this up
18965            // the next time we encounter that preferred activity, but it is
18966            // possible for the user flow to never be able to return to that
18967            // situation so here we do a sanity check to make sure we haven't
18968            // left any junk around.
18969            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18970            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18971                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18972                removed.clear();
18973                for (PreferredActivity pa : pir.filterSet()) {
18974                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18975                        removed.add(pa);
18976                    }
18977                }
18978                if (removed.size() > 0) {
18979                    for (int r=0; r<removed.size(); r++) {
18980                        PreferredActivity pa = removed.get(r);
18981                        Slog.w(TAG, "Removing dangling preferred activity: "
18982                                + pa.mPref.mComponent);
18983                        pir.removeFilter(pa);
18984                    }
18985                    mSettings.writePackageRestrictionsLPr(
18986                            mSettings.mPreferredActivities.keyAt(i));
18987                }
18988            }
18989
18990            for (int userId : UserManagerService.getInstance().getUserIds()) {
18991                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18992                    grantPermissionsUserIds = ArrayUtils.appendInt(
18993                            grantPermissionsUserIds, userId);
18994                }
18995            }
18996        }
18997        sUserManager.systemReady();
18998
18999        // If we upgraded grant all default permissions before kicking off.
19000        for (int userId : grantPermissionsUserIds) {
19001            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19002        }
19003
19004        // If we did not grant default permissions, we preload from this the
19005        // default permission exceptions lazily to ensure we don't hit the
19006        // disk on a new user creation.
19007        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19008            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19009        }
19010
19011        // Kick off any messages waiting for system ready
19012        if (mPostSystemReadyMessages != null) {
19013            for (Message msg : mPostSystemReadyMessages) {
19014                msg.sendToTarget();
19015            }
19016            mPostSystemReadyMessages = null;
19017        }
19018
19019        // Watch for external volumes that come and go over time
19020        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19021        storage.registerListener(mStorageListener);
19022
19023        mInstallerService.systemReady();
19024        mPackageDexOptimizer.systemReady();
19025
19026        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19027                StorageManagerInternal.class);
19028        StorageManagerInternal.addExternalStoragePolicy(
19029                new StorageManagerInternal.ExternalStorageMountPolicy() {
19030            @Override
19031            public int getMountMode(int uid, String packageName) {
19032                if (Process.isIsolated(uid)) {
19033                    return Zygote.MOUNT_EXTERNAL_NONE;
19034                }
19035                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19036                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19037                }
19038                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19039                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19040                }
19041                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19042                    return Zygote.MOUNT_EXTERNAL_READ;
19043                }
19044                return Zygote.MOUNT_EXTERNAL_WRITE;
19045            }
19046
19047            @Override
19048            public boolean hasExternalStorage(int uid, String packageName) {
19049                return true;
19050            }
19051        });
19052
19053        // Now that we're mostly running, clean up stale users and apps
19054        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19055        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19056    }
19057
19058    @Override
19059    public boolean isSafeMode() {
19060        return mSafeMode;
19061    }
19062
19063    @Override
19064    public boolean hasSystemUidErrors() {
19065        return mHasSystemUidErrors;
19066    }
19067
19068    static String arrayToString(int[] array) {
19069        StringBuffer buf = new StringBuffer(128);
19070        buf.append('[');
19071        if (array != null) {
19072            for (int i=0; i<array.length; i++) {
19073                if (i > 0) buf.append(", ");
19074                buf.append(array[i]);
19075            }
19076        }
19077        buf.append(']');
19078        return buf.toString();
19079    }
19080
19081    static class DumpState {
19082        public static final int DUMP_LIBS = 1 << 0;
19083        public static final int DUMP_FEATURES = 1 << 1;
19084        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19085        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19086        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19087        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19088        public static final int DUMP_PERMISSIONS = 1 << 6;
19089        public static final int DUMP_PACKAGES = 1 << 7;
19090        public static final int DUMP_SHARED_USERS = 1 << 8;
19091        public static final int DUMP_MESSAGES = 1 << 9;
19092        public static final int DUMP_PROVIDERS = 1 << 10;
19093        public static final int DUMP_VERIFIERS = 1 << 11;
19094        public static final int DUMP_PREFERRED = 1 << 12;
19095        public static final int DUMP_PREFERRED_XML = 1 << 13;
19096        public static final int DUMP_KEYSETS = 1 << 14;
19097        public static final int DUMP_VERSION = 1 << 15;
19098        public static final int DUMP_INSTALLS = 1 << 16;
19099        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19100        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19101        public static final int DUMP_FROZEN = 1 << 19;
19102        public static final int DUMP_DEXOPT = 1 << 20;
19103        public static final int DUMP_COMPILER_STATS = 1 << 21;
19104
19105        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19106
19107        private int mTypes;
19108
19109        private int mOptions;
19110
19111        private boolean mTitlePrinted;
19112
19113        private SharedUserSetting mSharedUser;
19114
19115        public boolean isDumping(int type) {
19116            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19117                return true;
19118            }
19119
19120            return (mTypes & type) != 0;
19121        }
19122
19123        public void setDump(int type) {
19124            mTypes |= type;
19125        }
19126
19127        public boolean isOptionEnabled(int option) {
19128            return (mOptions & option) != 0;
19129        }
19130
19131        public void setOptionEnabled(int option) {
19132            mOptions |= option;
19133        }
19134
19135        public boolean onTitlePrinted() {
19136            final boolean printed = mTitlePrinted;
19137            mTitlePrinted = true;
19138            return printed;
19139        }
19140
19141        public boolean getTitlePrinted() {
19142            return mTitlePrinted;
19143        }
19144
19145        public void setTitlePrinted(boolean enabled) {
19146            mTitlePrinted = enabled;
19147        }
19148
19149        public SharedUserSetting getSharedUser() {
19150            return mSharedUser;
19151        }
19152
19153        public void setSharedUser(SharedUserSetting user) {
19154            mSharedUser = user;
19155        }
19156    }
19157
19158    @Override
19159    public void onShellCommand(FileDescriptor in, FileDescriptor out,
19160            FileDescriptor err, String[] args, ShellCallback callback,
19161            ResultReceiver resultReceiver) {
19162        (new PackageManagerShellCommand(this)).exec(
19163                this, in, out, err, args, callback, resultReceiver);
19164    }
19165
19166    @Override
19167    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
19168        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
19169                != PackageManager.PERMISSION_GRANTED) {
19170            pw.println("Permission Denial: can't dump ActivityManager from from pid="
19171                    + Binder.getCallingPid()
19172                    + ", uid=" + Binder.getCallingUid()
19173                    + " without permission "
19174                    + android.Manifest.permission.DUMP);
19175            return;
19176        }
19177
19178        DumpState dumpState = new DumpState();
19179        boolean fullPreferred = false;
19180        boolean checkin = false;
19181
19182        String packageName = null;
19183        ArraySet<String> permissionNames = null;
19184
19185        int opti = 0;
19186        while (opti < args.length) {
19187            String opt = args[opti];
19188            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
19189                break;
19190            }
19191            opti++;
19192
19193            if ("-a".equals(opt)) {
19194                // Right now we only know how to print all.
19195            } else if ("-h".equals(opt)) {
19196                pw.println("Package manager dump options:");
19197                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
19198                pw.println("    --checkin: dump for a checkin");
19199                pw.println("    -f: print details of intent filters");
19200                pw.println("    -h: print this help");
19201                pw.println("  cmd may be one of:");
19202                pw.println("    l[ibraries]: list known shared libraries");
19203                pw.println("    f[eatures]: list device features");
19204                pw.println("    k[eysets]: print known keysets");
19205                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
19206                pw.println("    perm[issions]: dump permissions");
19207                pw.println("    permission [name ...]: dump declaration and use of given permission");
19208                pw.println("    pref[erred]: print preferred package settings");
19209                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
19210                pw.println("    prov[iders]: dump content providers");
19211                pw.println("    p[ackages]: dump installed packages");
19212                pw.println("    s[hared-users]: dump shared user IDs");
19213                pw.println("    m[essages]: print collected runtime messages");
19214                pw.println("    v[erifiers]: print package verifier info");
19215                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
19216                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
19217                pw.println("    version: print database version info");
19218                pw.println("    write: write current settings now");
19219                pw.println("    installs: details about install sessions");
19220                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
19221                pw.println("    dexopt: dump dexopt state");
19222                pw.println("    compiler-stats: dump compiler statistics");
19223                pw.println("    <package.name>: info about given package");
19224                return;
19225            } else if ("--checkin".equals(opt)) {
19226                checkin = true;
19227            } else if ("-f".equals(opt)) {
19228                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19229            } else {
19230                pw.println("Unknown argument: " + opt + "; use -h for help");
19231            }
19232        }
19233
19234        // Is the caller requesting to dump a particular piece of data?
19235        if (opti < args.length) {
19236            String cmd = args[opti];
19237            opti++;
19238            // Is this a package name?
19239            if ("android".equals(cmd) || cmd.contains(".")) {
19240                packageName = cmd;
19241                // When dumping a single package, we always dump all of its
19242                // filter information since the amount of data will be reasonable.
19243                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19244            } else if ("check-permission".equals(cmd)) {
19245                if (opti >= args.length) {
19246                    pw.println("Error: check-permission missing permission argument");
19247                    return;
19248                }
19249                String perm = args[opti];
19250                opti++;
19251                if (opti >= args.length) {
19252                    pw.println("Error: check-permission missing package argument");
19253                    return;
19254                }
19255                String pkg = args[opti];
19256                opti++;
19257                int user = UserHandle.getUserId(Binder.getCallingUid());
19258                if (opti < args.length) {
19259                    try {
19260                        user = Integer.parseInt(args[opti]);
19261                    } catch (NumberFormatException e) {
19262                        pw.println("Error: check-permission user argument is not a number: "
19263                                + args[opti]);
19264                        return;
19265                    }
19266                }
19267                pw.println(checkPermission(perm, pkg, user));
19268                return;
19269            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
19270                dumpState.setDump(DumpState.DUMP_LIBS);
19271            } else if ("f".equals(cmd) || "features".equals(cmd)) {
19272                dumpState.setDump(DumpState.DUMP_FEATURES);
19273            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
19274                if (opti >= args.length) {
19275                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
19276                            | DumpState.DUMP_SERVICE_RESOLVERS
19277                            | DumpState.DUMP_RECEIVER_RESOLVERS
19278                            | DumpState.DUMP_CONTENT_RESOLVERS);
19279                } else {
19280                    while (opti < args.length) {
19281                        String name = args[opti];
19282                        if ("a".equals(name) || "activity".equals(name)) {
19283                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
19284                        } else if ("s".equals(name) || "service".equals(name)) {
19285                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
19286                        } else if ("r".equals(name) || "receiver".equals(name)) {
19287                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19288                        } else if ("c".equals(name) || "content".equals(name)) {
19289                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19290                        } else {
19291                            pw.println("Error: unknown resolver table type: " + name);
19292                            return;
19293                        }
19294                        opti++;
19295                    }
19296                }
19297            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19298                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19299            } else if ("permission".equals(cmd)) {
19300                if (opti >= args.length) {
19301                    pw.println("Error: permission requires permission name");
19302                    return;
19303                }
19304                permissionNames = new ArraySet<>();
19305                while (opti < args.length) {
19306                    permissionNames.add(args[opti]);
19307                    opti++;
19308                }
19309                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19310                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19311            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19312                dumpState.setDump(DumpState.DUMP_PREFERRED);
19313            } else if ("preferred-xml".equals(cmd)) {
19314                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19315                if (opti < args.length && "--full".equals(args[opti])) {
19316                    fullPreferred = true;
19317                    opti++;
19318                }
19319            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19320                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19321            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19322                dumpState.setDump(DumpState.DUMP_PACKAGES);
19323            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19324                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19325            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19326                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19327            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19328                dumpState.setDump(DumpState.DUMP_MESSAGES);
19329            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19330                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19331            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19332                    || "intent-filter-verifiers".equals(cmd)) {
19333                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19334            } else if ("version".equals(cmd)) {
19335                dumpState.setDump(DumpState.DUMP_VERSION);
19336            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19337                dumpState.setDump(DumpState.DUMP_KEYSETS);
19338            } else if ("installs".equals(cmd)) {
19339                dumpState.setDump(DumpState.DUMP_INSTALLS);
19340            } else if ("frozen".equals(cmd)) {
19341                dumpState.setDump(DumpState.DUMP_FROZEN);
19342            } else if ("dexopt".equals(cmd)) {
19343                dumpState.setDump(DumpState.DUMP_DEXOPT);
19344            } else if ("compiler-stats".equals(cmd)) {
19345                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19346            } else if ("write".equals(cmd)) {
19347                synchronized (mPackages) {
19348                    mSettings.writeLPr();
19349                    pw.println("Settings written.");
19350                    return;
19351                }
19352            }
19353        }
19354
19355        if (checkin) {
19356            pw.println("vers,1");
19357        }
19358
19359        // reader
19360        synchronized (mPackages) {
19361            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19362                if (!checkin) {
19363                    if (dumpState.onTitlePrinted())
19364                        pw.println();
19365                    pw.println("Database versions:");
19366                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19367                }
19368            }
19369
19370            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19371                if (!checkin) {
19372                    if (dumpState.onTitlePrinted())
19373                        pw.println();
19374                    pw.println("Verifiers:");
19375                    pw.print("  Required: ");
19376                    pw.print(mRequiredVerifierPackage);
19377                    pw.print(" (uid=");
19378                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19379                            UserHandle.USER_SYSTEM));
19380                    pw.println(")");
19381                } else if (mRequiredVerifierPackage != null) {
19382                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19383                    pw.print(",");
19384                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19385                            UserHandle.USER_SYSTEM));
19386                }
19387            }
19388
19389            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19390                    packageName == null) {
19391                if (mIntentFilterVerifierComponent != null) {
19392                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19393                    if (!checkin) {
19394                        if (dumpState.onTitlePrinted())
19395                            pw.println();
19396                        pw.println("Intent Filter Verifier:");
19397                        pw.print("  Using: ");
19398                        pw.print(verifierPackageName);
19399                        pw.print(" (uid=");
19400                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19401                                UserHandle.USER_SYSTEM));
19402                        pw.println(")");
19403                    } else if (verifierPackageName != null) {
19404                        pw.print("ifv,"); pw.print(verifierPackageName);
19405                        pw.print(",");
19406                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19407                                UserHandle.USER_SYSTEM));
19408                    }
19409                } else {
19410                    pw.println();
19411                    pw.println("No Intent Filter Verifier available!");
19412                }
19413            }
19414
19415            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19416                boolean printedHeader = false;
19417                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19418                while (it.hasNext()) {
19419                    String name = it.next();
19420                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19421                    if (!checkin) {
19422                        if (!printedHeader) {
19423                            if (dumpState.onTitlePrinted())
19424                                pw.println();
19425                            pw.println("Libraries:");
19426                            printedHeader = true;
19427                        }
19428                        pw.print("  ");
19429                    } else {
19430                        pw.print("lib,");
19431                    }
19432                    pw.print(name);
19433                    if (!checkin) {
19434                        pw.print(" -> ");
19435                    }
19436                    if (ent.path != null) {
19437                        if (!checkin) {
19438                            pw.print("(jar) ");
19439                            pw.print(ent.path);
19440                        } else {
19441                            pw.print(",jar,");
19442                            pw.print(ent.path);
19443                        }
19444                    } else {
19445                        if (!checkin) {
19446                            pw.print("(apk) ");
19447                            pw.print(ent.apk);
19448                        } else {
19449                            pw.print(",apk,");
19450                            pw.print(ent.apk);
19451                        }
19452                    }
19453                    pw.println();
19454                }
19455            }
19456
19457            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19458                if (dumpState.onTitlePrinted())
19459                    pw.println();
19460                if (!checkin) {
19461                    pw.println("Features:");
19462                }
19463
19464                for (FeatureInfo feat : mAvailableFeatures.values()) {
19465                    if (checkin) {
19466                        pw.print("feat,");
19467                        pw.print(feat.name);
19468                        pw.print(",");
19469                        pw.println(feat.version);
19470                    } else {
19471                        pw.print("  ");
19472                        pw.print(feat.name);
19473                        if (feat.version > 0) {
19474                            pw.print(" version=");
19475                            pw.print(feat.version);
19476                        }
19477                        pw.println();
19478                    }
19479                }
19480            }
19481
19482            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19483                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19484                        : "Activity Resolver Table:", "  ", packageName,
19485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19486                    dumpState.setTitlePrinted(true);
19487                }
19488            }
19489            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19490                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19491                        : "Receiver Resolver Table:", "  ", packageName,
19492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19493                    dumpState.setTitlePrinted(true);
19494                }
19495            }
19496            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19497                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19498                        : "Service Resolver Table:", "  ", packageName,
19499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19500                    dumpState.setTitlePrinted(true);
19501                }
19502            }
19503            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19504                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19505                        : "Provider Resolver Table:", "  ", packageName,
19506                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19507                    dumpState.setTitlePrinted(true);
19508                }
19509            }
19510
19511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19512                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19513                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19514                    int user = mSettings.mPreferredActivities.keyAt(i);
19515                    if (pir.dump(pw,
19516                            dumpState.getTitlePrinted()
19517                                ? "\nPreferred Activities User " + user + ":"
19518                                : "Preferred Activities User " + user + ":", "  ",
19519                            packageName, true, false)) {
19520                        dumpState.setTitlePrinted(true);
19521                    }
19522                }
19523            }
19524
19525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19526                pw.flush();
19527                FileOutputStream fout = new FileOutputStream(fd);
19528                BufferedOutputStream str = new BufferedOutputStream(fout);
19529                XmlSerializer serializer = new FastXmlSerializer();
19530                try {
19531                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19532                    serializer.startDocument(null, true);
19533                    serializer.setFeature(
19534                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19535                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19536                    serializer.endDocument();
19537                    serializer.flush();
19538                } catch (IllegalArgumentException e) {
19539                    pw.println("Failed writing: " + e);
19540                } catch (IllegalStateException e) {
19541                    pw.println("Failed writing: " + e);
19542                } catch (IOException e) {
19543                    pw.println("Failed writing: " + e);
19544                }
19545            }
19546
19547            if (!checkin
19548                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19549                    && packageName == null) {
19550                pw.println();
19551                int count = mSettings.mPackages.size();
19552                if (count == 0) {
19553                    pw.println("No applications!");
19554                    pw.println();
19555                } else {
19556                    final String prefix = "  ";
19557                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19558                    if (allPackageSettings.size() == 0) {
19559                        pw.println("No domain preferred apps!");
19560                        pw.println();
19561                    } else {
19562                        pw.println("App verification status:");
19563                        pw.println();
19564                        count = 0;
19565                        for (PackageSetting ps : allPackageSettings) {
19566                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19567                            if (ivi == null || ivi.getPackageName() == null) continue;
19568                            pw.println(prefix + "Package: " + ivi.getPackageName());
19569                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19570                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19571                            pw.println();
19572                            count++;
19573                        }
19574                        if (count == 0) {
19575                            pw.println(prefix + "No app verification established.");
19576                            pw.println();
19577                        }
19578                        for (int userId : sUserManager.getUserIds()) {
19579                            pw.println("App linkages for user " + userId + ":");
19580                            pw.println();
19581                            count = 0;
19582                            for (PackageSetting ps : allPackageSettings) {
19583                                final long status = ps.getDomainVerificationStatusForUser(userId);
19584                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19585                                    continue;
19586                                }
19587                                pw.println(prefix + "Package: " + ps.name);
19588                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19589                                String statusStr = IntentFilterVerificationInfo.
19590                                        getStatusStringFromValue(status);
19591                                pw.println(prefix + "Status:  " + statusStr);
19592                                pw.println();
19593                                count++;
19594                            }
19595                            if (count == 0) {
19596                                pw.println(prefix + "No configured app linkages.");
19597                                pw.println();
19598                            }
19599                        }
19600                    }
19601                }
19602            }
19603
19604            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19605                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19606                if (packageName == null && permissionNames == null) {
19607                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19608                        if (iperm == 0) {
19609                            if (dumpState.onTitlePrinted())
19610                                pw.println();
19611                            pw.println("AppOp Permissions:");
19612                        }
19613                        pw.print("  AppOp Permission ");
19614                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19615                        pw.println(":");
19616                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19617                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19618                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19619                        }
19620                    }
19621                }
19622            }
19623
19624            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19625                boolean printedSomething = false;
19626                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19627                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19628                        continue;
19629                    }
19630                    if (!printedSomething) {
19631                        if (dumpState.onTitlePrinted())
19632                            pw.println();
19633                        pw.println("Registered ContentProviders:");
19634                        printedSomething = true;
19635                    }
19636                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19637                    pw.print("    "); pw.println(p.toString());
19638                }
19639                printedSomething = false;
19640                for (Map.Entry<String, PackageParser.Provider> entry :
19641                        mProvidersByAuthority.entrySet()) {
19642                    PackageParser.Provider p = entry.getValue();
19643                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19644                        continue;
19645                    }
19646                    if (!printedSomething) {
19647                        if (dumpState.onTitlePrinted())
19648                            pw.println();
19649                        pw.println("ContentProvider Authorities:");
19650                        printedSomething = true;
19651                    }
19652                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19653                    pw.print("    "); pw.println(p.toString());
19654                    if (p.info != null && p.info.applicationInfo != null) {
19655                        final String appInfo = p.info.applicationInfo.toString();
19656                        pw.print("      applicationInfo="); pw.println(appInfo);
19657                    }
19658                }
19659            }
19660
19661            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19662                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19663            }
19664
19665            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19666                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19667            }
19668
19669            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19670                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19671            }
19672
19673            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19674                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19675            }
19676
19677            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19678                // XXX should handle packageName != null by dumping only install data that
19679                // the given package is involved with.
19680                if (dumpState.onTitlePrinted()) pw.println();
19681                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19682            }
19683
19684            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19685                // XXX should handle packageName != null by dumping only install data that
19686                // the given package is involved with.
19687                if (dumpState.onTitlePrinted()) pw.println();
19688
19689                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19690                ipw.println();
19691                ipw.println("Frozen packages:");
19692                ipw.increaseIndent();
19693                if (mFrozenPackages.size() == 0) {
19694                    ipw.println("(none)");
19695                } else {
19696                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19697                        ipw.println(mFrozenPackages.valueAt(i));
19698                    }
19699                }
19700                ipw.decreaseIndent();
19701            }
19702
19703            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19704                if (dumpState.onTitlePrinted()) pw.println();
19705                dumpDexoptStateLPr(pw, packageName);
19706            }
19707
19708            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19709                if (dumpState.onTitlePrinted()) pw.println();
19710                dumpCompilerStatsLPr(pw, packageName);
19711            }
19712
19713            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19714                if (dumpState.onTitlePrinted()) pw.println();
19715                mSettings.dumpReadMessagesLPr(pw, dumpState);
19716
19717                pw.println();
19718                pw.println("Package warning messages:");
19719                BufferedReader in = null;
19720                String line = null;
19721                try {
19722                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19723                    while ((line = in.readLine()) != null) {
19724                        if (line.contains("ignored: updated version")) continue;
19725                        pw.println(line);
19726                    }
19727                } catch (IOException ignored) {
19728                } finally {
19729                    IoUtils.closeQuietly(in);
19730                }
19731            }
19732
19733            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19734                BufferedReader in = null;
19735                String line = null;
19736                try {
19737                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19738                    while ((line = in.readLine()) != null) {
19739                        if (line.contains("ignored: updated version")) continue;
19740                        pw.print("msg,");
19741                        pw.println(line);
19742                    }
19743                } catch (IOException ignored) {
19744                } finally {
19745                    IoUtils.closeQuietly(in);
19746                }
19747            }
19748        }
19749    }
19750
19751    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19752        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19753        ipw.println();
19754        ipw.println("Dexopt state:");
19755        ipw.increaseIndent();
19756        Collection<PackageParser.Package> packages = null;
19757        if (packageName != null) {
19758            PackageParser.Package targetPackage = mPackages.get(packageName);
19759            if (targetPackage != null) {
19760                packages = Collections.singletonList(targetPackage);
19761            } else {
19762                ipw.println("Unable to find package: " + packageName);
19763                return;
19764            }
19765        } else {
19766            packages = mPackages.values();
19767        }
19768
19769        for (PackageParser.Package pkg : packages) {
19770            ipw.println("[" + pkg.packageName + "]");
19771            ipw.increaseIndent();
19772            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19773            ipw.decreaseIndent();
19774        }
19775    }
19776
19777    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19778        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19779        ipw.println();
19780        ipw.println("Compiler stats:");
19781        ipw.increaseIndent();
19782        Collection<PackageParser.Package> packages = null;
19783        if (packageName != null) {
19784            PackageParser.Package targetPackage = mPackages.get(packageName);
19785            if (targetPackage != null) {
19786                packages = Collections.singletonList(targetPackage);
19787            } else {
19788                ipw.println("Unable to find package: " + packageName);
19789                return;
19790            }
19791        } else {
19792            packages = mPackages.values();
19793        }
19794
19795        for (PackageParser.Package pkg : packages) {
19796            ipw.println("[" + pkg.packageName + "]");
19797            ipw.increaseIndent();
19798
19799            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19800            if (stats == null) {
19801                ipw.println("(No recorded stats)");
19802            } else {
19803                stats.dump(ipw);
19804            }
19805            ipw.decreaseIndent();
19806        }
19807    }
19808
19809    private String dumpDomainString(String packageName) {
19810        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19811                .getList();
19812        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19813
19814        ArraySet<String> result = new ArraySet<>();
19815        if (iviList.size() > 0) {
19816            for (IntentFilterVerificationInfo ivi : iviList) {
19817                for (String host : ivi.getDomains()) {
19818                    result.add(host);
19819                }
19820            }
19821        }
19822        if (filters != null && filters.size() > 0) {
19823            for (IntentFilter filter : filters) {
19824                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19825                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19826                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19827                    result.addAll(filter.getHostsList());
19828                }
19829            }
19830        }
19831
19832        StringBuilder sb = new StringBuilder(result.size() * 16);
19833        for (String domain : result) {
19834            if (sb.length() > 0) sb.append(" ");
19835            sb.append(domain);
19836        }
19837        return sb.toString();
19838    }
19839
19840    // ------- apps on sdcard specific code -------
19841    static final boolean DEBUG_SD_INSTALL = false;
19842
19843    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19844
19845    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19846
19847    private boolean mMediaMounted = false;
19848
19849    static String getEncryptKey() {
19850        try {
19851            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19852                    SD_ENCRYPTION_KEYSTORE_NAME);
19853            if (sdEncKey == null) {
19854                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19855                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19856                if (sdEncKey == null) {
19857                    Slog.e(TAG, "Failed to create encryption keys");
19858                    return null;
19859                }
19860            }
19861            return sdEncKey;
19862        } catch (NoSuchAlgorithmException nsae) {
19863            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19864            return null;
19865        } catch (IOException ioe) {
19866            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19867            return null;
19868        }
19869    }
19870
19871    /*
19872     * Update media status on PackageManager.
19873     */
19874    @Override
19875    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19876        int callingUid = Binder.getCallingUid();
19877        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19878            throw new SecurityException("Media status can only be updated by the system");
19879        }
19880        // reader; this apparently protects mMediaMounted, but should probably
19881        // be a different lock in that case.
19882        synchronized (mPackages) {
19883            Log.i(TAG, "Updating external media status from "
19884                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19885                    + (mediaStatus ? "mounted" : "unmounted"));
19886            if (DEBUG_SD_INSTALL)
19887                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19888                        + ", mMediaMounted=" + mMediaMounted);
19889            if (mediaStatus == mMediaMounted) {
19890                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19891                        : 0, -1);
19892                mHandler.sendMessage(msg);
19893                return;
19894            }
19895            mMediaMounted = mediaStatus;
19896        }
19897        // Queue up an async operation since the package installation may take a
19898        // little while.
19899        mHandler.post(new Runnable() {
19900            public void run() {
19901                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19902            }
19903        });
19904    }
19905
19906    /**
19907     * Called by StorageManagerService when the initial ASECs to scan are available.
19908     * Should block until all the ASEC containers are finished being scanned.
19909     */
19910    public void scanAvailableAsecs() {
19911        updateExternalMediaStatusInner(true, false, false);
19912    }
19913
19914    /*
19915     * Collect information of applications on external media, map them against
19916     * existing containers and update information based on current mount status.
19917     * Please note that we always have to report status if reportStatus has been
19918     * set to true especially when unloading packages.
19919     */
19920    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19921            boolean externalStorage) {
19922        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19923        int[] uidArr = EmptyArray.INT;
19924
19925        final String[] list = PackageHelper.getSecureContainerList();
19926        if (ArrayUtils.isEmpty(list)) {
19927            Log.i(TAG, "No secure containers found");
19928        } else {
19929            // Process list of secure containers and categorize them
19930            // as active or stale based on their package internal state.
19931
19932            // reader
19933            synchronized (mPackages) {
19934                for (String cid : list) {
19935                    // Leave stages untouched for now; installer service owns them
19936                    if (PackageInstallerService.isStageName(cid)) continue;
19937
19938                    if (DEBUG_SD_INSTALL)
19939                        Log.i(TAG, "Processing container " + cid);
19940                    String pkgName = getAsecPackageName(cid);
19941                    if (pkgName == null) {
19942                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19943                        continue;
19944                    }
19945                    if (DEBUG_SD_INSTALL)
19946                        Log.i(TAG, "Looking for pkg : " + pkgName);
19947
19948                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19949                    if (ps == null) {
19950                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19951                        continue;
19952                    }
19953
19954                    /*
19955                     * Skip packages that are not external if we're unmounting
19956                     * external storage.
19957                     */
19958                    if (externalStorage && !isMounted && !isExternal(ps)) {
19959                        continue;
19960                    }
19961
19962                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19963                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19964                    // The package status is changed only if the code path
19965                    // matches between settings and the container id.
19966                    if (ps.codePathString != null
19967                            && ps.codePathString.startsWith(args.getCodePath())) {
19968                        if (DEBUG_SD_INSTALL) {
19969                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19970                                    + " at code path: " + ps.codePathString);
19971                        }
19972
19973                        // We do have a valid package installed on sdcard
19974                        processCids.put(args, ps.codePathString);
19975                        final int uid = ps.appId;
19976                        if (uid != -1) {
19977                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19978                        }
19979                    } else {
19980                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19981                                + ps.codePathString);
19982                    }
19983                }
19984            }
19985
19986            Arrays.sort(uidArr);
19987        }
19988
19989        // Process packages with valid entries.
19990        if (isMounted) {
19991            if (DEBUG_SD_INSTALL)
19992                Log.i(TAG, "Loading packages");
19993            loadMediaPackages(processCids, uidArr, externalStorage);
19994            startCleaningPackages();
19995            mInstallerService.onSecureContainersAvailable();
19996        } else {
19997            if (DEBUG_SD_INSTALL)
19998                Log.i(TAG, "Unloading packages");
19999            unloadMediaPackages(processCids, uidArr, reportStatus);
20000        }
20001    }
20002
20003    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20004            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20005        final int size = infos.size();
20006        final String[] packageNames = new String[size];
20007        final int[] packageUids = new int[size];
20008        for (int i = 0; i < size; i++) {
20009            final ApplicationInfo info = infos.get(i);
20010            packageNames[i] = info.packageName;
20011            packageUids[i] = info.uid;
20012        }
20013        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20014                finishedReceiver);
20015    }
20016
20017    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20018            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20019        sendResourcesChangedBroadcast(mediaStatus, replacing,
20020                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20021    }
20022
20023    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20024            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20025        int size = pkgList.length;
20026        if (size > 0) {
20027            // Send broadcasts here
20028            Bundle extras = new Bundle();
20029            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20030            if (uidArr != null) {
20031                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20032            }
20033            if (replacing) {
20034                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20035            }
20036            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20037                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20038            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20039        }
20040    }
20041
20042   /*
20043     * Look at potentially valid container ids from processCids If package
20044     * information doesn't match the one on record or package scanning fails,
20045     * the cid is added to list of removeCids. We currently don't delete stale
20046     * containers.
20047     */
20048    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20049            boolean externalStorage) {
20050        ArrayList<String> pkgList = new ArrayList<String>();
20051        Set<AsecInstallArgs> keys = processCids.keySet();
20052
20053        for (AsecInstallArgs args : keys) {
20054            String codePath = processCids.get(args);
20055            if (DEBUG_SD_INSTALL)
20056                Log.i(TAG, "Loading container : " + args.cid);
20057            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20058            try {
20059                // Make sure there are no container errors first.
20060                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20061                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20062                            + " when installing from sdcard");
20063                    continue;
20064                }
20065                // Check code path here.
20066                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20067                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20068                            + " does not match one in settings " + codePath);
20069                    continue;
20070                }
20071                // Parse package
20072                int parseFlags = mDefParseFlags;
20073                if (args.isExternalAsec()) {
20074                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20075                }
20076                if (args.isFwdLocked()) {
20077                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20078                }
20079
20080                synchronized (mInstallLock) {
20081                    PackageParser.Package pkg = null;
20082                    try {
20083                        // Sadly we don't know the package name yet to freeze it
20084                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20085                                SCAN_IGNORE_FROZEN, 0, null);
20086                    } catch (PackageManagerException e) {
20087                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20088                    }
20089                    // Scan the package
20090                    if (pkg != null) {
20091                        /*
20092                         * TODO why is the lock being held? doPostInstall is
20093                         * called in other places without the lock. This needs
20094                         * to be straightened out.
20095                         */
20096                        // writer
20097                        synchronized (mPackages) {
20098                            retCode = PackageManager.INSTALL_SUCCEEDED;
20099                            pkgList.add(pkg.packageName);
20100                            // Post process args
20101                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20102                                    pkg.applicationInfo.uid);
20103                        }
20104                    } else {
20105                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20106                    }
20107                }
20108
20109            } finally {
20110                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20111                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20112                }
20113            }
20114        }
20115        // writer
20116        synchronized (mPackages) {
20117            // If the platform SDK has changed since the last time we booted,
20118            // we need to re-grant app permission to catch any new ones that
20119            // appear. This is really a hack, and means that apps can in some
20120            // cases get permissions that the user didn't initially explicitly
20121            // allow... it would be nice to have some better way to handle
20122            // this situation.
20123            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20124                    : mSettings.getInternalVersion();
20125            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20126                    : StorageManager.UUID_PRIVATE_INTERNAL;
20127
20128            int updateFlags = UPDATE_PERMISSIONS_ALL;
20129            if (ver.sdkVersion != mSdkVersion) {
20130                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20131                        + mSdkVersion + "; regranting permissions for external");
20132                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20133            }
20134            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20135
20136            // Yay, everything is now upgraded
20137            ver.forceCurrent();
20138
20139            // can downgrade to reader
20140            // Persist settings
20141            mSettings.writeLPr();
20142        }
20143        // Send a broadcast to let everyone know we are done processing
20144        if (pkgList.size() > 0) {
20145            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20146        }
20147    }
20148
20149   /*
20150     * Utility method to unload a list of specified containers
20151     */
20152    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
20153        // Just unmount all valid containers.
20154        for (AsecInstallArgs arg : cidArgs) {
20155            synchronized (mInstallLock) {
20156                arg.doPostDeleteLI(false);
20157           }
20158       }
20159   }
20160
20161    /*
20162     * Unload packages mounted on external media. This involves deleting package
20163     * data from internal structures, sending broadcasts about disabled packages,
20164     * gc'ing to free up references, unmounting all secure containers
20165     * corresponding to packages on external media, and posting a
20166     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
20167     * that we always have to post this message if status has been requested no
20168     * matter what.
20169     */
20170    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
20171            final boolean reportStatus) {
20172        if (DEBUG_SD_INSTALL)
20173            Log.i(TAG, "unloading media packages");
20174        ArrayList<String> pkgList = new ArrayList<String>();
20175        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
20176        final Set<AsecInstallArgs> keys = processCids.keySet();
20177        for (AsecInstallArgs args : keys) {
20178            String pkgName = args.getPackageName();
20179            if (DEBUG_SD_INSTALL)
20180                Log.i(TAG, "Trying to unload pkg : " + pkgName);
20181            // Delete package internally
20182            PackageRemovedInfo outInfo = new PackageRemovedInfo();
20183            synchronized (mInstallLock) {
20184                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20185                final boolean res;
20186                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
20187                        "unloadMediaPackages")) {
20188                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
20189                            null);
20190                }
20191                if (res) {
20192                    pkgList.add(pkgName);
20193                } else {
20194                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
20195                    failedList.add(args);
20196                }
20197            }
20198        }
20199
20200        // reader
20201        synchronized (mPackages) {
20202            // We didn't update the settings after removing each package;
20203            // write them now for all packages.
20204            mSettings.writeLPr();
20205        }
20206
20207        // We have to absolutely send UPDATED_MEDIA_STATUS only
20208        // after confirming that all the receivers processed the ordered
20209        // broadcast when packages get disabled, force a gc to clean things up.
20210        // and unload all the containers.
20211        if (pkgList.size() > 0) {
20212            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
20213                    new IIntentReceiver.Stub() {
20214                public void performReceive(Intent intent, int resultCode, String data,
20215                        Bundle extras, boolean ordered, boolean sticky,
20216                        int sendingUser) throws RemoteException {
20217                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
20218                            reportStatus ? 1 : 0, 1, keys);
20219                    mHandler.sendMessage(msg);
20220                }
20221            });
20222        } else {
20223            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
20224                    keys);
20225            mHandler.sendMessage(msg);
20226        }
20227    }
20228
20229    private void loadPrivatePackages(final VolumeInfo vol) {
20230        mHandler.post(new Runnable() {
20231            @Override
20232            public void run() {
20233                loadPrivatePackagesInner(vol);
20234            }
20235        });
20236    }
20237
20238    private void loadPrivatePackagesInner(VolumeInfo vol) {
20239        final String volumeUuid = vol.fsUuid;
20240        if (TextUtils.isEmpty(volumeUuid)) {
20241            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20242            return;
20243        }
20244
20245        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20246        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20247        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20248
20249        final VersionInfo ver;
20250        final List<PackageSetting> packages;
20251        synchronized (mPackages) {
20252            ver = mSettings.findOrCreateVersion(volumeUuid);
20253            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20254        }
20255
20256        for (PackageSetting ps : packages) {
20257            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20258            synchronized (mInstallLock) {
20259                final PackageParser.Package pkg;
20260                try {
20261                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20262                    loaded.add(pkg.applicationInfo);
20263
20264                } catch (PackageManagerException e) {
20265                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20266                }
20267
20268                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20269                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20270                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20271                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20272                }
20273            }
20274        }
20275
20276        // Reconcile app data for all started/unlocked users
20277        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20278        final UserManager um = mContext.getSystemService(UserManager.class);
20279        UserManagerInternal umInternal = getUserManagerInternal();
20280        for (UserInfo user : um.getUsers()) {
20281            final int flags;
20282            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20283                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20284            } else if (umInternal.isUserRunning(user.id)) {
20285                flags = StorageManager.FLAG_STORAGE_DE;
20286            } else {
20287                continue;
20288            }
20289
20290            try {
20291                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20292                synchronized (mInstallLock) {
20293                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20294                }
20295            } catch (IllegalStateException e) {
20296                // Device was probably ejected, and we'll process that event momentarily
20297                Slog.w(TAG, "Failed to prepare storage: " + e);
20298            }
20299        }
20300
20301        synchronized (mPackages) {
20302            int updateFlags = UPDATE_PERMISSIONS_ALL;
20303            if (ver.sdkVersion != mSdkVersion) {
20304                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20305                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20306                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20307            }
20308            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20309
20310            // Yay, everything is now upgraded
20311            ver.forceCurrent();
20312
20313            mSettings.writeLPr();
20314        }
20315
20316        for (PackageFreezer freezer : freezers) {
20317            freezer.close();
20318        }
20319
20320        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20321        sendResourcesChangedBroadcast(true, false, loaded, null);
20322    }
20323
20324    private void unloadPrivatePackages(final VolumeInfo vol) {
20325        mHandler.post(new Runnable() {
20326            @Override
20327            public void run() {
20328                unloadPrivatePackagesInner(vol);
20329            }
20330        });
20331    }
20332
20333    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20334        final String volumeUuid = vol.fsUuid;
20335        if (TextUtils.isEmpty(volumeUuid)) {
20336            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20337            return;
20338        }
20339
20340        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20341        synchronized (mInstallLock) {
20342        synchronized (mPackages) {
20343            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20344            for (PackageSetting ps : packages) {
20345                if (ps.pkg == null) continue;
20346
20347                final ApplicationInfo info = ps.pkg.applicationInfo;
20348                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20349                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20350
20351                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20352                        "unloadPrivatePackagesInner")) {
20353                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20354                            false, null)) {
20355                        unloaded.add(info);
20356                    } else {
20357                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20358                    }
20359                }
20360
20361                // Try very hard to release any references to this package
20362                // so we don't risk the system server being killed due to
20363                // open FDs
20364                AttributeCache.instance().removePackage(ps.name);
20365            }
20366
20367            mSettings.writeLPr();
20368        }
20369        }
20370
20371        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20372        sendResourcesChangedBroadcast(false, false, unloaded, null);
20373
20374        // Try very hard to release any references to this path so we don't risk
20375        // the system server being killed due to open FDs
20376        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20377
20378        for (int i = 0; i < 3; i++) {
20379            System.gc();
20380            System.runFinalization();
20381        }
20382    }
20383
20384    /**
20385     * Prepare storage areas for given user on all mounted devices.
20386     */
20387    void prepareUserData(int userId, int userSerial, int flags) {
20388        synchronized (mInstallLock) {
20389            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20390            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20391                final String volumeUuid = vol.getFsUuid();
20392                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20393            }
20394        }
20395    }
20396
20397    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20398            boolean allowRecover) {
20399        // Prepare storage and verify that serial numbers are consistent; if
20400        // there's a mismatch we need to destroy to avoid leaking data
20401        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20402        try {
20403            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20404
20405            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20406                UserManagerService.enforceSerialNumber(
20407                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20408                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20409                    UserManagerService.enforceSerialNumber(
20410                            Environment.getDataSystemDeDirectory(userId), userSerial);
20411                }
20412            }
20413            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20414                UserManagerService.enforceSerialNumber(
20415                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20416                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20417                    UserManagerService.enforceSerialNumber(
20418                            Environment.getDataSystemCeDirectory(userId), userSerial);
20419                }
20420            }
20421
20422            synchronized (mInstallLock) {
20423                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20424            }
20425        } catch (Exception e) {
20426            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20427                    + " because we failed to prepare: " + e);
20428            destroyUserDataLI(volumeUuid, userId,
20429                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20430
20431            if (allowRecover) {
20432                // Try one last time; if we fail again we're really in trouble
20433                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20434            }
20435        }
20436    }
20437
20438    /**
20439     * Destroy storage areas for given user on all mounted devices.
20440     */
20441    void destroyUserData(int userId, int flags) {
20442        synchronized (mInstallLock) {
20443            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20444            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20445                final String volumeUuid = vol.getFsUuid();
20446                destroyUserDataLI(volumeUuid, userId, flags);
20447            }
20448        }
20449    }
20450
20451    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20452        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20453        try {
20454            // Clean up app data, profile data, and media data
20455            mInstaller.destroyUserData(volumeUuid, userId, flags);
20456
20457            // Clean up system data
20458            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20459                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20460                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20461                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20462                }
20463                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20464                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20465                }
20466            }
20467
20468            // Data with special labels is now gone, so finish the job
20469            storage.destroyUserStorage(volumeUuid, userId, flags);
20470
20471        } catch (Exception e) {
20472            logCriticalInfo(Log.WARN,
20473                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20474        }
20475    }
20476
20477    /**
20478     * Examine all users present on given mounted volume, and destroy data
20479     * belonging to users that are no longer valid, or whose user ID has been
20480     * recycled.
20481     */
20482    private void reconcileUsers(String volumeUuid) {
20483        final List<File> files = new ArrayList<>();
20484        Collections.addAll(files, FileUtils
20485                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20486        Collections.addAll(files, FileUtils
20487                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20488        Collections.addAll(files, FileUtils
20489                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20490        Collections.addAll(files, FileUtils
20491                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20492        for (File file : files) {
20493            if (!file.isDirectory()) continue;
20494
20495            final int userId;
20496            final UserInfo info;
20497            try {
20498                userId = Integer.parseInt(file.getName());
20499                info = sUserManager.getUserInfo(userId);
20500            } catch (NumberFormatException e) {
20501                Slog.w(TAG, "Invalid user directory " + file);
20502                continue;
20503            }
20504
20505            boolean destroyUser = false;
20506            if (info == null) {
20507                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20508                        + " because no matching user was found");
20509                destroyUser = true;
20510            } else if (!mOnlyCore) {
20511                try {
20512                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20513                } catch (IOException e) {
20514                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20515                            + " because we failed to enforce serial number: " + e);
20516                    destroyUser = true;
20517                }
20518            }
20519
20520            if (destroyUser) {
20521                synchronized (mInstallLock) {
20522                    destroyUserDataLI(volumeUuid, userId,
20523                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20524                }
20525            }
20526        }
20527    }
20528
20529    private void assertPackageKnown(String volumeUuid, String packageName)
20530            throws PackageManagerException {
20531        synchronized (mPackages) {
20532            // Normalize package name to handle renamed packages
20533            packageName = normalizePackageNameLPr(packageName);
20534
20535            final PackageSetting ps = mSettings.mPackages.get(packageName);
20536            if (ps == null) {
20537                throw new PackageManagerException("Package " + packageName + " is unknown");
20538            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20539                throw new PackageManagerException(
20540                        "Package " + packageName + " found on unknown volume " + volumeUuid
20541                                + "; expected volume " + ps.volumeUuid);
20542            }
20543        }
20544    }
20545
20546    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20547            throws PackageManagerException {
20548        synchronized (mPackages) {
20549            // Normalize package name to handle renamed packages
20550            packageName = normalizePackageNameLPr(packageName);
20551
20552            final PackageSetting ps = mSettings.mPackages.get(packageName);
20553            if (ps == null) {
20554                throw new PackageManagerException("Package " + packageName + " is unknown");
20555            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20556                throw new PackageManagerException(
20557                        "Package " + packageName + " found on unknown volume " + volumeUuid
20558                                + "; expected volume " + ps.volumeUuid);
20559            } else if (!ps.getInstalled(userId)) {
20560                throw new PackageManagerException(
20561                        "Package " + packageName + " not installed for user " + userId);
20562            }
20563        }
20564    }
20565
20566    /**
20567     * Examine all apps present on given mounted volume, and destroy apps that
20568     * aren't expected, either due to uninstallation or reinstallation on
20569     * another volume.
20570     */
20571    private void reconcileApps(String volumeUuid) {
20572        final File[] files = FileUtils
20573                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20574        for (File file : files) {
20575            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20576                    && !PackageInstallerService.isStageName(file.getName());
20577            if (!isPackage) {
20578                // Ignore entries which are not packages
20579                continue;
20580            }
20581
20582            try {
20583                final PackageLite pkg = PackageParser.parsePackageLite(file,
20584                        PackageParser.PARSE_MUST_BE_APK);
20585                assertPackageKnown(volumeUuid, pkg.packageName);
20586
20587            } catch (PackageParserException | PackageManagerException e) {
20588                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20589                synchronized (mInstallLock) {
20590                    removeCodePathLI(file);
20591                }
20592            }
20593        }
20594    }
20595
20596    /**
20597     * Reconcile all app data for the given user.
20598     * <p>
20599     * Verifies that directories exist and that ownership and labeling is
20600     * correct for all installed apps on all mounted volumes.
20601     */
20602    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20603        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20604        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20605            final String volumeUuid = vol.getFsUuid();
20606            synchronized (mInstallLock) {
20607                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20608            }
20609        }
20610    }
20611
20612    /**
20613     * Reconcile all app data on given mounted volume.
20614     * <p>
20615     * Destroys app data that isn't expected, either due to uninstallation or
20616     * reinstallation on another volume.
20617     * <p>
20618     * Verifies that directories exist and that ownership and labeling is
20619     * correct for all installed apps.
20620     */
20621    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20622            boolean migrateAppData) {
20623        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20624                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20625
20626        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20627        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20628
20629        // First look for stale data that doesn't belong, and check if things
20630        // have changed since we did our last restorecon
20631        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20632            if (StorageManager.isFileEncryptedNativeOrEmulated()
20633                    && !StorageManager.isUserKeyUnlocked(userId)) {
20634                throw new RuntimeException(
20635                        "Yikes, someone asked us to reconcile CE storage while " + userId
20636                                + " was still locked; this would have caused massive data loss!");
20637            }
20638
20639            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20640            for (File file : files) {
20641                final String packageName = file.getName();
20642                try {
20643                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20644                } catch (PackageManagerException e) {
20645                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20646                    try {
20647                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20648                                StorageManager.FLAG_STORAGE_CE, 0);
20649                    } catch (InstallerException e2) {
20650                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20651                    }
20652                }
20653            }
20654        }
20655        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20656            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20657            for (File file : files) {
20658                final String packageName = file.getName();
20659                try {
20660                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20661                } catch (PackageManagerException e) {
20662                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20663                    try {
20664                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20665                                StorageManager.FLAG_STORAGE_DE, 0);
20666                    } catch (InstallerException e2) {
20667                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20668                    }
20669                }
20670            }
20671        }
20672
20673        // Ensure that data directories are ready to roll for all packages
20674        // installed for this volume and user
20675        final List<PackageSetting> packages;
20676        synchronized (mPackages) {
20677            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20678        }
20679        int preparedCount = 0;
20680        for (PackageSetting ps : packages) {
20681            final String packageName = ps.name;
20682            if (ps.pkg == null) {
20683                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20684                // TODO: might be due to legacy ASEC apps; we should circle back
20685                // and reconcile again once they're scanned
20686                continue;
20687            }
20688
20689            if (ps.getInstalled(userId)) {
20690                prepareAppDataLIF(ps.pkg, userId, flags);
20691
20692                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20693                    // We may have just shuffled around app data directories, so
20694                    // prepare them one more time
20695                    prepareAppDataLIF(ps.pkg, userId, flags);
20696                }
20697
20698                preparedCount++;
20699            }
20700        }
20701
20702        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20703    }
20704
20705    /**
20706     * Prepare app data for the given app just after it was installed or
20707     * upgraded. This method carefully only touches users that it's installed
20708     * for, and it forces a restorecon to handle any seinfo changes.
20709     * <p>
20710     * Verifies that directories exist and that ownership and labeling is
20711     * correct for all installed apps. If there is an ownership mismatch, it
20712     * will try recovering system apps by wiping data; third-party app data is
20713     * left intact.
20714     * <p>
20715     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20716     */
20717    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20718        final PackageSetting ps;
20719        synchronized (mPackages) {
20720            ps = mSettings.mPackages.get(pkg.packageName);
20721            mSettings.writeKernelMappingLPr(ps);
20722        }
20723
20724        final UserManager um = mContext.getSystemService(UserManager.class);
20725        UserManagerInternal umInternal = getUserManagerInternal();
20726        for (UserInfo user : um.getUsers()) {
20727            final int flags;
20728            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20729                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20730            } else if (umInternal.isUserRunning(user.id)) {
20731                flags = StorageManager.FLAG_STORAGE_DE;
20732            } else {
20733                continue;
20734            }
20735
20736            if (ps.getInstalled(user.id)) {
20737                // TODO: when user data is locked, mark that we're still dirty
20738                prepareAppDataLIF(pkg, user.id, flags);
20739            }
20740        }
20741    }
20742
20743    /**
20744     * Prepare app data for the given app.
20745     * <p>
20746     * Verifies that directories exist and that ownership and labeling is
20747     * correct for all installed apps. If there is an ownership mismatch, this
20748     * will try recovering system apps by wiping data; third-party app data is
20749     * left intact.
20750     */
20751    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20752        if (pkg == null) {
20753            Slog.wtf(TAG, "Package was null!", new Throwable());
20754            return;
20755        }
20756        prepareAppDataLeafLIF(pkg, userId, flags);
20757        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20758        for (int i = 0; i < childCount; i++) {
20759            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20760        }
20761    }
20762
20763    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20764        if (DEBUG_APP_DATA) {
20765            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20766                    + Integer.toHexString(flags));
20767        }
20768
20769        final String volumeUuid = pkg.volumeUuid;
20770        final String packageName = pkg.packageName;
20771        final ApplicationInfo app = pkg.applicationInfo;
20772        final int appId = UserHandle.getAppId(app.uid);
20773
20774        Preconditions.checkNotNull(app.seinfo);
20775
20776        long ceDataInode = -1;
20777        try {
20778            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20779                    appId, app.seinfo, app.targetSdkVersion);
20780        } catch (InstallerException e) {
20781            if (app.isSystemApp()) {
20782                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20783                        + ", but trying to recover: " + e);
20784                destroyAppDataLeafLIF(pkg, userId, flags);
20785                try {
20786                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20787                            appId, app.seinfo, app.targetSdkVersion);
20788                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20789                } catch (InstallerException e2) {
20790                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20791                }
20792            } else {
20793                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20794            }
20795        }
20796
20797        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20798            // TODO: mark this structure as dirty so we persist it!
20799            synchronized (mPackages) {
20800                final PackageSetting ps = mSettings.mPackages.get(packageName);
20801                if (ps != null) {
20802                    ps.setCeDataInode(ceDataInode, userId);
20803                }
20804            }
20805        }
20806
20807        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20808    }
20809
20810    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20811        if (pkg == null) {
20812            Slog.wtf(TAG, "Package was null!", new Throwable());
20813            return;
20814        }
20815        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20816        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20817        for (int i = 0; i < childCount; i++) {
20818            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20819        }
20820    }
20821
20822    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20823        final String volumeUuid = pkg.volumeUuid;
20824        final String packageName = pkg.packageName;
20825        final ApplicationInfo app = pkg.applicationInfo;
20826
20827        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20828            // Create a native library symlink only if we have native libraries
20829            // and if the native libraries are 32 bit libraries. We do not provide
20830            // this symlink for 64 bit libraries.
20831            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20832                final String nativeLibPath = app.nativeLibraryDir;
20833                try {
20834                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20835                            nativeLibPath, userId);
20836                } catch (InstallerException e) {
20837                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20838                }
20839            }
20840        }
20841    }
20842
20843    /**
20844     * For system apps on non-FBE devices, this method migrates any existing
20845     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20846     * requested by the app.
20847     */
20848    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20849        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20850                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20851            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20852                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20853            try {
20854                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20855                        storageTarget);
20856            } catch (InstallerException e) {
20857                logCriticalInfo(Log.WARN,
20858                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20859            }
20860            return true;
20861        } else {
20862            return false;
20863        }
20864    }
20865
20866    public PackageFreezer freezePackage(String packageName, String killReason) {
20867        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20868    }
20869
20870    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20871        return new PackageFreezer(packageName, userId, killReason);
20872    }
20873
20874    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20875            String killReason) {
20876        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20877    }
20878
20879    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20880            String killReason) {
20881        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20882            return new PackageFreezer();
20883        } else {
20884            return freezePackage(packageName, userId, killReason);
20885        }
20886    }
20887
20888    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20889            String killReason) {
20890        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20891    }
20892
20893    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20894            String killReason) {
20895        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20896            return new PackageFreezer();
20897        } else {
20898            return freezePackage(packageName, userId, killReason);
20899        }
20900    }
20901
20902    /**
20903     * Class that freezes and kills the given package upon creation, and
20904     * unfreezes it upon closing. This is typically used when doing surgery on
20905     * app code/data to prevent the app from running while you're working.
20906     */
20907    private class PackageFreezer implements AutoCloseable {
20908        private final String mPackageName;
20909        private final PackageFreezer[] mChildren;
20910
20911        private final boolean mWeFroze;
20912
20913        private final AtomicBoolean mClosed = new AtomicBoolean();
20914        private final CloseGuard mCloseGuard = CloseGuard.get();
20915
20916        /**
20917         * Create and return a stub freezer that doesn't actually do anything,
20918         * typically used when someone requested
20919         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20920         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20921         */
20922        public PackageFreezer() {
20923            mPackageName = null;
20924            mChildren = null;
20925            mWeFroze = false;
20926            mCloseGuard.open("close");
20927        }
20928
20929        public PackageFreezer(String packageName, int userId, String killReason) {
20930            synchronized (mPackages) {
20931                mPackageName = packageName;
20932                mWeFroze = mFrozenPackages.add(mPackageName);
20933
20934                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20935                if (ps != null) {
20936                    killApplication(ps.name, ps.appId, userId, killReason);
20937                }
20938
20939                final PackageParser.Package p = mPackages.get(packageName);
20940                if (p != null && p.childPackages != null) {
20941                    final int N = p.childPackages.size();
20942                    mChildren = new PackageFreezer[N];
20943                    for (int i = 0; i < N; i++) {
20944                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20945                                userId, killReason);
20946                    }
20947                } else {
20948                    mChildren = null;
20949                }
20950            }
20951            mCloseGuard.open("close");
20952        }
20953
20954        @Override
20955        protected void finalize() throws Throwable {
20956            try {
20957                mCloseGuard.warnIfOpen();
20958                close();
20959            } finally {
20960                super.finalize();
20961            }
20962        }
20963
20964        @Override
20965        public void close() {
20966            mCloseGuard.close();
20967            if (mClosed.compareAndSet(false, true)) {
20968                synchronized (mPackages) {
20969                    if (mWeFroze) {
20970                        mFrozenPackages.remove(mPackageName);
20971                    }
20972
20973                    if (mChildren != null) {
20974                        for (PackageFreezer freezer : mChildren) {
20975                            freezer.close();
20976                        }
20977                    }
20978                }
20979            }
20980        }
20981    }
20982
20983    /**
20984     * Verify that given package is currently frozen.
20985     */
20986    private void checkPackageFrozen(String packageName) {
20987        synchronized (mPackages) {
20988            if (!mFrozenPackages.contains(packageName)) {
20989                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20990            }
20991        }
20992    }
20993
20994    @Override
20995    public int movePackage(final String packageName, final String volumeUuid) {
20996        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20997
20998        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20999        final int moveId = mNextMoveId.getAndIncrement();
21000        mHandler.post(new Runnable() {
21001            @Override
21002            public void run() {
21003                try {
21004                    movePackageInternal(packageName, volumeUuid, moveId, user);
21005                } catch (PackageManagerException e) {
21006                    Slog.w(TAG, "Failed to move " + packageName, e);
21007                    mMoveCallbacks.notifyStatusChanged(moveId,
21008                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21009                }
21010            }
21011        });
21012        return moveId;
21013    }
21014
21015    private void movePackageInternal(final String packageName, final String volumeUuid,
21016            final int moveId, UserHandle user) throws PackageManagerException {
21017        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21018        final PackageManager pm = mContext.getPackageManager();
21019
21020        final boolean currentAsec;
21021        final String currentVolumeUuid;
21022        final File codeFile;
21023        final String installerPackageName;
21024        final String packageAbiOverride;
21025        final int appId;
21026        final String seinfo;
21027        final String label;
21028        final int targetSdkVersion;
21029        final PackageFreezer freezer;
21030        final int[] installedUserIds;
21031
21032        // reader
21033        synchronized (mPackages) {
21034            final PackageParser.Package pkg = mPackages.get(packageName);
21035            final PackageSetting ps = mSettings.mPackages.get(packageName);
21036            if (pkg == null || ps == null) {
21037                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21038            }
21039
21040            if (pkg.applicationInfo.isSystemApp()) {
21041                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21042                        "Cannot move system application");
21043            }
21044
21045            if (pkg.applicationInfo.isExternalAsec()) {
21046                currentAsec = true;
21047                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21048            } else if (pkg.applicationInfo.isForwardLocked()) {
21049                currentAsec = true;
21050                currentVolumeUuid = "forward_locked";
21051            } else {
21052                currentAsec = false;
21053                currentVolumeUuid = ps.volumeUuid;
21054
21055                final File probe = new File(pkg.codePath);
21056                final File probeOat = new File(probe, "oat");
21057                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21058                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21059                            "Move only supported for modern cluster style installs");
21060                }
21061            }
21062
21063            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21064                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21065                        "Package already moved to " + volumeUuid);
21066            }
21067            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21068                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21069                        "Device admin cannot be moved");
21070            }
21071
21072            if (mFrozenPackages.contains(packageName)) {
21073                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21074                        "Failed to move already frozen package");
21075            }
21076
21077            codeFile = new File(pkg.codePath);
21078            installerPackageName = ps.installerPackageName;
21079            packageAbiOverride = ps.cpuAbiOverrideString;
21080            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21081            seinfo = pkg.applicationInfo.seinfo;
21082            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21083            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21084            freezer = freezePackage(packageName, "movePackageInternal");
21085            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21086        }
21087
21088        final Bundle extras = new Bundle();
21089        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21090        extras.putString(Intent.EXTRA_TITLE, label);
21091        mMoveCallbacks.notifyCreated(moveId, extras);
21092
21093        int installFlags;
21094        final boolean moveCompleteApp;
21095        final File measurePath;
21096
21097        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21098            installFlags = INSTALL_INTERNAL;
21099            moveCompleteApp = !currentAsec;
21100            measurePath = Environment.getDataAppDirectory(volumeUuid);
21101        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21102            installFlags = INSTALL_EXTERNAL;
21103            moveCompleteApp = false;
21104            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21105        } else {
21106            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21107            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21108                    || !volume.isMountedWritable()) {
21109                freezer.close();
21110                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21111                        "Move location not mounted private volume");
21112            }
21113
21114            Preconditions.checkState(!currentAsec);
21115
21116            installFlags = INSTALL_INTERNAL;
21117            moveCompleteApp = true;
21118            measurePath = Environment.getDataAppDirectory(volumeUuid);
21119        }
21120
21121        final PackageStats stats = new PackageStats(null, -1);
21122        synchronized (mInstaller) {
21123            for (int userId : installedUserIds) {
21124                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21125                    freezer.close();
21126                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21127                            "Failed to measure package size");
21128                }
21129            }
21130        }
21131
21132        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21133                + stats.dataSize);
21134
21135        final long startFreeBytes = measurePath.getFreeSpace();
21136        final long sizeBytes;
21137        if (moveCompleteApp) {
21138            sizeBytes = stats.codeSize + stats.dataSize;
21139        } else {
21140            sizeBytes = stats.codeSize;
21141        }
21142
21143        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21144            freezer.close();
21145            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21146                    "Not enough free space to move");
21147        }
21148
21149        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21150
21151        final CountDownLatch installedLatch = new CountDownLatch(1);
21152        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21153            @Override
21154            public void onUserActionRequired(Intent intent) throws RemoteException {
21155                throw new IllegalStateException();
21156            }
21157
21158            @Override
21159            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21160                    Bundle extras) throws RemoteException {
21161                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21162                        + PackageManager.installStatusToString(returnCode, msg));
21163
21164                installedLatch.countDown();
21165                freezer.close();
21166
21167                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21168                switch (status) {
21169                    case PackageInstaller.STATUS_SUCCESS:
21170                        mMoveCallbacks.notifyStatusChanged(moveId,
21171                                PackageManager.MOVE_SUCCEEDED);
21172                        break;
21173                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21174                        mMoveCallbacks.notifyStatusChanged(moveId,
21175                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21176                        break;
21177                    default:
21178                        mMoveCallbacks.notifyStatusChanged(moveId,
21179                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21180                        break;
21181                }
21182            }
21183        };
21184
21185        final MoveInfo move;
21186        if (moveCompleteApp) {
21187            // Kick off a thread to report progress estimates
21188            new Thread() {
21189                @Override
21190                public void run() {
21191                    while (true) {
21192                        try {
21193                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21194                                break;
21195                            }
21196                        } catch (InterruptedException ignored) {
21197                        }
21198
21199                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
21200                        final int progress = 10 + (int) MathUtils.constrain(
21201                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21202                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21203                    }
21204                }
21205            }.start();
21206
21207            final String dataAppName = codeFile.getName();
21208            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21209                    dataAppName, appId, seinfo, targetSdkVersion);
21210        } else {
21211            move = null;
21212        }
21213
21214        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21215
21216        final Message msg = mHandler.obtainMessage(INIT_COPY);
21217        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21218        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21219                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21220                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21221                PackageManager.INSTALL_REASON_UNKNOWN);
21222        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21223        msg.obj = params;
21224
21225        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21226                System.identityHashCode(msg.obj));
21227        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21228                System.identityHashCode(msg.obj));
21229
21230        mHandler.sendMessage(msg);
21231    }
21232
21233    @Override
21234    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21235        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21236
21237        final int realMoveId = mNextMoveId.getAndIncrement();
21238        final Bundle extras = new Bundle();
21239        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21240        mMoveCallbacks.notifyCreated(realMoveId, extras);
21241
21242        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21243            @Override
21244            public void onCreated(int moveId, Bundle extras) {
21245                // Ignored
21246            }
21247
21248            @Override
21249            public void onStatusChanged(int moveId, int status, long estMillis) {
21250                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21251            }
21252        };
21253
21254        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21255        storage.setPrimaryStorageUuid(volumeUuid, callback);
21256        return realMoveId;
21257    }
21258
21259    @Override
21260    public int getMoveStatus(int moveId) {
21261        mContext.enforceCallingOrSelfPermission(
21262                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21263        return mMoveCallbacks.mLastStatus.get(moveId);
21264    }
21265
21266    @Override
21267    public void registerMoveCallback(IPackageMoveObserver callback) {
21268        mContext.enforceCallingOrSelfPermission(
21269                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21270        mMoveCallbacks.register(callback);
21271    }
21272
21273    @Override
21274    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21275        mContext.enforceCallingOrSelfPermission(
21276                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21277        mMoveCallbacks.unregister(callback);
21278    }
21279
21280    @Override
21281    public boolean setInstallLocation(int loc) {
21282        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21283                null);
21284        if (getInstallLocation() == loc) {
21285            return true;
21286        }
21287        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21288                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21289            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21290                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21291            return true;
21292        }
21293        return false;
21294   }
21295
21296    @Override
21297    public int getInstallLocation() {
21298        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21299                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21300                PackageHelper.APP_INSTALL_AUTO);
21301    }
21302
21303    /** Called by UserManagerService */
21304    void cleanUpUser(UserManagerService userManager, int userHandle) {
21305        synchronized (mPackages) {
21306            mDirtyUsers.remove(userHandle);
21307            mUserNeedsBadging.delete(userHandle);
21308            mSettings.removeUserLPw(userHandle);
21309            mPendingBroadcasts.remove(userHandle);
21310            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21311            removeUnusedPackagesLPw(userManager, userHandle);
21312        }
21313    }
21314
21315    /**
21316     * We're removing userHandle and would like to remove any downloaded packages
21317     * that are no longer in use by any other user.
21318     * @param userHandle the user being removed
21319     */
21320    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21321        final boolean DEBUG_CLEAN_APKS = false;
21322        int [] users = userManager.getUserIds();
21323        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21324        while (psit.hasNext()) {
21325            PackageSetting ps = psit.next();
21326            if (ps.pkg == null) {
21327                continue;
21328            }
21329            final String packageName = ps.pkg.packageName;
21330            // Skip over if system app
21331            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21332                continue;
21333            }
21334            if (DEBUG_CLEAN_APKS) {
21335                Slog.i(TAG, "Checking package " + packageName);
21336            }
21337            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21338            if (keep) {
21339                if (DEBUG_CLEAN_APKS) {
21340                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21341                }
21342            } else {
21343                for (int i = 0; i < users.length; i++) {
21344                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21345                        keep = true;
21346                        if (DEBUG_CLEAN_APKS) {
21347                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21348                                    + users[i]);
21349                        }
21350                        break;
21351                    }
21352                }
21353            }
21354            if (!keep) {
21355                if (DEBUG_CLEAN_APKS) {
21356                    Slog.i(TAG, "  Removing package " + packageName);
21357                }
21358                mHandler.post(new Runnable() {
21359                    public void run() {
21360                        deletePackageX(packageName, userHandle, 0);
21361                    } //end run
21362                });
21363            }
21364        }
21365    }
21366
21367    /** Called by UserManagerService */
21368    void createNewUser(int userId, String[] disallowedPackages) {
21369        synchronized (mInstallLock) {
21370            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21371        }
21372        synchronized (mPackages) {
21373            scheduleWritePackageRestrictionsLocked(userId);
21374            scheduleWritePackageListLocked(userId);
21375            applyFactoryDefaultBrowserLPw(userId);
21376            primeDomainVerificationsLPw(userId);
21377        }
21378    }
21379
21380    void onNewUserCreated(final int userId) {
21381        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21382        // If permission review for legacy apps is required, we represent
21383        // dagerous permissions for such apps as always granted runtime
21384        // permissions to keep per user flag state whether review is needed.
21385        // Hence, if a new user is added we have to propagate dangerous
21386        // permission grants for these legacy apps.
21387        if (mPermissionReviewRequired) {
21388            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21389                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21390        }
21391    }
21392
21393    @Override
21394    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21395        mContext.enforceCallingOrSelfPermission(
21396                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21397                "Only package verification agents can read the verifier device identity");
21398
21399        synchronized (mPackages) {
21400            return mSettings.getVerifierDeviceIdentityLPw();
21401        }
21402    }
21403
21404    @Override
21405    public void setPermissionEnforced(String permission, boolean enforced) {
21406        // TODO: Now that we no longer change GID for storage, this should to away.
21407        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21408                "setPermissionEnforced");
21409        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21410            synchronized (mPackages) {
21411                if (mSettings.mReadExternalStorageEnforced == null
21412                        || mSettings.mReadExternalStorageEnforced != enforced) {
21413                    mSettings.mReadExternalStorageEnforced = enforced;
21414                    mSettings.writeLPr();
21415                }
21416            }
21417            // kill any non-foreground processes so we restart them and
21418            // grant/revoke the GID.
21419            final IActivityManager am = ActivityManager.getService();
21420            if (am != null) {
21421                final long token = Binder.clearCallingIdentity();
21422                try {
21423                    am.killProcessesBelowForeground("setPermissionEnforcement");
21424                } catch (RemoteException e) {
21425                } finally {
21426                    Binder.restoreCallingIdentity(token);
21427                }
21428            }
21429        } else {
21430            throw new IllegalArgumentException("No selective enforcement for " + permission);
21431        }
21432    }
21433
21434    @Override
21435    @Deprecated
21436    public boolean isPermissionEnforced(String permission) {
21437        return true;
21438    }
21439
21440    @Override
21441    public boolean isStorageLow() {
21442        final long token = Binder.clearCallingIdentity();
21443        try {
21444            final DeviceStorageMonitorInternal
21445                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21446            if (dsm != null) {
21447                return dsm.isMemoryLow();
21448            } else {
21449                return false;
21450            }
21451        } finally {
21452            Binder.restoreCallingIdentity(token);
21453        }
21454    }
21455
21456    @Override
21457    public IPackageInstaller getPackageInstaller() {
21458        return mInstallerService;
21459    }
21460
21461    private boolean userNeedsBadging(int userId) {
21462        int index = mUserNeedsBadging.indexOfKey(userId);
21463        if (index < 0) {
21464            final UserInfo userInfo;
21465            final long token = Binder.clearCallingIdentity();
21466            try {
21467                userInfo = sUserManager.getUserInfo(userId);
21468            } finally {
21469                Binder.restoreCallingIdentity(token);
21470            }
21471            final boolean b;
21472            if (userInfo != null && userInfo.isManagedProfile()) {
21473                b = true;
21474            } else {
21475                b = false;
21476            }
21477            mUserNeedsBadging.put(userId, b);
21478            return b;
21479        }
21480        return mUserNeedsBadging.valueAt(index);
21481    }
21482
21483    @Override
21484    public KeySet getKeySetByAlias(String packageName, String alias) {
21485        if (packageName == null || alias == null) {
21486            return null;
21487        }
21488        synchronized(mPackages) {
21489            final PackageParser.Package pkg = mPackages.get(packageName);
21490            if (pkg == null) {
21491                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21492                throw new IllegalArgumentException("Unknown package: " + packageName);
21493            }
21494            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21495            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21496        }
21497    }
21498
21499    @Override
21500    public KeySet getSigningKeySet(String packageName) {
21501        if (packageName == null) {
21502            return null;
21503        }
21504        synchronized(mPackages) {
21505            final PackageParser.Package pkg = mPackages.get(packageName);
21506            if (pkg == null) {
21507                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21508                throw new IllegalArgumentException("Unknown package: " + packageName);
21509            }
21510            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21511                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21512                throw new SecurityException("May not access signing KeySet of other apps.");
21513            }
21514            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21515            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21516        }
21517    }
21518
21519    @Override
21520    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21521        if (packageName == null || ks == null) {
21522            return false;
21523        }
21524        synchronized(mPackages) {
21525            final PackageParser.Package pkg = mPackages.get(packageName);
21526            if (pkg == null) {
21527                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21528                throw new IllegalArgumentException("Unknown package: " + packageName);
21529            }
21530            IBinder ksh = ks.getToken();
21531            if (ksh instanceof KeySetHandle) {
21532                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21533                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21534            }
21535            return false;
21536        }
21537    }
21538
21539    @Override
21540    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21541        if (packageName == null || ks == null) {
21542            return false;
21543        }
21544        synchronized(mPackages) {
21545            final PackageParser.Package pkg = mPackages.get(packageName);
21546            if (pkg == null) {
21547                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21548                throw new IllegalArgumentException("Unknown package: " + packageName);
21549            }
21550            IBinder ksh = ks.getToken();
21551            if (ksh instanceof KeySetHandle) {
21552                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21553                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21554            }
21555            return false;
21556        }
21557    }
21558
21559    private void deletePackageIfUnusedLPr(final String packageName) {
21560        PackageSetting ps = mSettings.mPackages.get(packageName);
21561        if (ps == null) {
21562            return;
21563        }
21564        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21565            // TODO Implement atomic delete if package is unused
21566            // It is currently possible that the package will be deleted even if it is installed
21567            // after this method returns.
21568            mHandler.post(new Runnable() {
21569                public void run() {
21570                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21571                }
21572            });
21573        }
21574    }
21575
21576    /**
21577     * Check and throw if the given before/after packages would be considered a
21578     * downgrade.
21579     */
21580    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21581            throws PackageManagerException {
21582        if (after.versionCode < before.mVersionCode) {
21583            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21584                    "Update version code " + after.versionCode + " is older than current "
21585                    + before.mVersionCode);
21586        } else if (after.versionCode == before.mVersionCode) {
21587            if (after.baseRevisionCode < before.baseRevisionCode) {
21588                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21589                        "Update base revision code " + after.baseRevisionCode
21590                        + " is older than current " + before.baseRevisionCode);
21591            }
21592
21593            if (!ArrayUtils.isEmpty(after.splitNames)) {
21594                for (int i = 0; i < after.splitNames.length; i++) {
21595                    final String splitName = after.splitNames[i];
21596                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21597                    if (j != -1) {
21598                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21599                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21600                                    "Update split " + splitName + " revision code "
21601                                    + after.splitRevisionCodes[i] + " is older than current "
21602                                    + before.splitRevisionCodes[j]);
21603                        }
21604                    }
21605                }
21606            }
21607        }
21608    }
21609
21610    private static class MoveCallbacks extends Handler {
21611        private static final int MSG_CREATED = 1;
21612        private static final int MSG_STATUS_CHANGED = 2;
21613
21614        private final RemoteCallbackList<IPackageMoveObserver>
21615                mCallbacks = new RemoteCallbackList<>();
21616
21617        private final SparseIntArray mLastStatus = new SparseIntArray();
21618
21619        public MoveCallbacks(Looper looper) {
21620            super(looper);
21621        }
21622
21623        public void register(IPackageMoveObserver callback) {
21624            mCallbacks.register(callback);
21625        }
21626
21627        public void unregister(IPackageMoveObserver callback) {
21628            mCallbacks.unregister(callback);
21629        }
21630
21631        @Override
21632        public void handleMessage(Message msg) {
21633            final SomeArgs args = (SomeArgs) msg.obj;
21634            final int n = mCallbacks.beginBroadcast();
21635            for (int i = 0; i < n; i++) {
21636                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21637                try {
21638                    invokeCallback(callback, msg.what, args);
21639                } catch (RemoteException ignored) {
21640                }
21641            }
21642            mCallbacks.finishBroadcast();
21643            args.recycle();
21644        }
21645
21646        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21647                throws RemoteException {
21648            switch (what) {
21649                case MSG_CREATED: {
21650                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21651                    break;
21652                }
21653                case MSG_STATUS_CHANGED: {
21654                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21655                    break;
21656                }
21657            }
21658        }
21659
21660        private void notifyCreated(int moveId, Bundle extras) {
21661            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21662
21663            final SomeArgs args = SomeArgs.obtain();
21664            args.argi1 = moveId;
21665            args.arg2 = extras;
21666            obtainMessage(MSG_CREATED, args).sendToTarget();
21667        }
21668
21669        private void notifyStatusChanged(int moveId, int status) {
21670            notifyStatusChanged(moveId, status, -1);
21671        }
21672
21673        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21674            Slog.v(TAG, "Move " + moveId + " status " + status);
21675
21676            final SomeArgs args = SomeArgs.obtain();
21677            args.argi1 = moveId;
21678            args.argi2 = status;
21679            args.arg3 = estMillis;
21680            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21681
21682            synchronized (mLastStatus) {
21683                mLastStatus.put(moveId, status);
21684            }
21685        }
21686    }
21687
21688    private final static class OnPermissionChangeListeners extends Handler {
21689        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21690
21691        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21692                new RemoteCallbackList<>();
21693
21694        public OnPermissionChangeListeners(Looper looper) {
21695            super(looper);
21696        }
21697
21698        @Override
21699        public void handleMessage(Message msg) {
21700            switch (msg.what) {
21701                case MSG_ON_PERMISSIONS_CHANGED: {
21702                    final int uid = msg.arg1;
21703                    handleOnPermissionsChanged(uid);
21704                } break;
21705            }
21706        }
21707
21708        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21709            mPermissionListeners.register(listener);
21710
21711        }
21712
21713        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21714            mPermissionListeners.unregister(listener);
21715        }
21716
21717        public void onPermissionsChanged(int uid) {
21718            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21719                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21720            }
21721        }
21722
21723        private void handleOnPermissionsChanged(int uid) {
21724            final int count = mPermissionListeners.beginBroadcast();
21725            try {
21726                for (int i = 0; i < count; i++) {
21727                    IOnPermissionsChangeListener callback = mPermissionListeners
21728                            .getBroadcastItem(i);
21729                    try {
21730                        callback.onPermissionsChanged(uid);
21731                    } catch (RemoteException e) {
21732                        Log.e(TAG, "Permission listener is dead", e);
21733                    }
21734                }
21735            } finally {
21736                mPermissionListeners.finishBroadcast();
21737            }
21738        }
21739    }
21740
21741    private class PackageManagerInternalImpl extends PackageManagerInternal {
21742        @Override
21743        public void setLocationPackagesProvider(PackagesProvider provider) {
21744            synchronized (mPackages) {
21745                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21746            }
21747        }
21748
21749        @Override
21750        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21751            synchronized (mPackages) {
21752                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21753            }
21754        }
21755
21756        @Override
21757        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21758            synchronized (mPackages) {
21759                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21760            }
21761        }
21762
21763        @Override
21764        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21765            synchronized (mPackages) {
21766                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21767            }
21768        }
21769
21770        @Override
21771        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21772            synchronized (mPackages) {
21773                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21774            }
21775        }
21776
21777        @Override
21778        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21779            synchronized (mPackages) {
21780                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21781            }
21782        }
21783
21784        @Override
21785        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21786            synchronized (mPackages) {
21787                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21788                        packageName, userId);
21789            }
21790        }
21791
21792        @Override
21793        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21794            synchronized (mPackages) {
21795                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21796                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21797                        packageName, userId);
21798            }
21799        }
21800
21801        @Override
21802        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21803            synchronized (mPackages) {
21804                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21805                        packageName, userId);
21806            }
21807        }
21808
21809        @Override
21810        public void setKeepUninstalledPackages(final List<String> packageList) {
21811            Preconditions.checkNotNull(packageList);
21812            List<String> removedFromList = null;
21813            synchronized (mPackages) {
21814                if (mKeepUninstalledPackages != null) {
21815                    final int packagesCount = mKeepUninstalledPackages.size();
21816                    for (int i = 0; i < packagesCount; i++) {
21817                        String oldPackage = mKeepUninstalledPackages.get(i);
21818                        if (packageList != null && packageList.contains(oldPackage)) {
21819                            continue;
21820                        }
21821                        if (removedFromList == null) {
21822                            removedFromList = new ArrayList<>();
21823                        }
21824                        removedFromList.add(oldPackage);
21825                    }
21826                }
21827                mKeepUninstalledPackages = new ArrayList<>(packageList);
21828                if (removedFromList != null) {
21829                    final int removedCount = removedFromList.size();
21830                    for (int i = 0; i < removedCount; i++) {
21831                        deletePackageIfUnusedLPr(removedFromList.get(i));
21832                    }
21833                }
21834            }
21835        }
21836
21837        @Override
21838        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21839            synchronized (mPackages) {
21840                // If we do not support permission review, done.
21841                if (!mPermissionReviewRequired) {
21842                    return false;
21843                }
21844
21845                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21846                if (packageSetting == null) {
21847                    return false;
21848                }
21849
21850                // Permission review applies only to apps not supporting the new permission model.
21851                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21852                    return false;
21853                }
21854
21855                // Legacy apps have the permission and get user consent on launch.
21856                PermissionsState permissionsState = packageSetting.getPermissionsState();
21857                return permissionsState.isPermissionReviewRequired(userId);
21858            }
21859        }
21860
21861        @Override
21862        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21863            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21864        }
21865
21866        @Override
21867        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21868                int userId) {
21869            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21870        }
21871
21872        @Override
21873        public void setDeviceAndProfileOwnerPackages(
21874                int deviceOwnerUserId, String deviceOwnerPackage,
21875                SparseArray<String> profileOwnerPackages) {
21876            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21877                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21878        }
21879
21880        @Override
21881        public boolean isPackageDataProtected(int userId, String packageName) {
21882            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21883        }
21884
21885        @Override
21886        public boolean isPackageEphemeral(int userId, String packageName) {
21887            synchronized (mPackages) {
21888                PackageParser.Package p = mPackages.get(packageName);
21889                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21890            }
21891        }
21892
21893        @Override
21894        public boolean wasPackageEverLaunched(String packageName, int userId) {
21895            synchronized (mPackages) {
21896                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21897            }
21898        }
21899
21900        @Override
21901        public void grantRuntimePermission(String packageName, String name, int userId,
21902                boolean overridePolicy) {
21903            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21904                    overridePolicy);
21905        }
21906
21907        @Override
21908        public void revokeRuntimePermission(String packageName, String name, int userId,
21909                boolean overridePolicy) {
21910            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21911                    overridePolicy);
21912        }
21913
21914        @Override
21915        public String getNameForUid(int uid) {
21916            return PackageManagerService.this.getNameForUid(uid);
21917        }
21918
21919        @Override
21920        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21921                Intent origIntent, String resolvedType, Intent launchIntent,
21922                String callingPackage, int userId) {
21923            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21924                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21925        }
21926
21927        public String getSetupWizardPackageName() {
21928            return mSetupWizardPackage;
21929        }
21930    }
21931
21932    @Override
21933    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21934        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21935        synchronized (mPackages) {
21936            final long identity = Binder.clearCallingIdentity();
21937            try {
21938                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21939                        packageNames, userId);
21940            } finally {
21941                Binder.restoreCallingIdentity(identity);
21942            }
21943        }
21944    }
21945
21946    private static void enforceSystemOrPhoneCaller(String tag) {
21947        int callingUid = Binder.getCallingUid();
21948        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21949            throw new SecurityException(
21950                    "Cannot call " + tag + " from UID " + callingUid);
21951        }
21952    }
21953
21954    boolean isHistoricalPackageUsageAvailable() {
21955        return mPackageUsage.isHistoricalPackageUsageAvailable();
21956    }
21957
21958    /**
21959     * Return a <b>copy</b> of the collection of packages known to the package manager.
21960     * @return A copy of the values of mPackages.
21961     */
21962    Collection<PackageParser.Package> getPackages() {
21963        synchronized (mPackages) {
21964            return new ArrayList<>(mPackages.values());
21965        }
21966    }
21967
21968    /**
21969     * Logs process start information (including base APK hash) to the security log.
21970     * @hide
21971     */
21972    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21973            String apkFile, int pid) {
21974        if (!SecurityLog.isLoggingEnabled()) {
21975            return;
21976        }
21977        Bundle data = new Bundle();
21978        data.putLong("startTimestamp", System.currentTimeMillis());
21979        data.putString("processName", processName);
21980        data.putInt("uid", uid);
21981        data.putString("seinfo", seinfo);
21982        data.putString("apkFile", apkFile);
21983        data.putInt("pid", pid);
21984        Message msg = mProcessLoggingHandler.obtainMessage(
21985                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21986        msg.setData(data);
21987        mProcessLoggingHandler.sendMessage(msg);
21988    }
21989
21990    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21991        return mCompilerStats.getPackageStats(pkgName);
21992    }
21993
21994    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21995        return getOrCreateCompilerPackageStats(pkg.packageName);
21996    }
21997
21998    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21999        return mCompilerStats.getOrCreatePackageStats(pkgName);
22000    }
22001
22002    public void deleteCompilerPackageStats(String pkgName) {
22003        mCompilerStats.deletePackageStats(pkgName);
22004    }
22005
22006    @Override
22007    public int getInstallReason(String packageName, int userId) {
22008        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22009                true /* requireFullPermission */, false /* checkShell */,
22010                "get install reason");
22011        synchronized (mPackages) {
22012            final PackageSetting ps = mSettings.mPackages.get(packageName);
22013            if (ps != null) {
22014                return ps.getInstallReason(userId);
22015            }
22016        }
22017        return PackageManager.INSTALL_REASON_UNKNOWN;
22018    }
22019}
22020