PackageManagerService.java revision 21f778060badb1e78bffde05e8de7662d275003d
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;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.app.ActivityManager;
105import android.app.AppOpsManager;
106import android.app.IActivityManager;
107import android.app.ResourcesManager;
108import android.app.admin.IDevicePolicyManager;
109import android.app.admin.SecurityLog;
110import android.app.backup.IBackupManager;
111import android.content.BroadcastReceiver;
112import android.content.ComponentName;
113import android.content.ContentResolver;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralRequest;
127import android.content.pm.EphemeralResolveInfo;
128import android.content.pm.EphemeralResponse;
129import android.content.pm.FallbackCategoryProvider;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.IntentFilterVerificationInfo;
142import android.content.pm.KeySet;
143import android.content.pm.PackageCleanItem;
144import android.content.pm.PackageInfo;
145import android.content.pm.PackageInfoLite;
146import android.content.pm.PackageInstaller;
147import android.content.pm.PackageManager;
148import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
149import android.content.pm.PackageManagerInternal;
150import android.content.pm.PackageParser;
151import android.content.pm.PackageParser.ActivityIntentInfo;
152import android.content.pm.PackageParser.PackageLite;
153import android.content.pm.PackageParser.PackageParserException;
154import android.content.pm.PackageStats;
155import android.content.pm.PackageUserState;
156import android.content.pm.ParceledListSlice;
157import android.content.pm.PermissionGroupInfo;
158import android.content.pm.PermissionInfo;
159import android.content.pm.ProviderInfo;
160import android.content.pm.ResolveInfo;
161import android.content.pm.ServiceInfo;
162import android.content.pm.Signature;
163import android.content.pm.UserInfo;
164import android.content.pm.VerifierDeviceIdentity;
165import android.content.pm.VerifierInfo;
166import android.content.res.Resources;
167import android.graphics.Bitmap;
168import android.hardware.display.DisplayManager;
169import android.net.Uri;
170import android.os.Binder;
171import android.os.Build;
172import android.os.Bundle;
173import android.os.Debug;
174import android.os.Environment;
175import android.os.Environment.UserEnvironment;
176import android.os.FileUtils;
177import android.os.Handler;
178import android.os.IBinder;
179import android.os.Looper;
180import android.os.Message;
181import android.os.Parcel;
182import android.os.ParcelFileDescriptor;
183import android.os.PatternMatcher;
184import android.os.Process;
185import android.os.RemoteCallbackList;
186import android.os.RemoteException;
187import android.os.ResultReceiver;
188import android.os.SELinux;
189import android.os.ServiceManager;
190import android.os.ShellCallback;
191import android.os.SystemClock;
192import android.os.SystemProperties;
193import android.os.Trace;
194import android.os.UserHandle;
195import android.os.UserManager;
196import android.os.UserManagerInternal;
197import android.os.storage.IStorageManager;
198import android.os.storage.StorageManagerInternal;
199import android.os.storage.StorageEventListener;
200import android.os.storage.StorageManager;
201import android.os.storage.VolumeInfo;
202import android.os.storage.VolumeRecord;
203import android.provider.Settings.Global;
204import android.provider.Settings.Secure;
205import android.security.KeyStore;
206import android.security.SystemKeyStore;
207import android.system.ErrnoException;
208import android.system.Os;
209import android.text.TextUtils;
210import android.text.format.DateUtils;
211import android.util.ArrayMap;
212import android.util.ArraySet;
213import android.util.Base64;
214import android.util.DisplayMetrics;
215import android.util.EventLog;
216import android.util.ExceptionUtils;
217import android.util.Log;
218import android.util.LogPrinter;
219import android.util.MathUtils;
220import android.util.Pair;
221import android.util.PrintStreamPrinter;
222import android.util.Slog;
223import android.util.SparseArray;
224import android.util.SparseBooleanArray;
225import android.util.SparseIntArray;
226import android.util.Xml;
227import android.util.jar.StrictJarFile;
228import android.view.Display;
229
230import com.android.internal.R;
231import com.android.internal.annotations.GuardedBy;
232import com.android.internal.app.IMediaContainerService;
233import com.android.internal.app.ResolverActivity;
234import com.android.internal.content.NativeLibraryHelper;
235import com.android.internal.content.PackageHelper;
236import com.android.internal.logging.MetricsLogger;
237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
238import com.android.internal.os.IParcelFileDescriptorFactory;
239import com.android.internal.os.RoSystemProperties;
240import com.android.internal.os.SomeArgs;
241import com.android.internal.os.Zygote;
242import com.android.internal.telephony.CarrierAppUtils;
243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
245import com.android.internal.util.FastXmlSerializer;
246import com.android.internal.util.IndentingPrintWriter;
247import com.android.internal.util.Preconditions;
248import com.android.internal.util.XmlUtils;
249import com.android.server.AttributeCache;
250import com.android.server.EventLogTags;
251import com.android.server.FgThread;
252import com.android.server.IntentResolver;
253import com.android.server.LocalServices;
254import com.android.server.ServiceThread;
255import com.android.server.SystemConfig;
256import com.android.server.Watchdog;
257import com.android.server.net.NetworkPolicyManagerInternal;
258import com.android.server.pm.Installer.InstallerException;
259import com.android.server.pm.PermissionsState.PermissionState;
260import com.android.server.pm.Settings.DatabaseVersion;
261import com.android.server.pm.Settings.VersionInfo;
262import com.android.server.pm.dex.DexManager;
263import com.android.server.storage.DeviceStorageMonitorInternal;
264
265import dalvik.system.CloseGuard;
266import dalvik.system.DexFile;
267import dalvik.system.VMRuntime;
268
269import libcore.io.IoUtils;
270import libcore.util.EmptyArray;
271
272import org.xmlpull.v1.XmlPullParser;
273import org.xmlpull.v1.XmlPullParserException;
274import org.xmlpull.v1.XmlSerializer;
275
276import java.io.BufferedOutputStream;
277import java.io.BufferedReader;
278import java.io.ByteArrayInputStream;
279import java.io.ByteArrayOutputStream;
280import java.io.File;
281import java.io.FileDescriptor;
282import java.io.FileInputStream;
283import java.io.FileNotFoundException;
284import java.io.FileOutputStream;
285import java.io.FileReader;
286import java.io.FilenameFilter;
287import java.io.IOException;
288import java.io.PrintWriter;
289import java.nio.charset.StandardCharsets;
290import java.security.DigestInputStream;
291import java.security.MessageDigest;
292import java.security.NoSuchAlgorithmException;
293import java.security.PublicKey;
294import java.security.SecureRandom;
295import java.security.cert.Certificate;
296import java.security.cert.CertificateEncodingException;
297import java.security.cert.CertificateException;
298import java.text.SimpleDateFormat;
299import java.util.ArrayList;
300import java.util.Arrays;
301import java.util.Collection;
302import java.util.Collections;
303import java.util.Comparator;
304import java.util.Date;
305import java.util.HashSet;
306import java.util.HashMap;
307import java.util.Iterator;
308import java.util.List;
309import java.util.Map;
310import java.util.Objects;
311import java.util.Set;
312import java.util.concurrent.CountDownLatch;
313import java.util.concurrent.TimeUnit;
314import java.util.concurrent.atomic.AtomicBoolean;
315import java.util.concurrent.atomic.AtomicInteger;
316
317/**
318 * Keep track of all those APKs everywhere.
319 * <p>
320 * Internally there are two important locks:
321 * <ul>
322 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
323 * and other related state. It is a fine-grained lock that should only be held
324 * momentarily, as it's one of the most contended locks in the system.
325 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
326 * operations typically involve heavy lifting of application data on disk. Since
327 * {@code installd} is single-threaded, and it's operations can often be slow,
328 * this lock should never be acquired while already holding {@link #mPackages}.
329 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
330 * holding {@link #mInstallLock}.
331 * </ul>
332 * Many internal methods rely on the caller to hold the appropriate locks, and
333 * this contract is expressed through method name suffixes:
334 * <ul>
335 * <li>fooLI(): the caller must hold {@link #mInstallLock}
336 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
337 * being modified must be frozen
338 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
339 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
340 * </ul>
341 * <p>
342 * Because this class is very central to the platform's security; please run all
343 * CTS and unit tests whenever making modifications:
344 *
345 * <pre>
346 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
347 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
348 * </pre>
349 */
350public class PackageManagerService extends IPackageManager.Stub {
351    static final String TAG = "PackageManager";
352    static final boolean DEBUG_SETTINGS = false;
353    static final boolean DEBUG_PREFERRED = false;
354    static final boolean DEBUG_UPGRADE = false;
355    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
356    private static final boolean DEBUG_BACKUP = false;
357    private static final boolean DEBUG_INSTALL = false;
358    private static final boolean DEBUG_REMOVE = false;
359    private static final boolean DEBUG_BROADCASTS = false;
360    private static final boolean DEBUG_SHOW_INFO = false;
361    private static final boolean DEBUG_PACKAGE_INFO = false;
362    private static final boolean DEBUG_INTENT_MATCHING = false;
363    private static final boolean DEBUG_PACKAGE_SCANNING = false;
364    private static final boolean DEBUG_VERIFY = false;
365    private static final boolean DEBUG_FILTERS = false;
366
367    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
368    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
369    // user, but by default initialize to this.
370    static final boolean DEBUG_DEXOPT = false;
371
372    private static final boolean DEBUG_ABI_SELECTION = false;
373    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
374    private static final boolean DEBUG_TRIAGED_MISSING = false;
375    private static final boolean DEBUG_APP_DATA = false;
376
377    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
378    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
379
380    private static final boolean DISABLE_EPHEMERAL_APPS = false;
381    private static final boolean HIDE_EPHEMERAL_APIS = true;
382
383    private static final boolean ENABLE_QUOTA =
384            SystemProperties.getBoolean("persist.fw.quota", false);
385
386    private static final int RADIO_UID = Process.PHONE_UID;
387    private static final int LOG_UID = Process.LOG_UID;
388    private static final int NFC_UID = Process.NFC_UID;
389    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
390    private static final int SHELL_UID = Process.SHELL_UID;
391
392    // Cap the size of permission trees that 3rd party apps can define
393    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
394
395    // Suffix used during package installation when copying/moving
396    // package apks to install directory.
397    private static final String INSTALL_PACKAGE_SUFFIX = "-";
398
399    static final int SCAN_NO_DEX = 1<<1;
400    static final int SCAN_FORCE_DEX = 1<<2;
401    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
402    static final int SCAN_NEW_INSTALL = 1<<4;
403    static final int SCAN_UPDATE_TIME = 1<<5;
404    static final int SCAN_BOOTING = 1<<6;
405    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
406    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
407    static final int SCAN_REPLACING = 1<<9;
408    static final int SCAN_REQUIRE_KNOWN = 1<<10;
409    static final int SCAN_MOVE = 1<<11;
410    static final int SCAN_INITIAL = 1<<12;
411    static final int SCAN_CHECK_ONLY = 1<<13;
412    static final int SCAN_DONT_KILL_APP = 1<<14;
413    static final int SCAN_IGNORE_FROZEN = 1<<15;
414    static final int REMOVE_CHATTY = 1<<16;
415    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
416
417    private static final int[] EMPTY_INT_ARRAY = new int[0];
418
419    /**
420     * Timeout (in milliseconds) after which the watchdog should declare that
421     * our handler thread is wedged.  The usual default for such things is one
422     * minute but we sometimes do very lengthy I/O operations on this thread,
423     * such as installing multi-gigabyte applications, so ours needs to be longer.
424     */
425    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
426
427    /**
428     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
429     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
430     * settings entry if available, otherwise we use the hardcoded default.  If it's been
431     * more than this long since the last fstrim, we force one during the boot sequence.
432     *
433     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
434     * one gets run at the next available charging+idle time.  This final mandatory
435     * no-fstrim check kicks in only of the other scheduling criteria is never met.
436     */
437    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
438
439    /**
440     * Whether verification is enabled by default.
441     */
442    private static final boolean DEFAULT_VERIFY_ENABLE = true;
443
444    /**
445     * The default maximum time to wait for the verification agent to return in
446     * milliseconds.
447     */
448    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
449
450    /**
451     * The default response for package verification timeout.
452     *
453     * This can be either PackageManager.VERIFICATION_ALLOW or
454     * PackageManager.VERIFICATION_REJECT.
455     */
456    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
457
458    static final String PLATFORM_PACKAGE_NAME = "android";
459
460    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
461
462    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
463            DEFAULT_CONTAINER_PACKAGE,
464            "com.android.defcontainer.DefaultContainerService");
465
466    private static final String KILL_APP_REASON_GIDS_CHANGED =
467            "permission grant or revoke changed gids";
468
469    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
470            "permissions revoked";
471
472    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
473
474    private static final String PACKAGE_SCHEME = "package";
475
476    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
477    /**
478     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
479     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
480     * VENDOR_OVERLAY_DIR.
481     */
482    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
483    /**
484     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
485     * is in VENDOR_OVERLAY_THEME_PROPERTY.
486     */
487    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
488            = "persist.vendor.overlay.theme";
489
490    /** Permission grant: not grant the permission. */
491    private static final int GRANT_DENIED = 1;
492
493    /** Permission grant: grant the permission as an install permission. */
494    private static final int GRANT_INSTALL = 2;
495
496    /** Permission grant: grant the permission as a runtime one. */
497    private static final int GRANT_RUNTIME = 3;
498
499    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
500    private static final int GRANT_UPGRADE = 4;
501
502    /** Canonical intent used to identify what counts as a "web browser" app */
503    private static final Intent sBrowserIntent;
504    static {
505        sBrowserIntent = new Intent();
506        sBrowserIntent.setAction(Intent.ACTION_VIEW);
507        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
508        sBrowserIntent.setData(Uri.parse("http:"));
509    }
510
511    /**
512     * The set of all protected actions [i.e. those actions for which a high priority
513     * intent filter is disallowed].
514     */
515    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
516    static {
517        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
518        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
519        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
520        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
521    }
522
523    // Compilation reasons.
524    public static final int REASON_FIRST_BOOT = 0;
525    public static final int REASON_BOOT = 1;
526    public static final int REASON_INSTALL = 2;
527    public static final int REASON_BACKGROUND_DEXOPT = 3;
528    public static final int REASON_AB_OTA = 4;
529    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
530    public static final int REASON_SHARED_APK = 6;
531    public static final int REASON_FORCED_DEXOPT = 7;
532    public static final int REASON_CORE_APP = 8;
533
534    public static final int REASON_LAST = REASON_CORE_APP;
535
536    /** Special library name that skips shared libraries check during compilation. */
537    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
538
539    /** All dangerous permission names in the same order as the events in MetricsEvent */
540    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
541            Manifest.permission.READ_CALENDAR,
542            Manifest.permission.WRITE_CALENDAR,
543            Manifest.permission.CAMERA,
544            Manifest.permission.READ_CONTACTS,
545            Manifest.permission.WRITE_CONTACTS,
546            Manifest.permission.GET_ACCOUNTS,
547            Manifest.permission.ACCESS_FINE_LOCATION,
548            Manifest.permission.ACCESS_COARSE_LOCATION,
549            Manifest.permission.RECORD_AUDIO,
550            Manifest.permission.READ_PHONE_STATE,
551            Manifest.permission.CALL_PHONE,
552            Manifest.permission.READ_CALL_LOG,
553            Manifest.permission.WRITE_CALL_LOG,
554            Manifest.permission.ADD_VOICEMAIL,
555            Manifest.permission.USE_SIP,
556            Manifest.permission.PROCESS_OUTGOING_CALLS,
557            Manifest.permission.READ_CELL_BROADCASTS,
558            Manifest.permission.BODY_SENSORS,
559            Manifest.permission.SEND_SMS,
560            Manifest.permission.RECEIVE_SMS,
561            Manifest.permission.READ_SMS,
562            Manifest.permission.RECEIVE_WAP_PUSH,
563            Manifest.permission.RECEIVE_MMS,
564            Manifest.permission.READ_EXTERNAL_STORAGE,
565            Manifest.permission.WRITE_EXTERNAL_STORAGE,
566            Manifest.permission.READ_PHONE_NUMBER);
567
568
569    /**
570     * Version number for the package parser cache. Increment this whenever the format or
571     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
572     */
573    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
574
575    /**
576     * Whether the package parser cache is enabled.
577     */
578    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
579
580    final ServiceThread mHandlerThread;
581
582    final PackageHandler mHandler;
583
584    private final ProcessLoggingHandler mProcessLoggingHandler;
585
586    /**
587     * Messages for {@link #mHandler} that need to wait for system ready before
588     * being dispatched.
589     */
590    private ArrayList<Message> mPostSystemReadyMessages;
591
592    final int mSdkVersion = Build.VERSION.SDK_INT;
593
594    final Context mContext;
595    final boolean mFactoryTest;
596    final boolean mOnlyCore;
597    final DisplayMetrics mMetrics;
598    final int mDefParseFlags;
599    final String[] mSeparateProcesses;
600    final boolean mIsUpgrade;
601    final boolean mIsPreNUpgrade;
602    final boolean mIsPreNMR1Upgrade;
603
604    @GuardedBy("mPackages")
605    private boolean mDexOptDialogShown;
606
607    /** The location for ASEC container files on internal storage. */
608    final String mAsecInternalPath;
609
610    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
611    // LOCK HELD.  Can be called with mInstallLock held.
612    @GuardedBy("mInstallLock")
613    final Installer mInstaller;
614
615    /** Directory where installed third-party apps stored */
616    final File mAppInstallDir;
617    final File mEphemeralInstallDir;
618
619    /**
620     * Directory to which applications installed internally have their
621     * 32 bit native libraries copied.
622     */
623    private File mAppLib32InstallDir;
624
625    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
626    // apps.
627    final File mDrmAppPrivateInstallDir;
628
629    // ----------------------------------------------------------------
630
631    // Lock for state used when installing and doing other long running
632    // operations.  Methods that must be called with this lock held have
633    // the suffix "LI".
634    final Object mInstallLock = new Object();
635
636    // ----------------------------------------------------------------
637
638    // Keys are String (package name), values are Package.  This also serves
639    // as the lock for the global state.  Methods that must be called with
640    // this lock held have the prefix "LP".
641    @GuardedBy("mPackages")
642    final ArrayMap<String, PackageParser.Package> mPackages =
643            new ArrayMap<String, PackageParser.Package>();
644
645    final ArrayMap<String, Set<String>> mKnownCodebase =
646            new ArrayMap<String, Set<String>>();
647
648    // Tracks available target package names -> overlay package paths.
649    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
650        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
651
652    /**
653     * Tracks new system packages [received in an OTA] that we expect to
654     * find updated user-installed versions. Keys are package name, values
655     * are package location.
656     */
657    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
658    /**
659     * Tracks high priority intent filters for protected actions. During boot, certain
660     * filter actions are protected and should never be allowed to have a high priority
661     * intent filter for them. However, there is one, and only one exception -- the
662     * setup wizard. It must be able to define a high priority intent filter for these
663     * actions to ensure there are no escapes from the wizard. We need to delay processing
664     * of these during boot as we need to look at all of the system packages in order
665     * to know which component is the setup wizard.
666     */
667    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
668    /**
669     * Whether or not processing protected filters should be deferred.
670     */
671    private boolean mDeferProtectedFilters = true;
672
673    /**
674     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
675     */
676    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
677    /**
678     * Whether or not system app permissions should be promoted from install to runtime.
679     */
680    boolean mPromoteSystemApps;
681
682    @GuardedBy("mPackages")
683    final Settings mSettings;
684
685    /**
686     * Set of package names that are currently "frozen", which means active
687     * surgery is being done on the code/data for that package. The platform
688     * will refuse to launch frozen packages to avoid race conditions.
689     *
690     * @see PackageFreezer
691     */
692    @GuardedBy("mPackages")
693    final ArraySet<String> mFrozenPackages = new ArraySet<>();
694
695    final ProtectedPackages mProtectedPackages;
696
697    boolean mFirstBoot;
698
699    // System configuration read by SystemConfig.
700    final int[] mGlobalGids;
701    final SparseArray<ArraySet<String>> mSystemPermissions;
702    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
703
704    // If mac_permissions.xml was found for seinfo labeling.
705    boolean mFoundPolicyFile;
706
707    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
708
709    public static final class SharedLibraryEntry {
710        public final String path;
711        public final String apk;
712
713        SharedLibraryEntry(String _path, String _apk) {
714            path = _path;
715            apk = _apk;
716        }
717    }
718
719    // Currently known shared libraries.
720    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
721            new ArrayMap<String, SharedLibraryEntry>();
722
723    // All available activities, for your resolving pleasure.
724    final ActivityIntentResolver mActivities =
725            new ActivityIntentResolver();
726
727    // All available receivers, for your resolving pleasure.
728    final ActivityIntentResolver mReceivers =
729            new ActivityIntentResolver();
730
731    // All available services, for your resolving pleasure.
732    final ServiceIntentResolver mServices = new ServiceIntentResolver();
733
734    // All available providers, for your resolving pleasure.
735    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
736
737    // Mapping from provider base names (first directory in content URI codePath)
738    // to the provider information.
739    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
740            new ArrayMap<String, PackageParser.Provider>();
741
742    // Mapping from instrumentation class names to info about them.
743    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
744            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
745
746    // Mapping from permission names to info about them.
747    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
748            new ArrayMap<String, PackageParser.PermissionGroup>();
749
750    // Packages whose data we have transfered into another package, thus
751    // should no longer exist.
752    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
753
754    // Broadcast actions that are only available to the system.
755    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
756
757    /** List of packages waiting for verification. */
758    final SparseArray<PackageVerificationState> mPendingVerification
759            = new SparseArray<PackageVerificationState>();
760
761    /** Set of packages associated with each app op permission. */
762    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
763
764    final PackageInstallerService mInstallerService;
765
766    private final PackageDexOptimizer mPackageDexOptimizer;
767    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
768    // is used by other apps).
769    private final DexManager mDexManager;
770
771    private AtomicInteger mNextMoveId = new AtomicInteger();
772    private final MoveCallbacks mMoveCallbacks;
773
774    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
775
776    // Cache of users who need badging.
777    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
778
779    /** Token for keys in mPendingVerification. */
780    private int mPendingVerificationToken = 0;
781
782    volatile boolean mSystemReady;
783    volatile boolean mSafeMode;
784    volatile boolean mHasSystemUidErrors;
785
786    ApplicationInfo mAndroidApplication;
787    final ActivityInfo mResolveActivity = new ActivityInfo();
788    final ResolveInfo mResolveInfo = new ResolveInfo();
789    ComponentName mResolveComponentName;
790    PackageParser.Package mPlatformPackage;
791    ComponentName mCustomResolverComponentName;
792
793    boolean mResolverReplaced = false;
794
795    private final @Nullable ComponentName mIntentFilterVerifierComponent;
796    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
797
798    private int mIntentFilterVerificationToken = 0;
799
800    /** The service connection to the ephemeral resolver */
801    final EphemeralResolverConnection mEphemeralResolverConnection;
802
803    /** Component used to install ephemeral applications */
804    ComponentName mEphemeralInstallerComponent;
805    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
806    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
807
808    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
809            = new SparseArray<IntentFilterVerificationState>();
810
811    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
812
813    // List of packages names to keep cached, even if they are uninstalled for all users
814    private List<String> mKeepUninstalledPackages;
815
816    private UserManagerInternal mUserManagerInternal;
817
818    private File mCacheDir;
819
820    private static class IFVerificationParams {
821        PackageParser.Package pkg;
822        boolean replacing;
823        int userId;
824        int verifierUid;
825
826        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
827                int _userId, int _verifierUid) {
828            pkg = _pkg;
829            replacing = _replacing;
830            userId = _userId;
831            replacing = _replacing;
832            verifierUid = _verifierUid;
833        }
834    }
835
836    private interface IntentFilterVerifier<T extends IntentFilter> {
837        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
838                                               T filter, String packageName);
839        void startVerifications(int userId);
840        void receiveVerificationResponse(int verificationId);
841    }
842
843    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
844        private Context mContext;
845        private ComponentName mIntentFilterVerifierComponent;
846        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
847
848        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
849            mContext = context;
850            mIntentFilterVerifierComponent = verifierComponent;
851        }
852
853        private String getDefaultScheme() {
854            return IntentFilter.SCHEME_HTTPS;
855        }
856
857        @Override
858        public void startVerifications(int userId) {
859            // Launch verifications requests
860            int count = mCurrentIntentFilterVerifications.size();
861            for (int n=0; n<count; n++) {
862                int verificationId = mCurrentIntentFilterVerifications.get(n);
863                final IntentFilterVerificationState ivs =
864                        mIntentFilterVerificationStates.get(verificationId);
865
866                String packageName = ivs.getPackageName();
867
868                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
869                final int filterCount = filters.size();
870                ArraySet<String> domainsSet = new ArraySet<>();
871                for (int m=0; m<filterCount; m++) {
872                    PackageParser.ActivityIntentInfo filter = filters.get(m);
873                    domainsSet.addAll(filter.getHostsList());
874                }
875                synchronized (mPackages) {
876                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
877                            packageName, domainsSet) != null) {
878                        scheduleWriteSettingsLocked();
879                    }
880                }
881                sendVerificationRequest(userId, verificationId, ivs);
882            }
883            mCurrentIntentFilterVerifications.clear();
884        }
885
886        private void sendVerificationRequest(int userId, int verificationId,
887                IntentFilterVerificationState ivs) {
888
889            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
890            verificationIntent.putExtra(
891                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
892                    verificationId);
893            verificationIntent.putExtra(
894                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
895                    getDefaultScheme());
896            verificationIntent.putExtra(
897                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
898                    ivs.getHostsString());
899            verificationIntent.putExtra(
900                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
901                    ivs.getPackageName());
902            verificationIntent.setComponent(mIntentFilterVerifierComponent);
903            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
904
905            UserHandle user = new UserHandle(userId);
906            mContext.sendBroadcastAsUser(verificationIntent, user);
907            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
908                    "Sending IntentFilter verification broadcast");
909        }
910
911        public void receiveVerificationResponse(int verificationId) {
912            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
913
914            final boolean verified = ivs.isVerified();
915
916            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
917            final int count = filters.size();
918            if (DEBUG_DOMAIN_VERIFICATION) {
919                Slog.i(TAG, "Received verification response " + verificationId
920                        + " for " + count + " filters, verified=" + verified);
921            }
922            for (int n=0; n<count; n++) {
923                PackageParser.ActivityIntentInfo filter = filters.get(n);
924                filter.setVerified(verified);
925
926                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
927                        + " verified with result:" + verified + " and hosts:"
928                        + ivs.getHostsString());
929            }
930
931            mIntentFilterVerificationStates.remove(verificationId);
932
933            final String packageName = ivs.getPackageName();
934            IntentFilterVerificationInfo ivi = null;
935
936            synchronized (mPackages) {
937                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
938            }
939            if (ivi == null) {
940                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
941                        + verificationId + " packageName:" + packageName);
942                return;
943            }
944            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
945                    "Updating IntentFilterVerificationInfo for package " + packageName
946                            +" verificationId:" + verificationId);
947
948            synchronized (mPackages) {
949                if (verified) {
950                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
951                } else {
952                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
953                }
954                scheduleWriteSettingsLocked();
955
956                final int userId = ivs.getUserId();
957                if (userId != UserHandle.USER_ALL) {
958                    final int userStatus =
959                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
960
961                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
962                    boolean needUpdate = false;
963
964                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
965                    // already been set by the User thru the Disambiguation dialog
966                    switch (userStatus) {
967                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
968                            if (verified) {
969                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
970                            } else {
971                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
972                            }
973                            needUpdate = true;
974                            break;
975
976                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
977                            if (verified) {
978                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
979                                needUpdate = true;
980                            }
981                            break;
982
983                        default:
984                            // Nothing to do
985                    }
986
987                    if (needUpdate) {
988                        mSettings.updateIntentFilterVerificationStatusLPw(
989                                packageName, updatedStatus, userId);
990                        scheduleWritePackageRestrictionsLocked(userId);
991                    }
992                }
993            }
994        }
995
996        @Override
997        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
998                    ActivityIntentInfo filter, String packageName) {
999            if (!hasValidDomains(filter)) {
1000                return false;
1001            }
1002            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1003            if (ivs == null) {
1004                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1005                        packageName);
1006            }
1007            if (DEBUG_DOMAIN_VERIFICATION) {
1008                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1009            }
1010            ivs.addFilter(filter);
1011            return true;
1012        }
1013
1014        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1015                int userId, int verificationId, String packageName) {
1016            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1017                    verifierUid, userId, packageName);
1018            ivs.setPendingState();
1019            synchronized (mPackages) {
1020                mIntentFilterVerificationStates.append(verificationId, ivs);
1021                mCurrentIntentFilterVerifications.add(verificationId);
1022            }
1023            return ivs;
1024        }
1025    }
1026
1027    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1028        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1029                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1030                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1031    }
1032
1033    // Set of pending broadcasts for aggregating enable/disable of components.
1034    static class PendingPackageBroadcasts {
1035        // for each user id, a map of <package name -> components within that package>
1036        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1037
1038        public PendingPackageBroadcasts() {
1039            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1040        }
1041
1042        public ArrayList<String> get(int userId, String packageName) {
1043            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1044            return packages.get(packageName);
1045        }
1046
1047        public void put(int userId, String packageName, ArrayList<String> components) {
1048            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1049            packages.put(packageName, components);
1050        }
1051
1052        public void remove(int userId, String packageName) {
1053            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1054            if (packages != null) {
1055                packages.remove(packageName);
1056            }
1057        }
1058
1059        public void remove(int userId) {
1060            mUidMap.remove(userId);
1061        }
1062
1063        public int userIdCount() {
1064            return mUidMap.size();
1065        }
1066
1067        public int userIdAt(int n) {
1068            return mUidMap.keyAt(n);
1069        }
1070
1071        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1072            return mUidMap.get(userId);
1073        }
1074
1075        public int size() {
1076            // total number of pending broadcast entries across all userIds
1077            int num = 0;
1078            for (int i = 0; i< mUidMap.size(); i++) {
1079                num += mUidMap.valueAt(i).size();
1080            }
1081            return num;
1082        }
1083
1084        public void clear() {
1085            mUidMap.clear();
1086        }
1087
1088        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1089            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1090            if (map == null) {
1091                map = new ArrayMap<String, ArrayList<String>>();
1092                mUidMap.put(userId, map);
1093            }
1094            return map;
1095        }
1096    }
1097    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1098
1099    // Service Connection to remote media container service to copy
1100    // package uri's from external media onto secure containers
1101    // or internal storage.
1102    private IMediaContainerService mContainerService = null;
1103
1104    static final int SEND_PENDING_BROADCAST = 1;
1105    static final int MCS_BOUND = 3;
1106    static final int END_COPY = 4;
1107    static final int INIT_COPY = 5;
1108    static final int MCS_UNBIND = 6;
1109    static final int START_CLEANING_PACKAGE = 7;
1110    static final int FIND_INSTALL_LOC = 8;
1111    static final int POST_INSTALL = 9;
1112    static final int MCS_RECONNECT = 10;
1113    static final int MCS_GIVE_UP = 11;
1114    static final int UPDATED_MEDIA_STATUS = 12;
1115    static final int WRITE_SETTINGS = 13;
1116    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1117    static final int PACKAGE_VERIFIED = 15;
1118    static final int CHECK_PENDING_VERIFICATION = 16;
1119    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1120    static final int INTENT_FILTER_VERIFIED = 18;
1121    static final int WRITE_PACKAGE_LIST = 19;
1122    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1123
1124    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1125
1126    // Delay time in millisecs
1127    static final int BROADCAST_DELAY = 10 * 1000;
1128
1129    static UserManagerService sUserManager;
1130
1131    // Stores a list of users whose package restrictions file needs to be updated
1132    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1133
1134    final private DefaultContainerConnection mDefContainerConn =
1135            new DefaultContainerConnection();
1136    class DefaultContainerConnection implements ServiceConnection {
1137        public void onServiceConnected(ComponentName name, IBinder service) {
1138            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1139            final IMediaContainerService imcs = IMediaContainerService.Stub
1140                    .asInterface(Binder.allowBlocking(service));
1141            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1142        }
1143
1144        public void onServiceDisconnected(ComponentName name) {
1145            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1146        }
1147    }
1148
1149    // Recordkeeping of restore-after-install operations that are currently in flight
1150    // between the Package Manager and the Backup Manager
1151    static class PostInstallData {
1152        public InstallArgs args;
1153        public PackageInstalledInfo res;
1154
1155        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1156            args = _a;
1157            res = _r;
1158        }
1159    }
1160
1161    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1162    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1163
1164    // XML tags for backup/restore of various bits of state
1165    private static final String TAG_PREFERRED_BACKUP = "pa";
1166    private static final String TAG_DEFAULT_APPS = "da";
1167    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1168
1169    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1170    private static final String TAG_ALL_GRANTS = "rt-grants";
1171    private static final String TAG_GRANT = "grant";
1172    private static final String ATTR_PACKAGE_NAME = "pkg";
1173
1174    private static final String TAG_PERMISSION = "perm";
1175    private static final String ATTR_PERMISSION_NAME = "name";
1176    private static final String ATTR_IS_GRANTED = "g";
1177    private static final String ATTR_USER_SET = "set";
1178    private static final String ATTR_USER_FIXED = "fixed";
1179    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1180
1181    // System/policy permission grants are not backed up
1182    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1183            FLAG_PERMISSION_POLICY_FIXED
1184            | FLAG_PERMISSION_SYSTEM_FIXED
1185            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1186
1187    // And we back up these user-adjusted states
1188    private static final int USER_RUNTIME_GRANT_MASK =
1189            FLAG_PERMISSION_USER_SET
1190            | FLAG_PERMISSION_USER_FIXED
1191            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1192
1193    final @Nullable String mRequiredVerifierPackage;
1194    final @NonNull String mRequiredInstallerPackage;
1195    final @NonNull String mRequiredUninstallerPackage;
1196    final @Nullable String mSetupWizardPackage;
1197    final @Nullable String mStorageManagerPackage;
1198    final @NonNull String mServicesSystemSharedLibraryPackageName;
1199    final @NonNull String mSharedSystemSharedLibraryPackageName;
1200
1201    final boolean mPermissionReviewRequired;
1202
1203    private final PackageUsage mPackageUsage = new PackageUsage();
1204    private final CompilerStats mCompilerStats = new CompilerStats();
1205
1206    class PackageHandler extends Handler {
1207        private boolean mBound = false;
1208        final ArrayList<HandlerParams> mPendingInstalls =
1209            new ArrayList<HandlerParams>();
1210
1211        private boolean connectToService() {
1212            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1213                    " DefaultContainerService");
1214            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1215            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1216            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1217                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1218                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1219                mBound = true;
1220                return true;
1221            }
1222            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1223            return false;
1224        }
1225
1226        private void disconnectService() {
1227            mContainerService = null;
1228            mBound = false;
1229            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1230            mContext.unbindService(mDefContainerConn);
1231            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1232        }
1233
1234        PackageHandler(Looper looper) {
1235            super(looper);
1236        }
1237
1238        public void handleMessage(Message msg) {
1239            try {
1240                doHandleMessage(msg);
1241            } finally {
1242                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1243            }
1244        }
1245
1246        void doHandleMessage(Message msg) {
1247            switch (msg.what) {
1248                case INIT_COPY: {
1249                    HandlerParams params = (HandlerParams) msg.obj;
1250                    int idx = mPendingInstalls.size();
1251                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1252                    // If a bind was already initiated we dont really
1253                    // need to do anything. The pending install
1254                    // will be processed later on.
1255                    if (!mBound) {
1256                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1257                                System.identityHashCode(mHandler));
1258                        // If this is the only one pending we might
1259                        // have to bind to the service again.
1260                        if (!connectToService()) {
1261                            Slog.e(TAG, "Failed to bind to media container service");
1262                            params.serviceError();
1263                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1264                                    System.identityHashCode(mHandler));
1265                            if (params.traceMethod != null) {
1266                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1267                                        params.traceCookie);
1268                            }
1269                            return;
1270                        } else {
1271                            // Once we bind to the service, the first
1272                            // pending request will be processed.
1273                            mPendingInstalls.add(idx, params);
1274                        }
1275                    } else {
1276                        mPendingInstalls.add(idx, params);
1277                        // Already bound to the service. Just make
1278                        // sure we trigger off processing the first request.
1279                        if (idx == 0) {
1280                            mHandler.sendEmptyMessage(MCS_BOUND);
1281                        }
1282                    }
1283                    break;
1284                }
1285                case MCS_BOUND: {
1286                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1287                    if (msg.obj != null) {
1288                        mContainerService = (IMediaContainerService) msg.obj;
1289                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1290                                System.identityHashCode(mHandler));
1291                    }
1292                    if (mContainerService == null) {
1293                        if (!mBound) {
1294                            // Something seriously wrong since we are not bound and we are not
1295                            // waiting for connection. Bail out.
1296                            Slog.e(TAG, "Cannot bind to media container service");
1297                            for (HandlerParams params : mPendingInstalls) {
1298                                // Indicate service bind error
1299                                params.serviceError();
1300                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1301                                        System.identityHashCode(params));
1302                                if (params.traceMethod != null) {
1303                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1304                                            params.traceMethod, params.traceCookie);
1305                                }
1306                                return;
1307                            }
1308                            mPendingInstalls.clear();
1309                        } else {
1310                            Slog.w(TAG, "Waiting to connect to media container service");
1311                        }
1312                    } else if (mPendingInstalls.size() > 0) {
1313                        HandlerParams params = mPendingInstalls.get(0);
1314                        if (params != null) {
1315                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1316                                    System.identityHashCode(params));
1317                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1318                            if (params.startCopy()) {
1319                                // We are done...  look for more work or to
1320                                // go idle.
1321                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1322                                        "Checking for more work or unbind...");
1323                                // Delete pending install
1324                                if (mPendingInstalls.size() > 0) {
1325                                    mPendingInstalls.remove(0);
1326                                }
1327                                if (mPendingInstalls.size() == 0) {
1328                                    if (mBound) {
1329                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1330                                                "Posting delayed MCS_UNBIND");
1331                                        removeMessages(MCS_UNBIND);
1332                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1333                                        // Unbind after a little delay, to avoid
1334                                        // continual thrashing.
1335                                        sendMessageDelayed(ubmsg, 10000);
1336                                    }
1337                                } else {
1338                                    // There are more pending requests in queue.
1339                                    // Just post MCS_BOUND message to trigger processing
1340                                    // of next pending install.
1341                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1342                                            "Posting MCS_BOUND for next work");
1343                                    mHandler.sendEmptyMessage(MCS_BOUND);
1344                                }
1345                            }
1346                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1347                        }
1348                    } else {
1349                        // Should never happen ideally.
1350                        Slog.w(TAG, "Empty queue");
1351                    }
1352                    break;
1353                }
1354                case MCS_RECONNECT: {
1355                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1356                    if (mPendingInstalls.size() > 0) {
1357                        if (mBound) {
1358                            disconnectService();
1359                        }
1360                        if (!connectToService()) {
1361                            Slog.e(TAG, "Failed to bind to media container service");
1362                            for (HandlerParams params : mPendingInstalls) {
1363                                // Indicate service bind error
1364                                params.serviceError();
1365                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1366                                        System.identityHashCode(params));
1367                            }
1368                            mPendingInstalls.clear();
1369                        }
1370                    }
1371                    break;
1372                }
1373                case MCS_UNBIND: {
1374                    // If there is no actual work left, then time to unbind.
1375                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1376
1377                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1378                        if (mBound) {
1379                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1380
1381                            disconnectService();
1382                        }
1383                    } else if (mPendingInstalls.size() > 0) {
1384                        // There are more pending requests in queue.
1385                        // Just post MCS_BOUND message to trigger processing
1386                        // of next pending install.
1387                        mHandler.sendEmptyMessage(MCS_BOUND);
1388                    }
1389
1390                    break;
1391                }
1392                case MCS_GIVE_UP: {
1393                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1394                    HandlerParams params = mPendingInstalls.remove(0);
1395                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1396                            System.identityHashCode(params));
1397                    break;
1398                }
1399                case SEND_PENDING_BROADCAST: {
1400                    String packages[];
1401                    ArrayList<String> components[];
1402                    int size = 0;
1403                    int uids[];
1404                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1405                    synchronized (mPackages) {
1406                        if (mPendingBroadcasts == null) {
1407                            return;
1408                        }
1409                        size = mPendingBroadcasts.size();
1410                        if (size <= 0) {
1411                            // Nothing to be done. Just return
1412                            return;
1413                        }
1414                        packages = new String[size];
1415                        components = new ArrayList[size];
1416                        uids = new int[size];
1417                        int i = 0;  // filling out the above arrays
1418
1419                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1420                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1421                            Iterator<Map.Entry<String, ArrayList<String>>> it
1422                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1423                                            .entrySet().iterator();
1424                            while (it.hasNext() && i < size) {
1425                                Map.Entry<String, ArrayList<String>> ent = it.next();
1426                                packages[i] = ent.getKey();
1427                                components[i] = ent.getValue();
1428                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1429                                uids[i] = (ps != null)
1430                                        ? UserHandle.getUid(packageUserId, ps.appId)
1431                                        : -1;
1432                                i++;
1433                            }
1434                        }
1435                        size = i;
1436                        mPendingBroadcasts.clear();
1437                    }
1438                    // Send broadcasts
1439                    for (int i = 0; i < size; i++) {
1440                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1441                    }
1442                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443                    break;
1444                }
1445                case START_CLEANING_PACKAGE: {
1446                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1447                    final String packageName = (String)msg.obj;
1448                    final int userId = msg.arg1;
1449                    final boolean andCode = msg.arg2 != 0;
1450                    synchronized (mPackages) {
1451                        if (userId == UserHandle.USER_ALL) {
1452                            int[] users = sUserManager.getUserIds();
1453                            for (int user : users) {
1454                                mSettings.addPackageToCleanLPw(
1455                                        new PackageCleanItem(user, packageName, andCode));
1456                            }
1457                        } else {
1458                            mSettings.addPackageToCleanLPw(
1459                                    new PackageCleanItem(userId, packageName, andCode));
1460                        }
1461                    }
1462                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1463                    startCleaningPackages();
1464                } break;
1465                case POST_INSTALL: {
1466                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1467
1468                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1469                    final boolean didRestore = (msg.arg2 != 0);
1470                    mRunningInstalls.delete(msg.arg1);
1471
1472                    if (data != null) {
1473                        InstallArgs args = data.args;
1474                        PackageInstalledInfo parentRes = data.res;
1475
1476                        final boolean grantPermissions = (args.installFlags
1477                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1478                        final boolean killApp = (args.installFlags
1479                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1480                        final String[] grantedPermissions = args.installGrantPermissions;
1481
1482                        // Handle the parent package
1483                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1484                                grantedPermissions, didRestore, args.installerPackageName,
1485                                args.observer);
1486
1487                        // Handle the child packages
1488                        final int childCount = (parentRes.addedChildPackages != null)
1489                                ? parentRes.addedChildPackages.size() : 0;
1490                        for (int i = 0; i < childCount; i++) {
1491                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1492                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1493                                    grantedPermissions, false, args.installerPackageName,
1494                                    args.observer);
1495                        }
1496
1497                        // Log tracing if needed
1498                        if (args.traceMethod != null) {
1499                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1500                                    args.traceCookie);
1501                        }
1502                    } else {
1503                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1504                    }
1505
1506                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1507                } break;
1508                case UPDATED_MEDIA_STATUS: {
1509                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1510                    boolean reportStatus = msg.arg1 == 1;
1511                    boolean doGc = msg.arg2 == 1;
1512                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1513                    if (doGc) {
1514                        // Force a gc to clear up stale containers.
1515                        Runtime.getRuntime().gc();
1516                    }
1517                    if (msg.obj != null) {
1518                        @SuppressWarnings("unchecked")
1519                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1520                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1521                        // Unload containers
1522                        unloadAllContainers(args);
1523                    }
1524                    if (reportStatus) {
1525                        try {
1526                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                    "Invoking StorageManagerService call back");
1528                            PackageHelper.getStorageManager().finishMediaUpdate();
1529                        } catch (RemoteException e) {
1530                            Log.e(TAG, "StorageManagerService not running?");
1531                        }
1532                    }
1533                } break;
1534                case WRITE_SETTINGS: {
1535                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1536                    synchronized (mPackages) {
1537                        removeMessages(WRITE_SETTINGS);
1538                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1539                        mSettings.writeLPr();
1540                        mDirtyUsers.clear();
1541                    }
1542                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1543                } break;
1544                case WRITE_PACKAGE_RESTRICTIONS: {
1545                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1546                    synchronized (mPackages) {
1547                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1548                        for (int userId : mDirtyUsers) {
1549                            mSettings.writePackageRestrictionsLPr(userId);
1550                        }
1551                        mDirtyUsers.clear();
1552                    }
1553                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1554                } break;
1555                case WRITE_PACKAGE_LIST: {
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1557                    synchronized (mPackages) {
1558                        removeMessages(WRITE_PACKAGE_LIST);
1559                        mSettings.writePackageListLPr(msg.arg1);
1560                    }
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562                } break;
1563                case CHECK_PENDING_VERIFICATION: {
1564                    final int verificationId = msg.arg1;
1565                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1566
1567                    if ((state != null) && !state.timeoutExtended()) {
1568                        final InstallArgs args = state.getInstallArgs();
1569                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1570
1571                        Slog.i(TAG, "Verification timed out for " + originUri);
1572                        mPendingVerification.remove(verificationId);
1573
1574                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1575
1576                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1577                            Slog.i(TAG, "Continuing with installation of " + originUri);
1578                            state.setVerifierResponse(Binder.getCallingUid(),
1579                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1580                            broadcastPackageVerified(verificationId, originUri,
1581                                    PackageManager.VERIFICATION_ALLOW,
1582                                    state.getInstallArgs().getUser());
1583                            try {
1584                                ret = args.copyApk(mContainerService, true);
1585                            } catch (RemoteException e) {
1586                                Slog.e(TAG, "Could not contact the ContainerService");
1587                            }
1588                        } else {
1589                            broadcastPackageVerified(verificationId, originUri,
1590                                    PackageManager.VERIFICATION_REJECT,
1591                                    state.getInstallArgs().getUser());
1592                        }
1593
1594                        Trace.asyncTraceEnd(
1595                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1596
1597                        processPendingInstall(args, ret);
1598                        mHandler.sendEmptyMessage(MCS_UNBIND);
1599                    }
1600                    break;
1601                }
1602                case PACKAGE_VERIFIED: {
1603                    final int verificationId = msg.arg1;
1604
1605                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1606                    if (state == null) {
1607                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1608                        break;
1609                    }
1610
1611                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1612
1613                    state.setVerifierResponse(response.callerUid, response.code);
1614
1615                    if (state.isVerificationComplete()) {
1616                        mPendingVerification.remove(verificationId);
1617
1618                        final InstallArgs args = state.getInstallArgs();
1619                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1620
1621                        int ret;
1622                        if (state.isInstallAllowed()) {
1623                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1624                            broadcastPackageVerified(verificationId, originUri,
1625                                    response.code, state.getInstallArgs().getUser());
1626                            try {
1627                                ret = args.copyApk(mContainerService, true);
1628                            } catch (RemoteException e) {
1629                                Slog.e(TAG, "Could not contact the ContainerService");
1630                            }
1631                        } else {
1632                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1633                        }
1634
1635                        Trace.asyncTraceEnd(
1636                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1637
1638                        processPendingInstall(args, ret);
1639                        mHandler.sendEmptyMessage(MCS_UNBIND);
1640                    }
1641
1642                    break;
1643                }
1644                case START_INTENT_FILTER_VERIFICATIONS: {
1645                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1646                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1647                            params.replacing, params.pkg);
1648                    break;
1649                }
1650                case INTENT_FILTER_VERIFIED: {
1651                    final int verificationId = msg.arg1;
1652
1653                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1654                            verificationId);
1655                    if (state == null) {
1656                        Slog.w(TAG, "Invalid IntentFilter verification token "
1657                                + verificationId + " received");
1658                        break;
1659                    }
1660
1661                    final int userId = state.getUserId();
1662
1663                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1664                            "Processing IntentFilter verification with token:"
1665                            + verificationId + " and userId:" + userId);
1666
1667                    final IntentFilterVerificationResponse response =
1668                            (IntentFilterVerificationResponse) msg.obj;
1669
1670                    state.setVerifierResponse(response.callerUid, response.code);
1671
1672                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1673                            "IntentFilter verification with token:" + verificationId
1674                            + " and userId:" + userId
1675                            + " is settings verifier response with response code:"
1676                            + response.code);
1677
1678                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1679                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1680                                + response.getFailedDomainsString());
1681                    }
1682
1683                    if (state.isVerificationComplete()) {
1684                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1685                    } else {
1686                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1687                                "IntentFilter verification with token:" + verificationId
1688                                + " was not said to be complete");
1689                    }
1690
1691                    break;
1692                }
1693                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1694                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1695                            mEphemeralResolverConnection,
1696                            (EphemeralRequest) msg.obj,
1697                            mEphemeralInstallerActivity,
1698                            mHandler);
1699                }
1700            }
1701        }
1702    }
1703
1704    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1705            boolean killApp, String[] grantedPermissions,
1706            boolean launchedForRestore, String installerPackage,
1707            IPackageInstallObserver2 installObserver) {
1708        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1709            // Send the removed broadcasts
1710            if (res.removedInfo != null) {
1711                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1712            }
1713
1714            // Now that we successfully installed the package, grant runtime
1715            // permissions if requested before broadcasting the install. Also
1716            // for legacy apps in permission review mode we clear the permission
1717            // review flag which is used to emulate runtime permissions for
1718            // legacy apps.
1719            if (grantPermissions) {
1720                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1721            }
1722
1723            final boolean update = res.removedInfo != null
1724                    && res.removedInfo.removedPackage != null;
1725
1726            // If this is the first time we have child packages for a disabled privileged
1727            // app that had no children, we grant requested runtime permissions to the new
1728            // children if the parent on the system image had them already granted.
1729            if (res.pkg.parentPackage != null) {
1730                synchronized (mPackages) {
1731                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1732                }
1733            }
1734
1735            synchronized (mPackages) {
1736                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1737            }
1738
1739            final String packageName = res.pkg.applicationInfo.packageName;
1740
1741            // Determine the set of users who are adding this package for
1742            // the first time vs. those who are seeing an update.
1743            int[] firstUsers = EMPTY_INT_ARRAY;
1744            int[] updateUsers = EMPTY_INT_ARRAY;
1745            if (res.origUsers == null || res.origUsers.length == 0) {
1746                firstUsers = res.newUsers;
1747            } else {
1748                for (int newUser : res.newUsers) {
1749                    boolean isNew = true;
1750                    for (int origUser : res.origUsers) {
1751                        if (origUser == newUser) {
1752                            isNew = false;
1753                            break;
1754                        }
1755                    }
1756                    if (isNew) {
1757                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1758                    } else {
1759                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1760                    }
1761                }
1762            }
1763
1764            // Send installed broadcasts if the install/update is not ephemeral
1765            if (!isEphemeral(res.pkg)) {
1766                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1767
1768                // Send added for users that see the package for the first time
1769                // sendPackageAddedForNewUsers also deals with system apps
1770                int appId = UserHandle.getAppId(res.uid);
1771                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1772                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1773
1774                // Send added for users that don't see the package for the first time
1775                Bundle extras = new Bundle(1);
1776                extras.putInt(Intent.EXTRA_UID, res.uid);
1777                if (update) {
1778                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1779                }
1780                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1781                        extras, 0 /*flags*/, null /*targetPackage*/,
1782                        null /*finishedReceiver*/, updateUsers);
1783
1784                // Send replaced for users that don't see the package for the first time
1785                if (update) {
1786                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1787                            packageName, extras, 0 /*flags*/,
1788                            null /*targetPackage*/, null /*finishedReceiver*/,
1789                            updateUsers);
1790                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1791                            null /*package*/, null /*extras*/, 0 /*flags*/,
1792                            packageName /*targetPackage*/,
1793                            null /*finishedReceiver*/, updateUsers);
1794                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1795                    // First-install and we did a restore, so we're responsible for the
1796                    // first-launch broadcast.
1797                    if (DEBUG_BACKUP) {
1798                        Slog.i(TAG, "Post-restore of " + packageName
1799                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1800                    }
1801                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1802                }
1803
1804                // Send broadcast package appeared if forward locked/external for all users
1805                // treat asec-hosted packages like removable media on upgrade
1806                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1807                    if (DEBUG_INSTALL) {
1808                        Slog.i(TAG, "upgrading pkg " + res.pkg
1809                                + " is ASEC-hosted -> AVAILABLE");
1810                    }
1811                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1812                    ArrayList<String> pkgList = new ArrayList<>(1);
1813                    pkgList.add(packageName);
1814                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1815                }
1816            }
1817
1818            // Work that needs to happen on first install within each user
1819            if (firstUsers != null && firstUsers.length > 0) {
1820                synchronized (mPackages) {
1821                    for (int userId : firstUsers) {
1822                        // If this app is a browser and it's newly-installed for some
1823                        // users, clear any default-browser state in those users. The
1824                        // app's nature doesn't depend on the user, so we can just check
1825                        // its browser nature in any user and generalize.
1826                        if (packageIsBrowser(packageName, userId)) {
1827                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1828                        }
1829
1830                        // We may also need to apply pending (restored) runtime
1831                        // permission grants within these users.
1832                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1833                    }
1834                }
1835            }
1836
1837            // Log current value of "unknown sources" setting
1838            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1839                    getUnknownSourcesSettings());
1840
1841            // Force a gc to clear up things
1842            Runtime.getRuntime().gc();
1843
1844            // Remove the replaced package's older resources safely now
1845            // We delete after a gc for applications  on sdcard.
1846            if (res.removedInfo != null && res.removedInfo.args != null) {
1847                synchronized (mInstallLock) {
1848                    res.removedInfo.args.doPostDeleteLI(true);
1849                }
1850            }
1851        }
1852
1853        // If someone is watching installs - notify them
1854        if (installObserver != null) {
1855            try {
1856                Bundle extras = extrasForInstallResult(res);
1857                installObserver.onPackageInstalled(res.name, res.returnCode,
1858                        res.returnMsg, extras);
1859            } catch (RemoteException e) {
1860                Slog.i(TAG, "Observer no longer exists.");
1861            }
1862        }
1863    }
1864
1865    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1866            PackageParser.Package pkg) {
1867        if (pkg.parentPackage == null) {
1868            return;
1869        }
1870        if (pkg.requestedPermissions == null) {
1871            return;
1872        }
1873        final PackageSetting disabledSysParentPs = mSettings
1874                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1875        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1876                || !disabledSysParentPs.isPrivileged()
1877                || (disabledSysParentPs.childPackageNames != null
1878                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1879            return;
1880        }
1881        final int[] allUserIds = sUserManager.getUserIds();
1882        final int permCount = pkg.requestedPermissions.size();
1883        for (int i = 0; i < permCount; i++) {
1884            String permission = pkg.requestedPermissions.get(i);
1885            BasePermission bp = mSettings.mPermissions.get(permission);
1886            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1887                continue;
1888            }
1889            for (int userId : allUserIds) {
1890                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1891                        permission, userId)) {
1892                    grantRuntimePermission(pkg.packageName, permission, userId);
1893                }
1894            }
1895        }
1896    }
1897
1898    private StorageEventListener mStorageListener = new StorageEventListener() {
1899        @Override
1900        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1901            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1902                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1903                    final String volumeUuid = vol.getFsUuid();
1904
1905                    // Clean up any users or apps that were removed or recreated
1906                    // while this volume was missing
1907                    reconcileUsers(volumeUuid);
1908                    reconcileApps(volumeUuid);
1909
1910                    // Clean up any install sessions that expired or were
1911                    // cancelled while this volume was missing
1912                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1913
1914                    loadPrivatePackages(vol);
1915
1916                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1917                    unloadPrivatePackages(vol);
1918                }
1919            }
1920
1921            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1922                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1923                    updateExternalMediaStatus(true, false);
1924                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1925                    updateExternalMediaStatus(false, false);
1926                }
1927            }
1928        }
1929
1930        @Override
1931        public void onVolumeForgotten(String fsUuid) {
1932            if (TextUtils.isEmpty(fsUuid)) {
1933                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1934                return;
1935            }
1936
1937            // Remove any apps installed on the forgotten volume
1938            synchronized (mPackages) {
1939                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1940                for (PackageSetting ps : packages) {
1941                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1942                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1943                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1944
1945                    // Try very hard to release any references to this package
1946                    // so we don't risk the system server being killed due to
1947                    // open FDs
1948                    AttributeCache.instance().removePackage(ps.name);
1949                }
1950
1951                mSettings.onVolumeForgotten(fsUuid);
1952                mSettings.writeLPr();
1953            }
1954        }
1955    };
1956
1957    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1958            String[] grantedPermissions) {
1959        for (int userId : userIds) {
1960            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1961        }
1962    }
1963
1964    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1965            String[] grantedPermissions) {
1966        SettingBase sb = (SettingBase) pkg.mExtras;
1967        if (sb == null) {
1968            return;
1969        }
1970
1971        PermissionsState permissionsState = sb.getPermissionsState();
1972
1973        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1974                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1975
1976        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1977                >= Build.VERSION_CODES.M;
1978
1979        for (String permission : pkg.requestedPermissions) {
1980            final BasePermission bp;
1981            synchronized (mPackages) {
1982                bp = mSettings.mPermissions.get(permission);
1983            }
1984            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1985                    && (grantedPermissions == null
1986                           || ArrayUtils.contains(grantedPermissions, permission))) {
1987                final int flags = permissionsState.getPermissionFlags(permission, userId);
1988                if (supportsRuntimePermissions) {
1989                    // Installer cannot change immutable permissions.
1990                    if ((flags & immutableFlags) == 0) {
1991                        grantRuntimePermission(pkg.packageName, permission, userId);
1992                    }
1993                } else if (mPermissionReviewRequired) {
1994                    // In permission review mode we clear the review flag when we
1995                    // are asked to install the app with all permissions granted.
1996                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
1997                        updatePermissionFlags(permission, pkg.packageName,
1998                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
1999                    }
2000                }
2001            }
2002        }
2003    }
2004
2005    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2006        Bundle extras = null;
2007        switch (res.returnCode) {
2008            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2009                extras = new Bundle();
2010                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2011                        res.origPermission);
2012                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2013                        res.origPackage);
2014                break;
2015            }
2016            case PackageManager.INSTALL_SUCCEEDED: {
2017                extras = new Bundle();
2018                extras.putBoolean(Intent.EXTRA_REPLACING,
2019                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2020                break;
2021            }
2022        }
2023        return extras;
2024    }
2025
2026    void scheduleWriteSettingsLocked() {
2027        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2028            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2029        }
2030    }
2031
2032    void scheduleWritePackageListLocked(int userId) {
2033        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2034            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2035            msg.arg1 = userId;
2036            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2037        }
2038    }
2039
2040    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2041        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2042        scheduleWritePackageRestrictionsLocked(userId);
2043    }
2044
2045    void scheduleWritePackageRestrictionsLocked(int userId) {
2046        final int[] userIds = (userId == UserHandle.USER_ALL)
2047                ? sUserManager.getUserIds() : new int[]{userId};
2048        for (int nextUserId : userIds) {
2049            if (!sUserManager.exists(nextUserId)) return;
2050            mDirtyUsers.add(nextUserId);
2051            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2052                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2053            }
2054        }
2055    }
2056
2057    public static PackageManagerService main(Context context, Installer installer,
2058            boolean factoryTest, boolean onlyCore) {
2059        // Self-check for initial settings.
2060        PackageManagerServiceCompilerMapping.checkProperties();
2061
2062        PackageManagerService m = new PackageManagerService(context, installer,
2063                factoryTest, onlyCore);
2064        m.enableSystemUserPackages();
2065        ServiceManager.addService("package", m);
2066        return m;
2067    }
2068
2069    private void enableSystemUserPackages() {
2070        if (!UserManager.isSplitSystemUser()) {
2071            return;
2072        }
2073        // For system user, enable apps based on the following conditions:
2074        // - app is whitelisted or belong to one of these groups:
2075        //   -- system app which has no launcher icons
2076        //   -- system app which has INTERACT_ACROSS_USERS permission
2077        //   -- system IME app
2078        // - app is not in the blacklist
2079        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2080        Set<String> enableApps = new ArraySet<>();
2081        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2082                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2083                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2084        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2085        enableApps.addAll(wlApps);
2086        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2087                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2088        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2089        enableApps.removeAll(blApps);
2090        Log.i(TAG, "Applications installed for system user: " + enableApps);
2091        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2092                UserHandle.SYSTEM);
2093        final int allAppsSize = allAps.size();
2094        synchronized (mPackages) {
2095            for (int i = 0; i < allAppsSize; i++) {
2096                String pName = allAps.get(i);
2097                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2098                // Should not happen, but we shouldn't be failing if it does
2099                if (pkgSetting == null) {
2100                    continue;
2101                }
2102                boolean install = enableApps.contains(pName);
2103                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2104                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2105                            + " for system user");
2106                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2107                }
2108            }
2109        }
2110    }
2111
2112    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2113        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2114                Context.DISPLAY_SERVICE);
2115        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2116    }
2117
2118    /**
2119     * Requests that files preopted on a secondary system partition be copied to the data partition
2120     * if possible.  Note that the actual copying of the files is accomplished by init for security
2121     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2122     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2123     */
2124    private static void requestCopyPreoptedFiles() {
2125        final int WAIT_TIME_MS = 100;
2126        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2127        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2128            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2129            // We will wait for up to 100 seconds.
2130            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2131            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2132                try {
2133                    Thread.sleep(WAIT_TIME_MS);
2134                } catch (InterruptedException e) {
2135                    // Do nothing
2136                }
2137                if (SystemClock.uptimeMillis() > timeEnd) {
2138                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2139                    Slog.wtf(TAG, "cppreopt did not finish!");
2140                    break;
2141                }
2142            }
2143        }
2144    }
2145
2146    public PackageManagerService(Context context, Installer installer,
2147            boolean factoryTest, boolean onlyCore) {
2148        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2149        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2150                SystemClock.uptimeMillis());
2151
2152        if (mSdkVersion <= 0) {
2153            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2154        }
2155
2156        mContext = context;
2157
2158        mPermissionReviewRequired = context.getResources().getBoolean(
2159                R.bool.config_permissionReviewRequired);
2160
2161        mFactoryTest = factoryTest;
2162        mOnlyCore = onlyCore;
2163        mMetrics = new DisplayMetrics();
2164        mSettings = new Settings(mPackages);
2165        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2166                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2167        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2168                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2169        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2170                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2171        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2172                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2173        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2174                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2175        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2176                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2177
2178        String separateProcesses = SystemProperties.get("debug.separate_processes");
2179        if (separateProcesses != null && separateProcesses.length() > 0) {
2180            if ("*".equals(separateProcesses)) {
2181                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2182                mSeparateProcesses = null;
2183                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2184            } else {
2185                mDefParseFlags = 0;
2186                mSeparateProcesses = separateProcesses.split(",");
2187                Slog.w(TAG, "Running with debug.separate_processes: "
2188                        + separateProcesses);
2189            }
2190        } else {
2191            mDefParseFlags = 0;
2192            mSeparateProcesses = null;
2193        }
2194
2195        mInstaller = installer;
2196        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2197                "*dexopt*");
2198        mDexManager = new DexManager();
2199        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2200
2201        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2202                FgThread.get().getLooper());
2203
2204        getDefaultDisplayMetrics(context, mMetrics);
2205
2206        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2207        SystemConfig systemConfig = SystemConfig.getInstance();
2208        mGlobalGids = systemConfig.getGlobalGids();
2209        mSystemPermissions = systemConfig.getSystemPermissions();
2210        mAvailableFeatures = systemConfig.getAvailableFeatures();
2211        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2212
2213        mProtectedPackages = new ProtectedPackages(mContext);
2214
2215        synchronized (mInstallLock) {
2216        // writer
2217        synchronized (mPackages) {
2218            mHandlerThread = new ServiceThread(TAG,
2219                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2220            mHandlerThread.start();
2221            mHandler = new PackageHandler(mHandlerThread.getLooper());
2222            mProcessLoggingHandler = new ProcessLoggingHandler();
2223            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2224
2225            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2226
2227            File dataDir = Environment.getDataDirectory();
2228            mAppInstallDir = new File(dataDir, "app");
2229            mAppLib32InstallDir = new File(dataDir, "app-lib");
2230            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2231            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2232            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2233
2234            sUserManager = new UserManagerService(context, this, mPackages);
2235
2236            // Propagate permission configuration in to package manager.
2237            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2238                    = systemConfig.getPermissions();
2239            for (int i=0; i<permConfig.size(); i++) {
2240                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2241                BasePermission bp = mSettings.mPermissions.get(perm.name);
2242                if (bp == null) {
2243                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2244                    mSettings.mPermissions.put(perm.name, bp);
2245                }
2246                if (perm.gids != null) {
2247                    bp.setGids(perm.gids, perm.perUser);
2248                }
2249            }
2250
2251            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2252            for (int i=0; i<libConfig.size(); i++) {
2253                mSharedLibraries.put(libConfig.keyAt(i),
2254                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2255            }
2256
2257            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2258
2259            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2260            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2261            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2262
2263            // Clean up orphaned packages for which the code path doesn't exist
2264            // and they are an update to a system app - caused by bug/32321269
2265            final int packageSettingCount = mSettings.mPackages.size();
2266            for (int i = packageSettingCount - 1; i >= 0; i--) {
2267                PackageSetting ps = mSettings.mPackages.valueAt(i);
2268                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2269                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2270                    mSettings.mPackages.removeAt(i);
2271                    mSettings.enableSystemPackageLPw(ps.name);
2272                }
2273            }
2274
2275            if (mFirstBoot) {
2276                requestCopyPreoptedFiles();
2277            }
2278
2279            String customResolverActivity = Resources.getSystem().getString(
2280                    R.string.config_customResolverActivity);
2281            if (TextUtils.isEmpty(customResolverActivity)) {
2282                customResolverActivity = null;
2283            } else {
2284                mCustomResolverComponentName = ComponentName.unflattenFromString(
2285                        customResolverActivity);
2286            }
2287
2288            long startTime = SystemClock.uptimeMillis();
2289
2290            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2291                    startTime);
2292
2293            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2294            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2295
2296            if (bootClassPath == null) {
2297                Slog.w(TAG, "No BOOTCLASSPATH found!");
2298            }
2299
2300            if (systemServerClassPath == null) {
2301                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2302            }
2303
2304            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2305            final String[] dexCodeInstructionSets =
2306                    getDexCodeInstructionSets(
2307                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2308
2309            /**
2310             * Ensure all external libraries have had dexopt run on them.
2311             */
2312            if (mSharedLibraries.size() > 0) {
2313                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2314                // NOTE: For now, we're compiling these system "shared libraries"
2315                // (and framework jars) into all available architectures. It's possible
2316                // to compile them only when we come across an app that uses them (there's
2317                // already logic for that in scanPackageLI) but that adds some complexity.
2318                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2319                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2320                        final String lib = libEntry.path;
2321                        if (lib == null) {
2322                            continue;
2323                        }
2324
2325                        try {
2326                            // Shared libraries do not have profiles so we perform a full
2327                            // AOT compilation (if needed).
2328                            int dexoptNeeded = DexFile.getDexOptNeeded(
2329                                    lib, dexCodeInstructionSet,
2330                                    getCompilerFilterForReason(REASON_SHARED_APK),
2331                                    false /* newProfile */);
2332                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2333                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2334                                        dexCodeInstructionSet, dexoptNeeded, null,
2335                                        DEXOPT_PUBLIC,
2336                                        getCompilerFilterForReason(REASON_SHARED_APK),
2337                                        StorageManager.UUID_PRIVATE_INTERNAL,
2338                                        SKIP_SHARED_LIBRARY_CHECK);
2339                            }
2340                        } catch (FileNotFoundException e) {
2341                            Slog.w(TAG, "Library not found: " + lib);
2342                        } catch (IOException | InstallerException e) {
2343                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2344                                    + e.getMessage());
2345                        }
2346                    }
2347                }
2348                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2349            }
2350
2351            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2352
2353            final VersionInfo ver = mSettings.getInternalVersion();
2354            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2355
2356            // when upgrading from pre-M, promote system app permissions from install to runtime
2357            mPromoteSystemApps =
2358                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2359
2360            // When upgrading from pre-N, we need to handle package extraction like first boot,
2361            // as there is no profiling data available.
2362            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2363
2364            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2365
2366            // save off the names of pre-existing system packages prior to scanning; we don't
2367            // want to automatically grant runtime permissions for new system apps
2368            if (mPromoteSystemApps) {
2369                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2370                while (pkgSettingIter.hasNext()) {
2371                    PackageSetting ps = pkgSettingIter.next();
2372                    if (isSystemApp(ps)) {
2373                        mExistingSystemPackages.add(ps.name);
2374                    }
2375                }
2376            }
2377
2378            mCacheDir = preparePackageParserCache(mIsUpgrade);
2379
2380            // Set flag to monitor and not change apk file paths when
2381            // scanning install directories.
2382            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2383
2384            if (mIsUpgrade || mFirstBoot) {
2385                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2386            }
2387
2388            // Collect vendor overlay packages. (Do this before scanning any apps.)
2389            // For security and version matching reason, only consider
2390            // overlay packages if they reside in the right directory.
2391            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2392            if (overlayThemeDir.isEmpty()) {
2393                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2394            }
2395            if (!overlayThemeDir.isEmpty()) {
2396                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2397                        | PackageParser.PARSE_IS_SYSTEM
2398                        | PackageParser.PARSE_IS_SYSTEM_DIR
2399                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2400            }
2401            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2402                    | PackageParser.PARSE_IS_SYSTEM
2403                    | PackageParser.PARSE_IS_SYSTEM_DIR
2404                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2405
2406            // Find base frameworks (resource packages without code).
2407            scanDirTracedLI(frameworkDir, mDefParseFlags
2408                    | PackageParser.PARSE_IS_SYSTEM
2409                    | PackageParser.PARSE_IS_SYSTEM_DIR
2410                    | PackageParser.PARSE_IS_PRIVILEGED,
2411                    scanFlags | SCAN_NO_DEX, 0);
2412
2413            // Collected privileged system packages.
2414            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2415            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2416                    | PackageParser.PARSE_IS_SYSTEM
2417                    | PackageParser.PARSE_IS_SYSTEM_DIR
2418                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2419
2420            // Collect ordinary system packages.
2421            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2422            scanDirTracedLI(systemAppDir, mDefParseFlags
2423                    | PackageParser.PARSE_IS_SYSTEM
2424                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2425
2426            // Collect all vendor packages.
2427            File vendorAppDir = new File("/vendor/app");
2428            try {
2429                vendorAppDir = vendorAppDir.getCanonicalFile();
2430            } catch (IOException e) {
2431                // failed to look up canonical path, continue with original one
2432            }
2433            scanDirTracedLI(vendorAppDir, mDefParseFlags
2434                    | PackageParser.PARSE_IS_SYSTEM
2435                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2436
2437            // Collect all OEM packages.
2438            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2439            scanDirTracedLI(oemAppDir, mDefParseFlags
2440                    | PackageParser.PARSE_IS_SYSTEM
2441                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2442
2443            // Prune any system packages that no longer exist.
2444            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2445            if (!mOnlyCore) {
2446                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2447                while (psit.hasNext()) {
2448                    PackageSetting ps = psit.next();
2449
2450                    /*
2451                     * If this is not a system app, it can't be a
2452                     * disable system app.
2453                     */
2454                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2455                        continue;
2456                    }
2457
2458                    /*
2459                     * If the package is scanned, it's not erased.
2460                     */
2461                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2462                    if (scannedPkg != null) {
2463                        /*
2464                         * If the system app is both scanned and in the
2465                         * disabled packages list, then it must have been
2466                         * added via OTA. Remove it from the currently
2467                         * scanned package so the previously user-installed
2468                         * application can be scanned.
2469                         */
2470                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2471                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2472                                    + ps.name + "; removing system app.  Last known codePath="
2473                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2474                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2475                                    + scannedPkg.mVersionCode);
2476                            removePackageLI(scannedPkg, true);
2477                            mExpectingBetter.put(ps.name, ps.codePath);
2478                        }
2479
2480                        continue;
2481                    }
2482
2483                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2484                        psit.remove();
2485                        logCriticalInfo(Log.WARN, "System package " + ps.name
2486                                + " no longer exists; it's data will be wiped");
2487                        // Actual deletion of code and data will be handled by later
2488                        // reconciliation step
2489                    } else {
2490                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2491                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2492                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2493                        }
2494                    }
2495                }
2496            }
2497
2498            //look for any incomplete package installations
2499            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2500            for (int i = 0; i < deletePkgsList.size(); i++) {
2501                // Actual deletion of code and data will be handled by later
2502                // reconciliation step
2503                final String packageName = deletePkgsList.get(i).name;
2504                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2505                synchronized (mPackages) {
2506                    mSettings.removePackageLPw(packageName);
2507                }
2508            }
2509
2510            //delete tmp files
2511            deleteTempPackageFiles();
2512
2513            // Remove any shared userIDs that have no associated packages
2514            mSettings.pruneSharedUsersLPw();
2515
2516            if (!mOnlyCore) {
2517                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2518                        SystemClock.uptimeMillis());
2519                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2520
2521                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2522                        | PackageParser.PARSE_FORWARD_LOCK,
2523                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2524
2525                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2526                        | PackageParser.PARSE_IS_EPHEMERAL,
2527                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2528
2529                /**
2530                 * Remove disable package settings for any updated system
2531                 * apps that were removed via an OTA. If they're not a
2532                 * previously-updated app, remove them completely.
2533                 * Otherwise, just revoke their system-level permissions.
2534                 */
2535                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2536                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2537                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2538
2539                    String msg;
2540                    if (deletedPkg == null) {
2541                        msg = "Updated system package " + deletedAppName
2542                                + " no longer exists; it's data will be wiped";
2543                        // Actual deletion of code and data will be handled by later
2544                        // reconciliation step
2545                    } else {
2546                        msg = "Updated system app + " + deletedAppName
2547                                + " no longer present; removing system privileges for "
2548                                + deletedAppName;
2549
2550                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2551
2552                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2553                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2554                    }
2555                    logCriticalInfo(Log.WARN, msg);
2556                }
2557
2558                /**
2559                 * Make sure all system apps that we expected to appear on
2560                 * the userdata partition actually showed up. If they never
2561                 * appeared, crawl back and revive the system version.
2562                 */
2563                for (int i = 0; i < mExpectingBetter.size(); i++) {
2564                    final String packageName = mExpectingBetter.keyAt(i);
2565                    if (!mPackages.containsKey(packageName)) {
2566                        final File scanFile = mExpectingBetter.valueAt(i);
2567
2568                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2569                                + " but never showed up; reverting to system");
2570
2571                        int reparseFlags = mDefParseFlags;
2572                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2573                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2574                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2575                                    | PackageParser.PARSE_IS_PRIVILEGED;
2576                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2577                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2578                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2579                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2580                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2581                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2582                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2583                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2584                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2585                        } else {
2586                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2587                            continue;
2588                        }
2589
2590                        mSettings.enableSystemPackageLPw(packageName);
2591
2592                        try {
2593                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2594                        } catch (PackageManagerException e) {
2595                            Slog.e(TAG, "Failed to parse original system package: "
2596                                    + e.getMessage());
2597                        }
2598                    }
2599                }
2600            }
2601            mExpectingBetter.clear();
2602
2603            // Resolve the storage manager.
2604            mStorageManagerPackage = getStorageManagerPackageName();
2605
2606            // Resolve protected action filters. Only the setup wizard is allowed to
2607            // have a high priority filter for these actions.
2608            mSetupWizardPackage = getSetupWizardPackageName();
2609            if (mProtectedFilters.size() > 0) {
2610                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2611                    Slog.i(TAG, "No setup wizard;"
2612                        + " All protected intents capped to priority 0");
2613                }
2614                for (ActivityIntentInfo filter : mProtectedFilters) {
2615                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2616                        if (DEBUG_FILTERS) {
2617                            Slog.i(TAG, "Found setup wizard;"
2618                                + " allow priority " + filter.getPriority() + ";"
2619                                + " package: " + filter.activity.info.packageName
2620                                + " activity: " + filter.activity.className
2621                                + " priority: " + filter.getPriority());
2622                        }
2623                        // skip setup wizard; allow it to keep the high priority filter
2624                        continue;
2625                    }
2626                    Slog.w(TAG, "Protected action; cap priority to 0;"
2627                            + " package: " + filter.activity.info.packageName
2628                            + " activity: " + filter.activity.className
2629                            + " origPrio: " + filter.getPriority());
2630                    filter.setPriority(0);
2631                }
2632            }
2633            mDeferProtectedFilters = false;
2634            mProtectedFilters.clear();
2635
2636            // Now that we know all of the shared libraries, update all clients to have
2637            // the correct library paths.
2638            updateAllSharedLibrariesLPw();
2639
2640            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2641                // NOTE: We ignore potential failures here during a system scan (like
2642                // the rest of the commands above) because there's precious little we
2643                // can do about it. A settings error is reported, though.
2644                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2645            }
2646
2647            // Now that we know all the packages we are keeping,
2648            // read and update their last usage times.
2649            mPackageUsage.read(mPackages);
2650            mCompilerStats.read();
2651
2652            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2653                    SystemClock.uptimeMillis());
2654            Slog.i(TAG, "Time to scan packages: "
2655                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2656                    + " seconds");
2657
2658            // If the platform SDK has changed since the last time we booted,
2659            // we need to re-grant app permission to catch any new ones that
2660            // appear.  This is really a hack, and means that apps can in some
2661            // cases get permissions that the user didn't initially explicitly
2662            // allow...  it would be nice to have some better way to handle
2663            // this situation.
2664            int updateFlags = UPDATE_PERMISSIONS_ALL;
2665            if (ver.sdkVersion != mSdkVersion) {
2666                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2667                        + mSdkVersion + "; regranting permissions for internal storage");
2668                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2669            }
2670            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2671            ver.sdkVersion = mSdkVersion;
2672
2673            // If this is the first boot or an update from pre-M, and it is a normal
2674            // boot, then we need to initialize the default preferred apps across
2675            // all defined users.
2676            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2677                for (UserInfo user : sUserManager.getUsers(true)) {
2678                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2679                    applyFactoryDefaultBrowserLPw(user.id);
2680                    primeDomainVerificationsLPw(user.id);
2681                }
2682            }
2683
2684            // Prepare storage for system user really early during boot,
2685            // since core system apps like SettingsProvider and SystemUI
2686            // can't wait for user to start
2687            final int storageFlags;
2688            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2689                storageFlags = StorageManager.FLAG_STORAGE_DE;
2690            } else {
2691                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2692            }
2693            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2694                    storageFlags, true /* migrateAppData */);
2695
2696            // If this is first boot after an OTA, and a normal boot, then
2697            // we need to clear code cache directories.
2698            // Note that we do *not* clear the application profiles. These remain valid
2699            // across OTAs and are used to drive profile verification (post OTA) and
2700            // profile compilation (without waiting to collect a fresh set of profiles).
2701            if (mIsUpgrade && !onlyCore) {
2702                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2703                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2704                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2705                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2706                        // No apps are running this early, so no need to freeze
2707                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2708                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2709                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2710                    }
2711                }
2712                ver.fingerprint = Build.FINGERPRINT;
2713            }
2714
2715            checkDefaultBrowser();
2716
2717            // clear only after permissions and other defaults have been updated
2718            mExistingSystemPackages.clear();
2719            mPromoteSystemApps = false;
2720
2721            // All the changes are done during package scanning.
2722            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2723
2724            // can downgrade to reader
2725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2726            mSettings.writeLPr();
2727            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2728
2729            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2730            // early on (before the package manager declares itself as early) because other
2731            // components in the system server might ask for package contexts for these apps.
2732            //
2733            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2734            // (i.e, that the data partition is unavailable).
2735            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2736                long start = System.nanoTime();
2737                List<PackageParser.Package> coreApps = new ArrayList<>();
2738                for (PackageParser.Package pkg : mPackages.values()) {
2739                    if (pkg.coreApp) {
2740                        coreApps.add(pkg);
2741                    }
2742                }
2743
2744                int[] stats = performDexOptUpgrade(coreApps, false,
2745                        getCompilerFilterForReason(REASON_CORE_APP));
2746
2747                final int elapsedTimeSeconds =
2748                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2749                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2750
2751                if (DEBUG_DEXOPT) {
2752                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2753                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2754                }
2755
2756
2757                // TODO: Should we log these stats to tron too ?
2758                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2759                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2760                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2761                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2762            }
2763
2764            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2765                    SystemClock.uptimeMillis());
2766
2767            if (!mOnlyCore) {
2768                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2769                mRequiredInstallerPackage = getRequiredInstallerLPr();
2770                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2771                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2772                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2773                        mIntentFilterVerifierComponent);
2774                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2775                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2776                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2777                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2778            } else {
2779                mRequiredVerifierPackage = null;
2780                mRequiredInstallerPackage = null;
2781                mRequiredUninstallerPackage = null;
2782                mIntentFilterVerifierComponent = null;
2783                mIntentFilterVerifier = null;
2784                mServicesSystemSharedLibraryPackageName = null;
2785                mSharedSystemSharedLibraryPackageName = null;
2786            }
2787
2788            mInstallerService = new PackageInstallerService(context, this);
2789
2790            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2791            if (ephemeralResolverComponent != null) {
2792                if (DEBUG_EPHEMERAL) {
2793                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2794                }
2795                mEphemeralResolverConnection =
2796                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2797            } else {
2798                mEphemeralResolverConnection = null;
2799            }
2800            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2801            if (mEphemeralInstallerComponent != null) {
2802                if (DEBUG_EPHEMERAL) {
2803                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2804                }
2805                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2806            }
2807
2808            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2809
2810            // Read and update the usage of dex files.
2811            // Do this at the end of PM init so that all the packages have their
2812            // data directory reconciled.
2813            // At this point we know the code paths of the packages, so we can validate
2814            // the disk file and build the internal cache.
2815            // The usage file is expected to be small so loading and verifying it
2816            // should take a fairly small time compare to the other activities (e.g. package
2817            // scanning).
2818            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2819            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2820            for (int userId : currentUserIds) {
2821                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2822            }
2823            mDexManager.load(userPackages);
2824        } // synchronized (mPackages)
2825        } // synchronized (mInstallLock)
2826
2827        // Now after opening every single application zip, make sure they
2828        // are all flushed.  Not really needed, but keeps things nice and
2829        // tidy.
2830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2831        Runtime.getRuntime().gc();
2832        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2833
2834        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2835        FallbackCategoryProvider.loadFallbacks();
2836        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2837
2838        // The initial scanning above does many calls into installd while
2839        // holding the mPackages lock, but we're mostly interested in yelling
2840        // once we have a booted system.
2841        mInstaller.setWarnIfHeld(mPackages);
2842
2843        // Expose private service for system components to use.
2844        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2845        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2846    }
2847
2848    private static File preparePackageParserCache(boolean isUpgrade) {
2849        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2850            return null;
2851        }
2852
2853        // Disable package parsing on eng builds to allow for faster incremental development.
2854        if ("eng".equals(Build.TYPE)) {
2855            return null;
2856        }
2857
2858        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2859            Slog.i(TAG, "Disabling package parser cache due to system property.");
2860            return null;
2861        }
2862
2863        // The base directory for the package parser cache lives under /data/system/.
2864        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2865                "package_cache");
2866        if (cacheBaseDir == null) {
2867            return null;
2868        }
2869
2870        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2871        // This also serves to "GC" unused entries when the package cache version changes (which
2872        // can only happen during upgrades).
2873        if (isUpgrade) {
2874            FileUtils.deleteContents(cacheBaseDir);
2875        }
2876
2877
2878        // Return the versioned package cache directory. This is something like
2879        // "/data/system/package_cache/1"
2880        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2881
2882        // The following is a workaround to aid development on non-numbered userdebug
2883        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2884        // the system partition is newer.
2885        //
2886        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2887        // that starts with "eng." to signify that this is an engineering build and not
2888        // destined for release.
2889        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2890            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2891
2892            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2893            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2894            // in general and should not be used for production changes. In this specific case,
2895            // we know that they will work.
2896            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2897            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2898                FileUtils.deleteContents(cacheBaseDir);
2899                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2900            }
2901        }
2902
2903        return cacheDir;
2904    }
2905
2906    @Override
2907    public boolean isFirstBoot() {
2908        return mFirstBoot;
2909    }
2910
2911    @Override
2912    public boolean isOnlyCoreApps() {
2913        return mOnlyCore;
2914    }
2915
2916    @Override
2917    public boolean isUpgrade() {
2918        return mIsUpgrade;
2919    }
2920
2921    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2922        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2923
2924        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2925                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2926                UserHandle.USER_SYSTEM);
2927        if (matches.size() == 1) {
2928            return matches.get(0).getComponentInfo().packageName;
2929        } else if (matches.size() == 0) {
2930            Log.e(TAG, "There should probably be a verifier, but, none were found");
2931            return null;
2932        }
2933        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2934    }
2935
2936    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2937        synchronized (mPackages) {
2938            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2939            if (libraryEntry == null) {
2940                throw new IllegalStateException("Missing required shared library:" + libraryName);
2941            }
2942            return libraryEntry.apk;
2943        }
2944    }
2945
2946    private @NonNull String getRequiredInstallerLPr() {
2947        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2948        intent.addCategory(Intent.CATEGORY_DEFAULT);
2949        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2950
2951        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2952                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2953                UserHandle.USER_SYSTEM);
2954        if (matches.size() == 1) {
2955            ResolveInfo resolveInfo = matches.get(0);
2956            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2957                throw new RuntimeException("The installer must be a privileged app");
2958            }
2959            return matches.get(0).getComponentInfo().packageName;
2960        } else {
2961            throw new RuntimeException("There must be exactly one installer; found " + matches);
2962        }
2963    }
2964
2965    private @NonNull String getRequiredUninstallerLPr() {
2966        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2967        intent.addCategory(Intent.CATEGORY_DEFAULT);
2968        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2969
2970        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2971                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2972                UserHandle.USER_SYSTEM);
2973        if (resolveInfo == null ||
2974                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2975            throw new RuntimeException("There must be exactly one uninstaller; found "
2976                    + resolveInfo);
2977        }
2978        return resolveInfo.getComponentInfo().packageName;
2979    }
2980
2981    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2982        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2983
2984        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2985                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2986                UserHandle.USER_SYSTEM);
2987        ResolveInfo best = null;
2988        final int N = matches.size();
2989        for (int i = 0; i < N; i++) {
2990            final ResolveInfo cur = matches.get(i);
2991            final String packageName = cur.getComponentInfo().packageName;
2992            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2993                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2994                continue;
2995            }
2996
2997            if (best == null || cur.priority > best.priority) {
2998                best = cur;
2999            }
3000        }
3001
3002        if (best != null) {
3003            return best.getComponentInfo().getComponentName();
3004        } else {
3005            throw new RuntimeException("There must be at least one intent filter verifier");
3006        }
3007    }
3008
3009    private @Nullable ComponentName getEphemeralResolverLPr() {
3010        final String[] packageArray =
3011                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3012        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3013            if (DEBUG_EPHEMERAL) {
3014                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3015            }
3016            return null;
3017        }
3018
3019        final int resolveFlags =
3020                MATCH_DIRECT_BOOT_AWARE
3021                | MATCH_DIRECT_BOOT_UNAWARE
3022                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3023        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3024        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3025                resolveFlags, UserHandle.USER_SYSTEM);
3026
3027        final int N = resolvers.size();
3028        if (N == 0) {
3029            if (DEBUG_EPHEMERAL) {
3030                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3031            }
3032            return null;
3033        }
3034
3035        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3036        for (int i = 0; i < N; i++) {
3037            final ResolveInfo info = resolvers.get(i);
3038
3039            if (info.serviceInfo == null) {
3040                continue;
3041            }
3042
3043            final String packageName = info.serviceInfo.packageName;
3044            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3045                if (DEBUG_EPHEMERAL) {
3046                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3047                            + " pkg: " + packageName + ", info:" + info);
3048                }
3049                continue;
3050            }
3051
3052            if (DEBUG_EPHEMERAL) {
3053                Slog.v(TAG, "Ephemeral resolver found;"
3054                        + " pkg: " + packageName + ", info:" + info);
3055            }
3056            return new ComponentName(packageName, info.serviceInfo.name);
3057        }
3058        if (DEBUG_EPHEMERAL) {
3059            Slog.v(TAG, "Ephemeral resolver NOT found");
3060        }
3061        return null;
3062    }
3063
3064    private @Nullable ComponentName getEphemeralInstallerLPr() {
3065        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3066        intent.addCategory(Intent.CATEGORY_DEFAULT);
3067        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3068
3069        final int resolveFlags =
3070                MATCH_DIRECT_BOOT_AWARE
3071                | MATCH_DIRECT_BOOT_UNAWARE
3072                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3073        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3074                resolveFlags, UserHandle.USER_SYSTEM);
3075        Iterator<ResolveInfo> iter = matches.iterator();
3076        while (iter.hasNext()) {
3077            final ResolveInfo rInfo = iter.next();
3078            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3079            if (ps != null) {
3080                final PermissionsState permissionsState = ps.getPermissionsState();
3081                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3082                    continue;
3083                }
3084            }
3085            iter.remove();
3086        }
3087        if (matches.size() == 0) {
3088            return null;
3089        } else if (matches.size() == 1) {
3090            return matches.get(0).getComponentInfo().getComponentName();
3091        } else {
3092            throw new RuntimeException(
3093                    "There must be at most one ephemeral installer; found " + matches);
3094        }
3095    }
3096
3097    private void primeDomainVerificationsLPw(int userId) {
3098        if (DEBUG_DOMAIN_VERIFICATION) {
3099            Slog.d(TAG, "Priming domain verifications in user " + userId);
3100        }
3101
3102        SystemConfig systemConfig = SystemConfig.getInstance();
3103        ArraySet<String> packages = systemConfig.getLinkedApps();
3104
3105        for (String packageName : packages) {
3106            PackageParser.Package pkg = mPackages.get(packageName);
3107            if (pkg != null) {
3108                if (!pkg.isSystemApp()) {
3109                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3110                    continue;
3111                }
3112
3113                ArraySet<String> domains = null;
3114                for (PackageParser.Activity a : pkg.activities) {
3115                    for (ActivityIntentInfo filter : a.intents) {
3116                        if (hasValidDomains(filter)) {
3117                            if (domains == null) {
3118                                domains = new ArraySet<String>();
3119                            }
3120                            domains.addAll(filter.getHostsList());
3121                        }
3122                    }
3123                }
3124
3125                if (domains != null && domains.size() > 0) {
3126                    if (DEBUG_DOMAIN_VERIFICATION) {
3127                        Slog.v(TAG, "      + " + packageName);
3128                    }
3129                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3130                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3131                    // and then 'always' in the per-user state actually used for intent resolution.
3132                    final IntentFilterVerificationInfo ivi;
3133                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3134                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3135                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3136                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3137                } else {
3138                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3139                            + "' does not handle web links");
3140                }
3141            } else {
3142                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3143            }
3144        }
3145
3146        scheduleWritePackageRestrictionsLocked(userId);
3147        scheduleWriteSettingsLocked();
3148    }
3149
3150    private void applyFactoryDefaultBrowserLPw(int userId) {
3151        // The default browser app's package name is stored in a string resource,
3152        // with a product-specific overlay used for vendor customization.
3153        String browserPkg = mContext.getResources().getString(
3154                com.android.internal.R.string.default_browser);
3155        if (!TextUtils.isEmpty(browserPkg)) {
3156            // non-empty string => required to be a known package
3157            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3158            if (ps == null) {
3159                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3160                browserPkg = null;
3161            } else {
3162                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3163            }
3164        }
3165
3166        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3167        // default.  If there's more than one, just leave everything alone.
3168        if (browserPkg == null) {
3169            calculateDefaultBrowserLPw(userId);
3170        }
3171    }
3172
3173    private void calculateDefaultBrowserLPw(int userId) {
3174        List<String> allBrowsers = resolveAllBrowserApps(userId);
3175        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3176        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3177    }
3178
3179    private List<String> resolveAllBrowserApps(int userId) {
3180        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3181        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3182                PackageManager.MATCH_ALL, userId);
3183
3184        final int count = list.size();
3185        List<String> result = new ArrayList<String>(count);
3186        for (int i=0; i<count; i++) {
3187            ResolveInfo info = list.get(i);
3188            if (info.activityInfo == null
3189                    || !info.handleAllWebDataURI
3190                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3191                    || result.contains(info.activityInfo.packageName)) {
3192                continue;
3193            }
3194            result.add(info.activityInfo.packageName);
3195        }
3196
3197        return result;
3198    }
3199
3200    private boolean packageIsBrowser(String packageName, int userId) {
3201        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3202                PackageManager.MATCH_ALL, userId);
3203        final int N = list.size();
3204        for (int i = 0; i < N; i++) {
3205            ResolveInfo info = list.get(i);
3206            if (packageName.equals(info.activityInfo.packageName)) {
3207                return true;
3208            }
3209        }
3210        return false;
3211    }
3212
3213    private void checkDefaultBrowser() {
3214        final int myUserId = UserHandle.myUserId();
3215        final String packageName = getDefaultBrowserPackageName(myUserId);
3216        if (packageName != null) {
3217            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3218            if (info == null) {
3219                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3220                synchronized (mPackages) {
3221                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3222                }
3223            }
3224        }
3225    }
3226
3227    @Override
3228    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3229            throws RemoteException {
3230        try {
3231            return super.onTransact(code, data, reply, flags);
3232        } catch (RuntimeException e) {
3233            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3234                Slog.wtf(TAG, "Package Manager Crash", e);
3235            }
3236            throw e;
3237        }
3238    }
3239
3240    static int[] appendInts(int[] cur, int[] add) {
3241        if (add == null) return cur;
3242        if (cur == null) return add;
3243        final int N = add.length;
3244        for (int i=0; i<N; i++) {
3245            cur = appendInt(cur, add[i]);
3246        }
3247        return cur;
3248    }
3249
3250    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3251        if (!sUserManager.exists(userId)) return null;
3252        if (ps == null) {
3253            return null;
3254        }
3255        final PackageParser.Package p = ps.pkg;
3256        if (p == null) {
3257            return null;
3258        }
3259
3260        final PermissionsState permissionsState = ps.getPermissionsState();
3261
3262        // Compute GIDs only if requested
3263        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3264                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3265        // Compute granted permissions only if package has requested permissions
3266        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3267                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3268        final PackageUserState state = ps.readUserState(userId);
3269
3270        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3271                && ps.isSystem()) {
3272            flags |= MATCH_ANY_USER;
3273        }
3274
3275        return PackageParser.generatePackageInfo(p, gids, flags,
3276                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3277    }
3278
3279    @Override
3280    public void checkPackageStartable(String packageName, int userId) {
3281        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3282
3283        synchronized (mPackages) {
3284            final PackageSetting ps = mSettings.mPackages.get(packageName);
3285            if (ps == null) {
3286                throw new SecurityException("Package " + packageName + " was not found!");
3287            }
3288
3289            if (!ps.getInstalled(userId)) {
3290                throw new SecurityException(
3291                        "Package " + packageName + " was not installed for user " + userId + "!");
3292            }
3293
3294            if (mSafeMode && !ps.isSystem()) {
3295                throw new SecurityException("Package " + packageName + " not a system app!");
3296            }
3297
3298            if (mFrozenPackages.contains(packageName)) {
3299                throw new SecurityException("Package " + packageName + " is currently frozen!");
3300            }
3301
3302            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3303                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3304                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3305            }
3306        }
3307    }
3308
3309    @Override
3310    public boolean isPackageAvailable(String packageName, int userId) {
3311        if (!sUserManager.exists(userId)) return false;
3312        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3313                false /* requireFullPermission */, false /* checkShell */, "is package available");
3314        synchronized (mPackages) {
3315            PackageParser.Package p = mPackages.get(packageName);
3316            if (p != null) {
3317                final PackageSetting ps = (PackageSetting) p.mExtras;
3318                if (ps != null) {
3319                    final PackageUserState state = ps.readUserState(userId);
3320                    if (state != null) {
3321                        return PackageParser.isAvailable(state);
3322                    }
3323                }
3324            }
3325        }
3326        return false;
3327    }
3328
3329    @Override
3330    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3331        if (!sUserManager.exists(userId)) return null;
3332        flags = updateFlagsForPackage(flags, userId, packageName);
3333        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3334                false /* requireFullPermission */, false /* checkShell */, "get package info");
3335
3336        // reader
3337        synchronized (mPackages) {
3338            // Normalize package name to hanlde renamed packages
3339            packageName = normalizePackageNameLPr(packageName);
3340
3341            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3342            PackageParser.Package p = null;
3343            if (matchFactoryOnly) {
3344                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3345                if (ps != null) {
3346                    return generatePackageInfo(ps, flags, userId);
3347                }
3348            }
3349            if (p == null) {
3350                p = mPackages.get(packageName);
3351                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3352                    return null;
3353                }
3354            }
3355            if (DEBUG_PACKAGE_INFO)
3356                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3357            if (p != null) {
3358                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3359            }
3360            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3361                final PackageSetting ps = mSettings.mPackages.get(packageName);
3362                return generatePackageInfo(ps, flags, userId);
3363            }
3364        }
3365        return null;
3366    }
3367
3368    @Override
3369    public String[] currentToCanonicalPackageNames(String[] names) {
3370        String[] out = new String[names.length];
3371        // reader
3372        synchronized (mPackages) {
3373            for (int i=names.length-1; i>=0; i--) {
3374                PackageSetting ps = mSettings.mPackages.get(names[i]);
3375                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3376            }
3377        }
3378        return out;
3379    }
3380
3381    @Override
3382    public String[] canonicalToCurrentPackageNames(String[] names) {
3383        String[] out = new String[names.length];
3384        // reader
3385        synchronized (mPackages) {
3386            for (int i=names.length-1; i>=0; i--) {
3387                String cur = mSettings.getRenamedPackageLPr(names[i]);
3388                out[i] = cur != null ? cur : names[i];
3389            }
3390        }
3391        return out;
3392    }
3393
3394    @Override
3395    public int getPackageUid(String packageName, int flags, int userId) {
3396        if (!sUserManager.exists(userId)) return -1;
3397        flags = updateFlagsForPackage(flags, userId, packageName);
3398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3399                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3400
3401        // reader
3402        synchronized (mPackages) {
3403            final PackageParser.Package p = mPackages.get(packageName);
3404            if (p != null && p.isMatch(flags)) {
3405                return UserHandle.getUid(userId, p.applicationInfo.uid);
3406            }
3407            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3408                final PackageSetting ps = mSettings.mPackages.get(packageName);
3409                if (ps != null && ps.isMatch(flags)) {
3410                    return UserHandle.getUid(userId, ps.appId);
3411                }
3412            }
3413        }
3414
3415        return -1;
3416    }
3417
3418    @Override
3419    public int[] getPackageGids(String packageName, int flags, int userId) {
3420        if (!sUserManager.exists(userId)) return null;
3421        flags = updateFlagsForPackage(flags, userId, packageName);
3422        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3423                false /* requireFullPermission */, false /* checkShell */,
3424                "getPackageGids");
3425
3426        // reader
3427        synchronized (mPackages) {
3428            final PackageParser.Package p = mPackages.get(packageName);
3429            if (p != null && p.isMatch(flags)) {
3430                PackageSetting ps = (PackageSetting) p.mExtras;
3431                // TODO: Shouldn't this be checking for package installed state for userId and
3432                // return null?
3433                return ps.getPermissionsState().computeGids(userId);
3434            }
3435            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3436                final PackageSetting ps = mSettings.mPackages.get(packageName);
3437                if (ps != null && ps.isMatch(flags)) {
3438                    return ps.getPermissionsState().computeGids(userId);
3439                }
3440            }
3441        }
3442
3443        return null;
3444    }
3445
3446    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3447        if (bp.perm != null) {
3448            return PackageParser.generatePermissionInfo(bp.perm, flags);
3449        }
3450        PermissionInfo pi = new PermissionInfo();
3451        pi.name = bp.name;
3452        pi.packageName = bp.sourcePackage;
3453        pi.nonLocalizedLabel = bp.name;
3454        pi.protectionLevel = bp.protectionLevel;
3455        return pi;
3456    }
3457
3458    @Override
3459    public PermissionInfo getPermissionInfo(String name, int flags) {
3460        // reader
3461        synchronized (mPackages) {
3462            final BasePermission p = mSettings.mPermissions.get(name);
3463            if (p != null) {
3464                return generatePermissionInfo(p, flags);
3465            }
3466            return null;
3467        }
3468    }
3469
3470    @Override
3471    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3472            int flags) {
3473        // reader
3474        synchronized (mPackages) {
3475            if (group != null && !mPermissionGroups.containsKey(group)) {
3476                // This is thrown as NameNotFoundException
3477                return null;
3478            }
3479
3480            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3481            for (BasePermission p : mSettings.mPermissions.values()) {
3482                if (group == null) {
3483                    if (p.perm == null || p.perm.info.group == null) {
3484                        out.add(generatePermissionInfo(p, flags));
3485                    }
3486                } else {
3487                    if (p.perm != null && group.equals(p.perm.info.group)) {
3488                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3489                    }
3490                }
3491            }
3492            return new ParceledListSlice<>(out);
3493        }
3494    }
3495
3496    @Override
3497    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3498        // reader
3499        synchronized (mPackages) {
3500            return PackageParser.generatePermissionGroupInfo(
3501                    mPermissionGroups.get(name), flags);
3502        }
3503    }
3504
3505    @Override
3506    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3507        // reader
3508        synchronized (mPackages) {
3509            final int N = mPermissionGroups.size();
3510            ArrayList<PermissionGroupInfo> out
3511                    = new ArrayList<PermissionGroupInfo>(N);
3512            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3513                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3514            }
3515            return new ParceledListSlice<>(out);
3516        }
3517    }
3518
3519    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3520            int userId) {
3521        if (!sUserManager.exists(userId)) return null;
3522        PackageSetting ps = mSettings.mPackages.get(packageName);
3523        if (ps != null) {
3524            if (ps.pkg == null) {
3525                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3526                if (pInfo != null) {
3527                    return pInfo.applicationInfo;
3528                }
3529                return null;
3530            }
3531            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3532                    ps.readUserState(userId), userId);
3533        }
3534        return null;
3535    }
3536
3537    @Override
3538    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3539        if (!sUserManager.exists(userId)) return null;
3540        flags = updateFlagsForApplication(flags, userId, packageName);
3541        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3542                false /* requireFullPermission */, false /* checkShell */, "get application info");
3543
3544        // writer
3545        synchronized (mPackages) {
3546            // Normalize package name to hanlde renamed packages
3547            packageName = normalizePackageNameLPr(packageName);
3548
3549            PackageParser.Package p = mPackages.get(packageName);
3550            if (DEBUG_PACKAGE_INFO) Log.v(
3551                    TAG, "getApplicationInfo " + packageName
3552                    + ": " + p);
3553            if (p != null) {
3554                PackageSetting ps = mSettings.mPackages.get(packageName);
3555                if (ps == null) return null;
3556                // Note: isEnabledLP() does not apply here - always return info
3557                return PackageParser.generateApplicationInfo(
3558                        p, flags, ps.readUserState(userId), userId);
3559            }
3560            if ("android".equals(packageName)||"system".equals(packageName)) {
3561                return mAndroidApplication;
3562            }
3563            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3564                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3565            }
3566        }
3567        return null;
3568    }
3569
3570    private String normalizePackageNameLPr(String packageName) {
3571        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3572        return normalizedPackageName != null ? normalizedPackageName : packageName;
3573    }
3574
3575    @Override
3576    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3577            final IPackageDataObserver observer) {
3578        mContext.enforceCallingOrSelfPermission(
3579                android.Manifest.permission.CLEAR_APP_CACHE, null);
3580        // Queue up an async operation since clearing cache may take a little while.
3581        mHandler.post(new Runnable() {
3582            public void run() {
3583                mHandler.removeCallbacks(this);
3584                boolean success = true;
3585                synchronized (mInstallLock) {
3586                    try {
3587                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3588                    } catch (InstallerException e) {
3589                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3590                        success = false;
3591                    }
3592                }
3593                if (observer != null) {
3594                    try {
3595                        observer.onRemoveCompleted(null, success);
3596                    } catch (RemoteException e) {
3597                        Slog.w(TAG, "RemoveException when invoking call back");
3598                    }
3599                }
3600            }
3601        });
3602    }
3603
3604    @Override
3605    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3606            final IntentSender pi) {
3607        mContext.enforceCallingOrSelfPermission(
3608                android.Manifest.permission.CLEAR_APP_CACHE, null);
3609        // Queue up an async operation since clearing cache may take a little while.
3610        mHandler.post(new Runnable() {
3611            public void run() {
3612                mHandler.removeCallbacks(this);
3613                boolean success = true;
3614                synchronized (mInstallLock) {
3615                    try {
3616                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3617                    } catch (InstallerException e) {
3618                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3619                        success = false;
3620                    }
3621                }
3622                if(pi != null) {
3623                    try {
3624                        // Callback via pending intent
3625                        int code = success ? 1 : 0;
3626                        pi.sendIntent(null, code, null,
3627                                null, null);
3628                    } catch (SendIntentException e1) {
3629                        Slog.i(TAG, "Failed to send pending intent");
3630                    }
3631                }
3632            }
3633        });
3634    }
3635
3636    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3637        synchronized (mInstallLock) {
3638            try {
3639                mInstaller.freeCache(volumeUuid, freeStorageSize);
3640            } catch (InstallerException e) {
3641                throw new IOException("Failed to free enough space", e);
3642            }
3643        }
3644    }
3645
3646    /**
3647     * Update given flags based on encryption status of current user.
3648     */
3649    private int updateFlags(int flags, int userId) {
3650        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3651                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3652            // Caller expressed an explicit opinion about what encryption
3653            // aware/unaware components they want to see, so fall through and
3654            // give them what they want
3655        } else {
3656            // Caller expressed no opinion, so match based on user state
3657            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3658                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3659            } else {
3660                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3661            }
3662        }
3663        return flags;
3664    }
3665
3666    private UserManagerInternal getUserManagerInternal() {
3667        if (mUserManagerInternal == null) {
3668            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3669        }
3670        return mUserManagerInternal;
3671    }
3672
3673    /**
3674     * Update given flags when being used to request {@link PackageInfo}.
3675     */
3676    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3677        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3678        boolean triaged = true;
3679        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3680                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3681            // Caller is asking for component details, so they'd better be
3682            // asking for specific encryption matching behavior, or be triaged
3683            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3684                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3685                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3686                triaged = false;
3687            }
3688        }
3689        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3690                | PackageManager.MATCH_SYSTEM_ONLY
3691                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3692            triaged = false;
3693        }
3694        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3695            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3696                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3697                    + Debug.getCallers(5));
3698        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3699                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3700            // If the caller wants all packages and has a restricted profile associated with it,
3701            // then match all users. This is to make sure that launchers that need to access work
3702            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3703            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3704            flags |= PackageManager.MATCH_ANY_USER;
3705        }
3706        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3707            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3708                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3709        }
3710        return updateFlags(flags, userId);
3711    }
3712
3713    /**
3714     * Update given flags when being used to request {@link ApplicationInfo}.
3715     */
3716    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3717        return updateFlagsForPackage(flags, userId, cookie);
3718    }
3719
3720    /**
3721     * Update given flags when being used to request {@link ComponentInfo}.
3722     */
3723    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3724        if (cookie instanceof Intent) {
3725            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3726                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3727            }
3728        }
3729
3730        boolean triaged = true;
3731        // Caller is asking for component details, so they'd better be
3732        // asking for specific encryption matching behavior, or be triaged
3733        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3734                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3735                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3736            triaged = false;
3737        }
3738        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3739            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3740                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3741        }
3742
3743        return updateFlags(flags, userId);
3744    }
3745
3746    /**
3747     * Update given flags when being used to request {@link ResolveInfo}.
3748     */
3749    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3750        // Safe mode means we shouldn't match any third-party components
3751        if (mSafeMode) {
3752            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3753        }
3754        final int callingUid = Binder.getCallingUid();
3755        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3756            // The system sees all components
3757            flags |= PackageManager.MATCH_EPHEMERAL;
3758        } else if (getEphemeralPackageName(callingUid) != null) {
3759            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3760            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3761            flags |= PackageManager.MATCH_EPHEMERAL;
3762        } else {
3763            // Otherwise, prevent leaking ephemeral components
3764            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3765            flags &= ~PackageManager.MATCH_EPHEMERAL;
3766        }
3767        return updateFlagsForComponent(flags, userId, cookie);
3768    }
3769
3770    @Override
3771    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3772        if (!sUserManager.exists(userId)) return null;
3773        flags = updateFlagsForComponent(flags, userId, component);
3774        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3775                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3776        synchronized (mPackages) {
3777            PackageParser.Activity a = mActivities.mActivities.get(component);
3778
3779            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3780            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3781                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3782                if (ps == null) return null;
3783                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3784                        userId);
3785            }
3786            if (mResolveComponentName.equals(component)) {
3787                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3788                        new PackageUserState(), userId);
3789            }
3790        }
3791        return null;
3792    }
3793
3794    @Override
3795    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3796            String resolvedType) {
3797        synchronized (mPackages) {
3798            if (component.equals(mResolveComponentName)) {
3799                // The resolver supports EVERYTHING!
3800                return true;
3801            }
3802            PackageParser.Activity a = mActivities.mActivities.get(component);
3803            if (a == null) {
3804                return false;
3805            }
3806            for (int i=0; i<a.intents.size(); i++) {
3807                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3808                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3809                    return true;
3810                }
3811            }
3812            return false;
3813        }
3814    }
3815
3816    @Override
3817    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3818        if (!sUserManager.exists(userId)) return null;
3819        flags = updateFlagsForComponent(flags, userId, component);
3820        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3821                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3822        synchronized (mPackages) {
3823            PackageParser.Activity a = mReceivers.mActivities.get(component);
3824            if (DEBUG_PACKAGE_INFO) Log.v(
3825                TAG, "getReceiverInfo " + component + ": " + a);
3826            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3827                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3828                if (ps == null) return null;
3829                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3830                        userId);
3831            }
3832        }
3833        return null;
3834    }
3835
3836    @Override
3837    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3838        if (!sUserManager.exists(userId)) return null;
3839        flags = updateFlagsForComponent(flags, userId, component);
3840        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3841                false /* requireFullPermission */, false /* checkShell */, "get service info");
3842        synchronized (mPackages) {
3843            PackageParser.Service s = mServices.mServices.get(component);
3844            if (DEBUG_PACKAGE_INFO) Log.v(
3845                TAG, "getServiceInfo " + component + ": " + s);
3846            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3847                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3848                if (ps == null) return null;
3849                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3850                        userId);
3851            }
3852        }
3853        return null;
3854    }
3855
3856    @Override
3857    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3858        if (!sUserManager.exists(userId)) return null;
3859        flags = updateFlagsForComponent(flags, userId, component);
3860        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3861                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3862        synchronized (mPackages) {
3863            PackageParser.Provider p = mProviders.mProviders.get(component);
3864            if (DEBUG_PACKAGE_INFO) Log.v(
3865                TAG, "getProviderInfo " + component + ": " + p);
3866            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3867                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3868                if (ps == null) return null;
3869                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3870                        userId);
3871            }
3872        }
3873        return null;
3874    }
3875
3876    @Override
3877    public String[] getSystemSharedLibraryNames() {
3878        Set<String> libSet;
3879        synchronized (mPackages) {
3880            libSet = mSharedLibraries.keySet();
3881            int size = libSet.size();
3882            if (size > 0) {
3883                String[] libs = new String[size];
3884                libSet.toArray(libs);
3885                return libs;
3886            }
3887        }
3888        return null;
3889    }
3890
3891    @Override
3892    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3893        synchronized (mPackages) {
3894            return mServicesSystemSharedLibraryPackageName;
3895        }
3896    }
3897
3898    @Override
3899    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3900        synchronized (mPackages) {
3901            return mSharedSystemSharedLibraryPackageName;
3902        }
3903    }
3904
3905    @Override
3906    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3907        synchronized (mPackages) {
3908            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3909
3910            final FeatureInfo fi = new FeatureInfo();
3911            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3912                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3913            res.add(fi);
3914
3915            return new ParceledListSlice<>(res);
3916        }
3917    }
3918
3919    @Override
3920    public boolean hasSystemFeature(String name, int version) {
3921        synchronized (mPackages) {
3922            final FeatureInfo feat = mAvailableFeatures.get(name);
3923            if (feat == null) {
3924                return false;
3925            } else {
3926                return feat.version >= version;
3927            }
3928        }
3929    }
3930
3931    @Override
3932    public int checkPermission(String permName, String pkgName, int userId) {
3933        if (!sUserManager.exists(userId)) {
3934            return PackageManager.PERMISSION_DENIED;
3935        }
3936
3937        synchronized (mPackages) {
3938            final PackageParser.Package p = mPackages.get(pkgName);
3939            if (p != null && p.mExtras != null) {
3940                final PackageSetting ps = (PackageSetting) p.mExtras;
3941                final PermissionsState permissionsState = ps.getPermissionsState();
3942                if (permissionsState.hasPermission(permName, userId)) {
3943                    return PackageManager.PERMISSION_GRANTED;
3944                }
3945                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3946                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3947                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3948                    return PackageManager.PERMISSION_GRANTED;
3949                }
3950            }
3951        }
3952
3953        return PackageManager.PERMISSION_DENIED;
3954    }
3955
3956    @Override
3957    public int checkUidPermission(String permName, int uid) {
3958        final int userId = UserHandle.getUserId(uid);
3959
3960        if (!sUserManager.exists(userId)) {
3961            return PackageManager.PERMISSION_DENIED;
3962        }
3963
3964        synchronized (mPackages) {
3965            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3966            if (obj != null) {
3967                final SettingBase ps = (SettingBase) obj;
3968                final PermissionsState permissionsState = ps.getPermissionsState();
3969                if (permissionsState.hasPermission(permName, userId)) {
3970                    return PackageManager.PERMISSION_GRANTED;
3971                }
3972                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3973                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3974                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3975                    return PackageManager.PERMISSION_GRANTED;
3976                }
3977            } else {
3978                ArraySet<String> perms = mSystemPermissions.get(uid);
3979                if (perms != null) {
3980                    if (perms.contains(permName)) {
3981                        return PackageManager.PERMISSION_GRANTED;
3982                    }
3983                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3984                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3985                        return PackageManager.PERMISSION_GRANTED;
3986                    }
3987                }
3988            }
3989        }
3990
3991        return PackageManager.PERMISSION_DENIED;
3992    }
3993
3994    @Override
3995    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3996        if (UserHandle.getCallingUserId() != userId) {
3997            mContext.enforceCallingPermission(
3998                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3999                    "isPermissionRevokedByPolicy for user " + userId);
4000        }
4001
4002        if (checkPermission(permission, packageName, userId)
4003                == PackageManager.PERMISSION_GRANTED) {
4004            return false;
4005        }
4006
4007        final long identity = Binder.clearCallingIdentity();
4008        try {
4009            final int flags = getPermissionFlags(permission, packageName, userId);
4010            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4011        } finally {
4012            Binder.restoreCallingIdentity(identity);
4013        }
4014    }
4015
4016    @Override
4017    public String getPermissionControllerPackageName() {
4018        synchronized (mPackages) {
4019            return mRequiredInstallerPackage;
4020        }
4021    }
4022
4023    /**
4024     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4025     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4026     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4027     * @param message the message to log on security exception
4028     */
4029    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4030            boolean checkShell, String message) {
4031        if (userId < 0) {
4032            throw new IllegalArgumentException("Invalid userId " + userId);
4033        }
4034        if (checkShell) {
4035            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4036        }
4037        if (userId == UserHandle.getUserId(callingUid)) return;
4038        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4039            if (requireFullPermission) {
4040                mContext.enforceCallingOrSelfPermission(
4041                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4042            } else {
4043                try {
4044                    mContext.enforceCallingOrSelfPermission(
4045                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4046                } catch (SecurityException se) {
4047                    mContext.enforceCallingOrSelfPermission(
4048                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4049                }
4050            }
4051        }
4052    }
4053
4054    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4055        if (callingUid == Process.SHELL_UID) {
4056            if (userHandle >= 0
4057                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4058                throw new SecurityException("Shell does not have permission to access user "
4059                        + userHandle);
4060            } else if (userHandle < 0) {
4061                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4062                        + Debug.getCallers(3));
4063            }
4064        }
4065    }
4066
4067    private BasePermission findPermissionTreeLP(String permName) {
4068        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4069            if (permName.startsWith(bp.name) &&
4070                    permName.length() > bp.name.length() &&
4071                    permName.charAt(bp.name.length()) == '.') {
4072                return bp;
4073            }
4074        }
4075        return null;
4076    }
4077
4078    private BasePermission checkPermissionTreeLP(String permName) {
4079        if (permName != null) {
4080            BasePermission bp = findPermissionTreeLP(permName);
4081            if (bp != null) {
4082                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4083                    return bp;
4084                }
4085                throw new SecurityException("Calling uid "
4086                        + Binder.getCallingUid()
4087                        + " is not allowed to add to permission tree "
4088                        + bp.name + " owned by uid " + bp.uid);
4089            }
4090        }
4091        throw new SecurityException("No permission tree found for " + permName);
4092    }
4093
4094    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4095        if (s1 == null) {
4096            return s2 == null;
4097        }
4098        if (s2 == null) {
4099            return false;
4100        }
4101        if (s1.getClass() != s2.getClass()) {
4102            return false;
4103        }
4104        return s1.equals(s2);
4105    }
4106
4107    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4108        if (pi1.icon != pi2.icon) return false;
4109        if (pi1.logo != pi2.logo) return false;
4110        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4111        if (!compareStrings(pi1.name, pi2.name)) return false;
4112        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4113        // We'll take care of setting this one.
4114        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4115        // These are not currently stored in settings.
4116        //if (!compareStrings(pi1.group, pi2.group)) return false;
4117        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4118        //if (pi1.labelRes != pi2.labelRes) return false;
4119        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4120        return true;
4121    }
4122
4123    int permissionInfoFootprint(PermissionInfo info) {
4124        int size = info.name.length();
4125        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4126        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4127        return size;
4128    }
4129
4130    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4131        int size = 0;
4132        for (BasePermission perm : mSettings.mPermissions.values()) {
4133            if (perm.uid == tree.uid) {
4134                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4135            }
4136        }
4137        return size;
4138    }
4139
4140    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4141        // We calculate the max size of permissions defined by this uid and throw
4142        // if that plus the size of 'info' would exceed our stated maximum.
4143        if (tree.uid != Process.SYSTEM_UID) {
4144            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4145            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4146                throw new SecurityException("Permission tree size cap exceeded");
4147            }
4148        }
4149    }
4150
4151    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4152        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4153            throw new SecurityException("Label must be specified in permission");
4154        }
4155        BasePermission tree = checkPermissionTreeLP(info.name);
4156        BasePermission bp = mSettings.mPermissions.get(info.name);
4157        boolean added = bp == null;
4158        boolean changed = true;
4159        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4160        if (added) {
4161            enforcePermissionCapLocked(info, tree);
4162            bp = new BasePermission(info.name, tree.sourcePackage,
4163                    BasePermission.TYPE_DYNAMIC);
4164        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4165            throw new SecurityException(
4166                    "Not allowed to modify non-dynamic permission "
4167                    + info.name);
4168        } else {
4169            if (bp.protectionLevel == fixedLevel
4170                    && bp.perm.owner.equals(tree.perm.owner)
4171                    && bp.uid == tree.uid
4172                    && comparePermissionInfos(bp.perm.info, info)) {
4173                changed = false;
4174            }
4175        }
4176        bp.protectionLevel = fixedLevel;
4177        info = new PermissionInfo(info);
4178        info.protectionLevel = fixedLevel;
4179        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4180        bp.perm.info.packageName = tree.perm.info.packageName;
4181        bp.uid = tree.uid;
4182        if (added) {
4183            mSettings.mPermissions.put(info.name, bp);
4184        }
4185        if (changed) {
4186            if (!async) {
4187                mSettings.writeLPr();
4188            } else {
4189                scheduleWriteSettingsLocked();
4190            }
4191        }
4192        return added;
4193    }
4194
4195    @Override
4196    public boolean addPermission(PermissionInfo info) {
4197        synchronized (mPackages) {
4198            return addPermissionLocked(info, false);
4199        }
4200    }
4201
4202    @Override
4203    public boolean addPermissionAsync(PermissionInfo info) {
4204        synchronized (mPackages) {
4205            return addPermissionLocked(info, true);
4206        }
4207    }
4208
4209    @Override
4210    public void removePermission(String name) {
4211        synchronized (mPackages) {
4212            checkPermissionTreeLP(name);
4213            BasePermission bp = mSettings.mPermissions.get(name);
4214            if (bp != null) {
4215                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4216                    throw new SecurityException(
4217                            "Not allowed to modify non-dynamic permission "
4218                            + name);
4219                }
4220                mSettings.mPermissions.remove(name);
4221                mSettings.writeLPr();
4222            }
4223        }
4224    }
4225
4226    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4227            BasePermission bp) {
4228        int index = pkg.requestedPermissions.indexOf(bp.name);
4229        if (index == -1) {
4230            throw new SecurityException("Package " + pkg.packageName
4231                    + " has not requested permission " + bp.name);
4232        }
4233        if (!bp.isRuntime() && !bp.isDevelopment()) {
4234            throw new SecurityException("Permission " + bp.name
4235                    + " is not a changeable permission type");
4236        }
4237    }
4238
4239    @Override
4240    public void grantRuntimePermission(String packageName, String name, final int userId) {
4241        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4242    }
4243
4244    private void grantRuntimePermission(String packageName, String name, final int userId,
4245            boolean overridePolicy) {
4246        if (!sUserManager.exists(userId)) {
4247            Log.e(TAG, "No such user:" + userId);
4248            return;
4249        }
4250
4251        mContext.enforceCallingOrSelfPermission(
4252                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4253                "grantRuntimePermission");
4254
4255        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4256                true /* requireFullPermission */, true /* checkShell */,
4257                "grantRuntimePermission");
4258
4259        final int uid;
4260        final SettingBase sb;
4261
4262        synchronized (mPackages) {
4263            final PackageParser.Package pkg = mPackages.get(packageName);
4264            if (pkg == null) {
4265                throw new IllegalArgumentException("Unknown package: " + packageName);
4266            }
4267
4268            final BasePermission bp = mSettings.mPermissions.get(name);
4269            if (bp == null) {
4270                throw new IllegalArgumentException("Unknown permission: " + name);
4271            }
4272
4273            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4274
4275            // If a permission review is required for legacy apps we represent
4276            // their permissions as always granted runtime ones since we need
4277            // to keep the review required permission flag per user while an
4278            // install permission's state is shared across all users.
4279            if (mPermissionReviewRequired
4280                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4281                    && bp.isRuntime()) {
4282                return;
4283            }
4284
4285            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4286            sb = (SettingBase) pkg.mExtras;
4287            if (sb == null) {
4288                throw new IllegalArgumentException("Unknown package: " + packageName);
4289            }
4290
4291            final PermissionsState permissionsState = sb.getPermissionsState();
4292
4293            final int flags = permissionsState.getPermissionFlags(name, userId);
4294            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4295                throw new SecurityException("Cannot grant system fixed permission "
4296                        + name + " for package " + packageName);
4297            }
4298            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4299                throw new SecurityException("Cannot grant policy fixed permission "
4300                        + name + " for package " + packageName);
4301            }
4302
4303            if (bp.isDevelopment()) {
4304                // Development permissions must be handled specially, since they are not
4305                // normal runtime permissions.  For now they apply to all users.
4306                if (permissionsState.grantInstallPermission(bp) !=
4307                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4308                    scheduleWriteSettingsLocked();
4309                }
4310                return;
4311            }
4312
4313            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4314                throw new SecurityException("Cannot grant non-ephemeral permission"
4315                        + name + " for package " + packageName);
4316            }
4317
4318            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4319                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4320                return;
4321            }
4322
4323            final int result = permissionsState.grantRuntimePermission(bp, userId);
4324            switch (result) {
4325                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4326                    return;
4327                }
4328
4329                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4330                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4331                    mHandler.post(new Runnable() {
4332                        @Override
4333                        public void run() {
4334                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4335                        }
4336                    });
4337                }
4338                break;
4339            }
4340
4341            if (bp.isRuntime()) {
4342                logPermissionGranted(mContext, name, packageName);
4343            }
4344
4345            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4346
4347            // Not critical if that is lost - app has to request again.
4348            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4349        }
4350
4351        // Only need to do this if user is initialized. Otherwise it's a new user
4352        // and there are no processes running as the user yet and there's no need
4353        // to make an expensive call to remount processes for the changed permissions.
4354        if (READ_EXTERNAL_STORAGE.equals(name)
4355                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4356            final long token = Binder.clearCallingIdentity();
4357            try {
4358                if (sUserManager.isInitialized(userId)) {
4359                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4360                            StorageManagerInternal.class);
4361                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4362                }
4363            } finally {
4364                Binder.restoreCallingIdentity(token);
4365            }
4366        }
4367    }
4368
4369    @Override
4370    public void revokeRuntimePermission(String packageName, String name, int userId) {
4371        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4372    }
4373
4374    private void revokeRuntimePermission(String packageName, String name, int userId,
4375            boolean overridePolicy) {
4376        if (!sUserManager.exists(userId)) {
4377            Log.e(TAG, "No such user:" + userId);
4378            return;
4379        }
4380
4381        mContext.enforceCallingOrSelfPermission(
4382                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4383                "revokeRuntimePermission");
4384
4385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4386                true /* requireFullPermission */, true /* checkShell */,
4387                "revokeRuntimePermission");
4388
4389        final int appId;
4390
4391        synchronized (mPackages) {
4392            final PackageParser.Package pkg = mPackages.get(packageName);
4393            if (pkg == null) {
4394                throw new IllegalArgumentException("Unknown package: " + packageName);
4395            }
4396
4397            final BasePermission bp = mSettings.mPermissions.get(name);
4398            if (bp == null) {
4399                throw new IllegalArgumentException("Unknown permission: " + name);
4400            }
4401
4402            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4403
4404            // If a permission review is required for legacy apps we represent
4405            // their permissions as always granted runtime ones since we need
4406            // to keep the review required permission flag per user while an
4407            // install permission's state is shared across all users.
4408            if (mPermissionReviewRequired
4409                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4410                    && bp.isRuntime()) {
4411                return;
4412            }
4413
4414            SettingBase sb = (SettingBase) pkg.mExtras;
4415            if (sb == null) {
4416                throw new IllegalArgumentException("Unknown package: " + packageName);
4417            }
4418
4419            final PermissionsState permissionsState = sb.getPermissionsState();
4420
4421            final int flags = permissionsState.getPermissionFlags(name, userId);
4422            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4423                throw new SecurityException("Cannot revoke system fixed permission "
4424                        + name + " for package " + packageName);
4425            }
4426            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4427                throw new SecurityException("Cannot revoke policy fixed permission "
4428                        + name + " for package " + packageName);
4429            }
4430
4431            if (bp.isDevelopment()) {
4432                // Development permissions must be handled specially, since they are not
4433                // normal runtime permissions.  For now they apply to all users.
4434                if (permissionsState.revokeInstallPermission(bp) !=
4435                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4436                    scheduleWriteSettingsLocked();
4437                }
4438                return;
4439            }
4440
4441            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4442                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4443                return;
4444            }
4445
4446            if (bp.isRuntime()) {
4447                logPermissionRevoked(mContext, name, packageName);
4448            }
4449
4450            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4451
4452            // Critical, after this call app should never have the permission.
4453            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4454
4455            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4456        }
4457
4458        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4459    }
4460
4461    /**
4462     * Get the first event id for the permission.
4463     *
4464     * <p>There are four events for each permission: <ul>
4465     *     <li>Request permission: first id + 0</li>
4466     *     <li>Grant permission: first id + 1</li>
4467     *     <li>Request for permission denied: first id + 2</li>
4468     *     <li>Revoke permission: first id + 3</li>
4469     * </ul></p>
4470     *
4471     * @param name name of the permission
4472     *
4473     * @return The first event id for the permission
4474     */
4475    private static int getBaseEventId(@NonNull String name) {
4476        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4477
4478        if (eventIdIndex == -1) {
4479            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4480                    || "user".equals(Build.TYPE)) {
4481                Log.i(TAG, "Unknown permission " + name);
4482
4483                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4484            } else {
4485                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4486                //
4487                // Also update
4488                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4489                // - metrics_constants.proto
4490                throw new IllegalStateException("Unknown permission " + name);
4491            }
4492        }
4493
4494        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4495    }
4496
4497    /**
4498     * Log that a permission was revoked.
4499     *
4500     * @param context Context of the caller
4501     * @param name name of the permission
4502     * @param packageName package permission if for
4503     */
4504    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4505            @NonNull String packageName) {
4506        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4507    }
4508
4509    /**
4510     * Log that a permission request was granted.
4511     *
4512     * @param context Context of the caller
4513     * @param name name of the permission
4514     * @param packageName package permission if for
4515     */
4516    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4517            @NonNull String packageName) {
4518        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4519    }
4520
4521    @Override
4522    public void resetRuntimePermissions() {
4523        mContext.enforceCallingOrSelfPermission(
4524                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4525                "revokeRuntimePermission");
4526
4527        int callingUid = Binder.getCallingUid();
4528        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4529            mContext.enforceCallingOrSelfPermission(
4530                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4531                    "resetRuntimePermissions");
4532        }
4533
4534        synchronized (mPackages) {
4535            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4536            for (int userId : UserManagerService.getInstance().getUserIds()) {
4537                final int packageCount = mPackages.size();
4538                for (int i = 0; i < packageCount; i++) {
4539                    PackageParser.Package pkg = mPackages.valueAt(i);
4540                    if (!(pkg.mExtras instanceof PackageSetting)) {
4541                        continue;
4542                    }
4543                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4544                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4545                }
4546            }
4547        }
4548    }
4549
4550    @Override
4551    public int getPermissionFlags(String name, String packageName, int userId) {
4552        if (!sUserManager.exists(userId)) {
4553            return 0;
4554        }
4555
4556        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4557
4558        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4559                true /* requireFullPermission */, false /* checkShell */,
4560                "getPermissionFlags");
4561
4562        synchronized (mPackages) {
4563            final PackageParser.Package pkg = mPackages.get(packageName);
4564            if (pkg == null) {
4565                return 0;
4566            }
4567
4568            final BasePermission bp = mSettings.mPermissions.get(name);
4569            if (bp == null) {
4570                return 0;
4571            }
4572
4573            SettingBase sb = (SettingBase) pkg.mExtras;
4574            if (sb == null) {
4575                return 0;
4576            }
4577
4578            PermissionsState permissionsState = sb.getPermissionsState();
4579            return permissionsState.getPermissionFlags(name, userId);
4580        }
4581    }
4582
4583    @Override
4584    public void updatePermissionFlags(String name, String packageName, int flagMask,
4585            int flagValues, int userId) {
4586        if (!sUserManager.exists(userId)) {
4587            return;
4588        }
4589
4590        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4591
4592        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4593                true /* requireFullPermission */, true /* checkShell */,
4594                "updatePermissionFlags");
4595
4596        // Only the system can change these flags and nothing else.
4597        if (getCallingUid() != Process.SYSTEM_UID) {
4598            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4599            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4600            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4601            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4602            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4603        }
4604
4605        synchronized (mPackages) {
4606            final PackageParser.Package pkg = mPackages.get(packageName);
4607            if (pkg == null) {
4608                throw new IllegalArgumentException("Unknown package: " + packageName);
4609            }
4610
4611            final BasePermission bp = mSettings.mPermissions.get(name);
4612            if (bp == null) {
4613                throw new IllegalArgumentException("Unknown permission: " + name);
4614            }
4615
4616            SettingBase sb = (SettingBase) pkg.mExtras;
4617            if (sb == null) {
4618                throw new IllegalArgumentException("Unknown package: " + packageName);
4619            }
4620
4621            PermissionsState permissionsState = sb.getPermissionsState();
4622
4623            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4624
4625            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4626                // Install and runtime permissions are stored in different places,
4627                // so figure out what permission changed and persist the change.
4628                if (permissionsState.getInstallPermissionState(name) != null) {
4629                    scheduleWriteSettingsLocked();
4630                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4631                        || hadState) {
4632                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4633                }
4634            }
4635        }
4636    }
4637
4638    /**
4639     * Update the permission flags for all packages and runtime permissions of a user in order
4640     * to allow device or profile owner to remove POLICY_FIXED.
4641     */
4642    @Override
4643    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4644        if (!sUserManager.exists(userId)) {
4645            return;
4646        }
4647
4648        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4649
4650        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4651                true /* requireFullPermission */, true /* checkShell */,
4652                "updatePermissionFlagsForAllApps");
4653
4654        // Only the system can change system fixed flags.
4655        if (getCallingUid() != Process.SYSTEM_UID) {
4656            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4657            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4658        }
4659
4660        synchronized (mPackages) {
4661            boolean changed = false;
4662            final int packageCount = mPackages.size();
4663            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4664                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4665                SettingBase sb = (SettingBase) pkg.mExtras;
4666                if (sb == null) {
4667                    continue;
4668                }
4669                PermissionsState permissionsState = sb.getPermissionsState();
4670                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4671                        userId, flagMask, flagValues);
4672            }
4673            if (changed) {
4674                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4675            }
4676        }
4677    }
4678
4679    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4680        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4681                != PackageManager.PERMISSION_GRANTED
4682            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4683                != PackageManager.PERMISSION_GRANTED) {
4684            throw new SecurityException(message + " requires "
4685                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4686                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4687        }
4688    }
4689
4690    @Override
4691    public boolean shouldShowRequestPermissionRationale(String permissionName,
4692            String packageName, int userId) {
4693        if (UserHandle.getCallingUserId() != userId) {
4694            mContext.enforceCallingPermission(
4695                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4696                    "canShowRequestPermissionRationale for user " + userId);
4697        }
4698
4699        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4700        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4701            return false;
4702        }
4703
4704        if (checkPermission(permissionName, packageName, userId)
4705                == PackageManager.PERMISSION_GRANTED) {
4706            return false;
4707        }
4708
4709        final int flags;
4710
4711        final long identity = Binder.clearCallingIdentity();
4712        try {
4713            flags = getPermissionFlags(permissionName,
4714                    packageName, userId);
4715        } finally {
4716            Binder.restoreCallingIdentity(identity);
4717        }
4718
4719        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4720                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4721                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4722
4723        if ((flags & fixedFlags) != 0) {
4724            return false;
4725        }
4726
4727        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4728    }
4729
4730    @Override
4731    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4732        mContext.enforceCallingOrSelfPermission(
4733                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4734                "addOnPermissionsChangeListener");
4735
4736        synchronized (mPackages) {
4737            mOnPermissionChangeListeners.addListenerLocked(listener);
4738        }
4739    }
4740
4741    @Override
4742    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4743        synchronized (mPackages) {
4744            mOnPermissionChangeListeners.removeListenerLocked(listener);
4745        }
4746    }
4747
4748    @Override
4749    public boolean isProtectedBroadcast(String actionName) {
4750        synchronized (mPackages) {
4751            if (mProtectedBroadcasts.contains(actionName)) {
4752                return true;
4753            } else if (actionName != null) {
4754                // TODO: remove these terrible hacks
4755                if (actionName.startsWith("android.net.netmon.lingerExpired")
4756                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4757                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4758                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4759                    return true;
4760                }
4761            }
4762        }
4763        return false;
4764    }
4765
4766    @Override
4767    public int checkSignatures(String pkg1, String pkg2) {
4768        synchronized (mPackages) {
4769            final PackageParser.Package p1 = mPackages.get(pkg1);
4770            final PackageParser.Package p2 = mPackages.get(pkg2);
4771            if (p1 == null || p1.mExtras == null
4772                    || p2 == null || p2.mExtras == null) {
4773                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4774            }
4775            return compareSignatures(p1.mSignatures, p2.mSignatures);
4776        }
4777    }
4778
4779    @Override
4780    public int checkUidSignatures(int uid1, int uid2) {
4781        // Map to base uids.
4782        uid1 = UserHandle.getAppId(uid1);
4783        uid2 = UserHandle.getAppId(uid2);
4784        // reader
4785        synchronized (mPackages) {
4786            Signature[] s1;
4787            Signature[] s2;
4788            Object obj = mSettings.getUserIdLPr(uid1);
4789            if (obj != null) {
4790                if (obj instanceof SharedUserSetting) {
4791                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4792                } else if (obj instanceof PackageSetting) {
4793                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4794                } else {
4795                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4796                }
4797            } else {
4798                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4799            }
4800            obj = mSettings.getUserIdLPr(uid2);
4801            if (obj != null) {
4802                if (obj instanceof SharedUserSetting) {
4803                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4804                } else if (obj instanceof PackageSetting) {
4805                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4806                } else {
4807                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4808                }
4809            } else {
4810                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4811            }
4812            return compareSignatures(s1, s2);
4813        }
4814    }
4815
4816    /**
4817     * This method should typically only be used when granting or revoking
4818     * permissions, since the app may immediately restart after this call.
4819     * <p>
4820     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4821     * guard your work against the app being relaunched.
4822     */
4823    private void killUid(int appId, int userId, String reason) {
4824        final long identity = Binder.clearCallingIdentity();
4825        try {
4826            IActivityManager am = ActivityManager.getService();
4827            if (am != null) {
4828                try {
4829                    am.killUid(appId, userId, reason);
4830                } catch (RemoteException e) {
4831                    /* ignore - same process */
4832                }
4833            }
4834        } finally {
4835            Binder.restoreCallingIdentity(identity);
4836        }
4837    }
4838
4839    /**
4840     * Compares two sets of signatures. Returns:
4841     * <br />
4842     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4843     * <br />
4844     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4845     * <br />
4846     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4847     * <br />
4848     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4849     * <br />
4850     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4851     */
4852    static int compareSignatures(Signature[] s1, Signature[] s2) {
4853        if (s1 == null) {
4854            return s2 == null
4855                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4856                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4857        }
4858
4859        if (s2 == null) {
4860            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4861        }
4862
4863        if (s1.length != s2.length) {
4864            return PackageManager.SIGNATURE_NO_MATCH;
4865        }
4866
4867        // Since both signature sets are of size 1, we can compare without HashSets.
4868        if (s1.length == 1) {
4869            return s1[0].equals(s2[0]) ?
4870                    PackageManager.SIGNATURE_MATCH :
4871                    PackageManager.SIGNATURE_NO_MATCH;
4872        }
4873
4874        ArraySet<Signature> set1 = new ArraySet<Signature>();
4875        for (Signature sig : s1) {
4876            set1.add(sig);
4877        }
4878        ArraySet<Signature> set2 = new ArraySet<Signature>();
4879        for (Signature sig : s2) {
4880            set2.add(sig);
4881        }
4882        // Make sure s2 contains all signatures in s1.
4883        if (set1.equals(set2)) {
4884            return PackageManager.SIGNATURE_MATCH;
4885        }
4886        return PackageManager.SIGNATURE_NO_MATCH;
4887    }
4888
4889    /**
4890     * If the database version for this type of package (internal storage or
4891     * external storage) is less than the version where package signatures
4892     * were updated, return true.
4893     */
4894    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4895        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4896        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4897    }
4898
4899    /**
4900     * Used for backward compatibility to make sure any packages with
4901     * certificate chains get upgraded to the new style. {@code existingSigs}
4902     * will be in the old format (since they were stored on disk from before the
4903     * system upgrade) and {@code scannedSigs} will be in the newer format.
4904     */
4905    private int compareSignaturesCompat(PackageSignatures existingSigs,
4906            PackageParser.Package scannedPkg) {
4907        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4908            return PackageManager.SIGNATURE_NO_MATCH;
4909        }
4910
4911        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4912        for (Signature sig : existingSigs.mSignatures) {
4913            existingSet.add(sig);
4914        }
4915        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4916        for (Signature sig : scannedPkg.mSignatures) {
4917            try {
4918                Signature[] chainSignatures = sig.getChainSignatures();
4919                for (Signature chainSig : chainSignatures) {
4920                    scannedCompatSet.add(chainSig);
4921                }
4922            } catch (CertificateEncodingException e) {
4923                scannedCompatSet.add(sig);
4924            }
4925        }
4926        /*
4927         * Make sure the expanded scanned set contains all signatures in the
4928         * existing one.
4929         */
4930        if (scannedCompatSet.equals(existingSet)) {
4931            // Migrate the old signatures to the new scheme.
4932            existingSigs.assignSignatures(scannedPkg.mSignatures);
4933            // The new KeySets will be re-added later in the scanning process.
4934            synchronized (mPackages) {
4935                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4936            }
4937            return PackageManager.SIGNATURE_MATCH;
4938        }
4939        return PackageManager.SIGNATURE_NO_MATCH;
4940    }
4941
4942    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4943        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4944        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4945    }
4946
4947    private int compareSignaturesRecover(PackageSignatures existingSigs,
4948            PackageParser.Package scannedPkg) {
4949        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4950            return PackageManager.SIGNATURE_NO_MATCH;
4951        }
4952
4953        String msg = null;
4954        try {
4955            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4956                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4957                        + scannedPkg.packageName);
4958                return PackageManager.SIGNATURE_MATCH;
4959            }
4960        } catch (CertificateException e) {
4961            msg = e.getMessage();
4962        }
4963
4964        logCriticalInfo(Log.INFO,
4965                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4966        return PackageManager.SIGNATURE_NO_MATCH;
4967    }
4968
4969    @Override
4970    public List<String> getAllPackages() {
4971        synchronized (mPackages) {
4972            return new ArrayList<String>(mPackages.keySet());
4973        }
4974    }
4975
4976    @Override
4977    public String[] getPackagesForUid(int uid) {
4978        final int userId = UserHandle.getUserId(uid);
4979        uid = UserHandle.getAppId(uid);
4980        // reader
4981        synchronized (mPackages) {
4982            Object obj = mSettings.getUserIdLPr(uid);
4983            if (obj instanceof SharedUserSetting) {
4984                final SharedUserSetting sus = (SharedUserSetting) obj;
4985                final int N = sus.packages.size();
4986                String[] res = new String[N];
4987                final Iterator<PackageSetting> it = sus.packages.iterator();
4988                int i = 0;
4989                while (it.hasNext()) {
4990                    PackageSetting ps = it.next();
4991                    if (ps.getInstalled(userId)) {
4992                        res[i++] = ps.name;
4993                    } else {
4994                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4995                    }
4996                }
4997                return res;
4998            } else if (obj instanceof PackageSetting) {
4999                final PackageSetting ps = (PackageSetting) obj;
5000                return new String[] { ps.name };
5001            }
5002        }
5003        return null;
5004    }
5005
5006    @Override
5007    public String getNameForUid(int uid) {
5008        // reader
5009        synchronized (mPackages) {
5010            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5011            if (obj instanceof SharedUserSetting) {
5012                final SharedUserSetting sus = (SharedUserSetting) obj;
5013                return sus.name + ":" + sus.userId;
5014            } else if (obj instanceof PackageSetting) {
5015                final PackageSetting ps = (PackageSetting) obj;
5016                return ps.name;
5017            }
5018        }
5019        return null;
5020    }
5021
5022    @Override
5023    public int getUidForSharedUser(String sharedUserName) {
5024        if(sharedUserName == null) {
5025            return -1;
5026        }
5027        // reader
5028        synchronized (mPackages) {
5029            SharedUserSetting suid;
5030            try {
5031                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5032                if (suid != null) {
5033                    return suid.userId;
5034                }
5035            } catch (PackageManagerException ignore) {
5036                // can't happen, but, still need to catch it
5037            }
5038            return -1;
5039        }
5040    }
5041
5042    @Override
5043    public int getFlagsForUid(int uid) {
5044        synchronized (mPackages) {
5045            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5046            if (obj instanceof SharedUserSetting) {
5047                final SharedUserSetting sus = (SharedUserSetting) obj;
5048                return sus.pkgFlags;
5049            } else if (obj instanceof PackageSetting) {
5050                final PackageSetting ps = (PackageSetting) obj;
5051                return ps.pkgFlags;
5052            }
5053        }
5054        return 0;
5055    }
5056
5057    @Override
5058    public int getPrivateFlagsForUid(int uid) {
5059        synchronized (mPackages) {
5060            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5061            if (obj instanceof SharedUserSetting) {
5062                final SharedUserSetting sus = (SharedUserSetting) obj;
5063                return sus.pkgPrivateFlags;
5064            } else if (obj instanceof PackageSetting) {
5065                final PackageSetting ps = (PackageSetting) obj;
5066                return ps.pkgPrivateFlags;
5067            }
5068        }
5069        return 0;
5070    }
5071
5072    @Override
5073    public boolean isUidPrivileged(int uid) {
5074        uid = UserHandle.getAppId(uid);
5075        // reader
5076        synchronized (mPackages) {
5077            Object obj = mSettings.getUserIdLPr(uid);
5078            if (obj instanceof SharedUserSetting) {
5079                final SharedUserSetting sus = (SharedUserSetting) obj;
5080                final Iterator<PackageSetting> it = sus.packages.iterator();
5081                while (it.hasNext()) {
5082                    if (it.next().isPrivileged()) {
5083                        return true;
5084                    }
5085                }
5086            } else if (obj instanceof PackageSetting) {
5087                final PackageSetting ps = (PackageSetting) obj;
5088                return ps.isPrivileged();
5089            }
5090        }
5091        return false;
5092    }
5093
5094    @Override
5095    public String[] getAppOpPermissionPackages(String permissionName) {
5096        synchronized (mPackages) {
5097            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5098            if (pkgs == null) {
5099                return null;
5100            }
5101            return pkgs.toArray(new String[pkgs.size()]);
5102        }
5103    }
5104
5105    @Override
5106    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5107            int flags, int userId) {
5108        try {
5109            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5110
5111            if (!sUserManager.exists(userId)) return null;
5112            flags = updateFlagsForResolve(flags, userId, intent);
5113            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5114                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5115
5116            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5117            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5118                    flags, userId);
5119            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5120
5121            final ResolveInfo bestChoice =
5122                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5123            return bestChoice;
5124        } finally {
5125            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5126        }
5127    }
5128
5129    @Override
5130    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5131            IntentFilter filter, int match, ComponentName activity) {
5132        final int userId = UserHandle.getCallingUserId();
5133        if (DEBUG_PREFERRED) {
5134            Log.v(TAG, "setLastChosenActivity intent=" + intent
5135                + " resolvedType=" + resolvedType
5136                + " flags=" + flags
5137                + " filter=" + filter
5138                + " match=" + match
5139                + " activity=" + activity);
5140            filter.dump(new PrintStreamPrinter(System.out), "    ");
5141        }
5142        intent.setComponent(null);
5143        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5144                userId);
5145        // Find any earlier preferred or last chosen entries and nuke them
5146        findPreferredActivity(intent, resolvedType,
5147                flags, query, 0, false, true, false, userId);
5148        // Add the new activity as the last chosen for this filter
5149        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5150                "Setting last chosen");
5151    }
5152
5153    @Override
5154    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5155        final int userId = UserHandle.getCallingUserId();
5156        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5157        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5158                userId);
5159        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5160                false, false, false, userId);
5161    }
5162
5163    private boolean isEphemeralDisabled() {
5164        // ephemeral apps have been disabled across the board
5165        if (DISABLE_EPHEMERAL_APPS) {
5166            return true;
5167        }
5168        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5169        if (!mSystemReady) {
5170            return true;
5171        }
5172        // we can't get a content resolver until the system is ready; these checks must happen last
5173        final ContentResolver resolver = mContext.getContentResolver();
5174        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5175            return true;
5176        }
5177        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5178    }
5179
5180    private boolean isEphemeralAllowed(
5181            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5182            boolean skipPackageCheck) {
5183        // Short circuit and return early if possible.
5184        if (isEphemeralDisabled()) {
5185            return false;
5186        }
5187        final int callingUser = UserHandle.getCallingUserId();
5188        if (callingUser != UserHandle.USER_SYSTEM) {
5189            return false;
5190        }
5191        if (mEphemeralResolverConnection == null) {
5192            return false;
5193        }
5194        if (mEphemeralInstallerComponent == null) {
5195            return false;
5196        }
5197        if (intent.getComponent() != null) {
5198            return false;
5199        }
5200        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5201            return false;
5202        }
5203        if (!skipPackageCheck && intent.getPackage() != null) {
5204            return false;
5205        }
5206        final boolean isWebUri = hasWebURI(intent);
5207        if (!isWebUri || intent.getData().getHost() == null) {
5208            return false;
5209        }
5210        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5211        synchronized (mPackages) {
5212            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5213            for (int n = 0; n < count; n++) {
5214                ResolveInfo info = resolvedActivities.get(n);
5215                String packageName = info.activityInfo.packageName;
5216                PackageSetting ps = mSettings.mPackages.get(packageName);
5217                if (ps != null) {
5218                    // Try to get the status from User settings first
5219                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5220                    int status = (int) (packedStatus >> 32);
5221                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5222                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5223                        if (DEBUG_EPHEMERAL) {
5224                            Slog.v(TAG, "DENY ephemeral apps;"
5225                                + " pkg: " + packageName + ", status: " + status);
5226                        }
5227                        return false;
5228                    }
5229                }
5230            }
5231        }
5232        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5233        return true;
5234    }
5235
5236    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5237            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5238            int userId) {
5239        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5240                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5241                        callingPackage, userId));
5242        mHandler.sendMessage(msg);
5243    }
5244
5245    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5246            int flags, List<ResolveInfo> query, int userId) {
5247        if (query != null) {
5248            final int N = query.size();
5249            if (N == 1) {
5250                return query.get(0);
5251            } else if (N > 1) {
5252                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5253                // If there is more than one activity with the same priority,
5254                // then let the user decide between them.
5255                ResolveInfo r0 = query.get(0);
5256                ResolveInfo r1 = query.get(1);
5257                if (DEBUG_INTENT_MATCHING || debug) {
5258                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5259                            + r1.activityInfo.name + "=" + r1.priority);
5260                }
5261                // If the first activity has a higher priority, or a different
5262                // default, then it is always desirable to pick it.
5263                if (r0.priority != r1.priority
5264                        || r0.preferredOrder != r1.preferredOrder
5265                        || r0.isDefault != r1.isDefault) {
5266                    return query.get(0);
5267                }
5268                // If we have saved a preference for a preferred activity for
5269                // this Intent, use that.
5270                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5271                        flags, query, r0.priority, true, false, debug, userId);
5272                if (ri != null) {
5273                    return ri;
5274                }
5275                ri = new ResolveInfo(mResolveInfo);
5276                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5277                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5278                // If all of the options come from the same package, show the application's
5279                // label and icon instead of the generic resolver's.
5280                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5281                // and then throw away the ResolveInfo itself, meaning that the caller loses
5282                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5283                // a fallback for this case; we only set the target package's resources on
5284                // the ResolveInfo, not the ActivityInfo.
5285                final String intentPackage = intent.getPackage();
5286                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5287                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5288                    ri.resolvePackageName = intentPackage;
5289                    if (userNeedsBadging(userId)) {
5290                        ri.noResourceId = true;
5291                    } else {
5292                        ri.icon = appi.icon;
5293                    }
5294                    ri.iconResourceId = appi.icon;
5295                    ri.labelRes = appi.labelRes;
5296                }
5297                ri.activityInfo.applicationInfo = new ApplicationInfo(
5298                        ri.activityInfo.applicationInfo);
5299                if (userId != 0) {
5300                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5301                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5302                }
5303                // Make sure that the resolver is displayable in car mode
5304                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5305                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5306                return ri;
5307            }
5308        }
5309        return null;
5310    }
5311
5312    /**
5313     * Return true if the given list is not empty and all of its contents have
5314     * an activityInfo with the given package name.
5315     */
5316    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5317        if (ArrayUtils.isEmpty(list)) {
5318            return false;
5319        }
5320        for (int i = 0, N = list.size(); i < N; i++) {
5321            final ResolveInfo ri = list.get(i);
5322            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5323            if (ai == null || !packageName.equals(ai.packageName)) {
5324                return false;
5325            }
5326        }
5327        return true;
5328    }
5329
5330    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5331            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5332        final int N = query.size();
5333        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5334                .get(userId);
5335        // Get the list of persistent preferred activities that handle the intent
5336        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5337        List<PersistentPreferredActivity> pprefs = ppir != null
5338                ? ppir.queryIntent(intent, resolvedType,
5339                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5340                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5341                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5342                : null;
5343        if (pprefs != null && pprefs.size() > 0) {
5344            final int M = pprefs.size();
5345            for (int i=0; i<M; i++) {
5346                final PersistentPreferredActivity ppa = pprefs.get(i);
5347                if (DEBUG_PREFERRED || debug) {
5348                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5349                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5350                            + "\n  component=" + ppa.mComponent);
5351                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5352                }
5353                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5354                        flags | MATCH_DISABLED_COMPONENTS, userId);
5355                if (DEBUG_PREFERRED || debug) {
5356                    Slog.v(TAG, "Found persistent preferred activity:");
5357                    if (ai != null) {
5358                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5359                    } else {
5360                        Slog.v(TAG, "  null");
5361                    }
5362                }
5363                if (ai == null) {
5364                    // This previously registered persistent preferred activity
5365                    // component is no longer known. Ignore it and do NOT remove it.
5366                    continue;
5367                }
5368                for (int j=0; j<N; j++) {
5369                    final ResolveInfo ri = query.get(j);
5370                    if (!ri.activityInfo.applicationInfo.packageName
5371                            .equals(ai.applicationInfo.packageName)) {
5372                        continue;
5373                    }
5374                    if (!ri.activityInfo.name.equals(ai.name)) {
5375                        continue;
5376                    }
5377                    //  Found a persistent preference that can handle the intent.
5378                    if (DEBUG_PREFERRED || debug) {
5379                        Slog.v(TAG, "Returning persistent preferred activity: " +
5380                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5381                    }
5382                    return ri;
5383                }
5384            }
5385        }
5386        return null;
5387    }
5388
5389    // TODO: handle preferred activities missing while user has amnesia
5390    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5391            List<ResolveInfo> query, int priority, boolean always,
5392            boolean removeMatches, boolean debug, int userId) {
5393        if (!sUserManager.exists(userId)) return null;
5394        flags = updateFlagsForResolve(flags, userId, intent);
5395        // writer
5396        synchronized (mPackages) {
5397            if (intent.getSelector() != null) {
5398                intent = intent.getSelector();
5399            }
5400            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5401
5402            // Try to find a matching persistent preferred activity.
5403            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5404                    debug, userId);
5405
5406            // If a persistent preferred activity matched, use it.
5407            if (pri != null) {
5408                return pri;
5409            }
5410
5411            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5412            // Get the list of preferred activities that handle the intent
5413            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5414            List<PreferredActivity> prefs = pir != null
5415                    ? pir.queryIntent(intent, resolvedType,
5416                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5417                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5418                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5419                    : null;
5420            if (prefs != null && prefs.size() > 0) {
5421                boolean changed = false;
5422                try {
5423                    // First figure out how good the original match set is.
5424                    // We will only allow preferred activities that came
5425                    // from the same match quality.
5426                    int match = 0;
5427
5428                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5429
5430                    final int N = query.size();
5431                    for (int j=0; j<N; j++) {
5432                        final ResolveInfo ri = query.get(j);
5433                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5434                                + ": 0x" + Integer.toHexString(match));
5435                        if (ri.match > match) {
5436                            match = ri.match;
5437                        }
5438                    }
5439
5440                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5441                            + Integer.toHexString(match));
5442
5443                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5444                    final int M = prefs.size();
5445                    for (int i=0; i<M; i++) {
5446                        final PreferredActivity pa = prefs.get(i);
5447                        if (DEBUG_PREFERRED || debug) {
5448                            Slog.v(TAG, "Checking PreferredActivity ds="
5449                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5450                                    + "\n  component=" + pa.mPref.mComponent);
5451                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5452                        }
5453                        if (pa.mPref.mMatch != match) {
5454                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5455                                    + Integer.toHexString(pa.mPref.mMatch));
5456                            continue;
5457                        }
5458                        // If it's not an "always" type preferred activity and that's what we're
5459                        // looking for, skip it.
5460                        if (always && !pa.mPref.mAlways) {
5461                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5462                            continue;
5463                        }
5464                        final ActivityInfo ai = getActivityInfo(
5465                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5466                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5467                                userId);
5468                        if (DEBUG_PREFERRED || debug) {
5469                            Slog.v(TAG, "Found preferred activity:");
5470                            if (ai != null) {
5471                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5472                            } else {
5473                                Slog.v(TAG, "  null");
5474                            }
5475                        }
5476                        if (ai == null) {
5477                            // This previously registered preferred activity
5478                            // component is no longer known.  Most likely an update
5479                            // to the app was installed and in the new version this
5480                            // component no longer exists.  Clean it up by removing
5481                            // it from the preferred activities list, and skip it.
5482                            Slog.w(TAG, "Removing dangling preferred activity: "
5483                                    + pa.mPref.mComponent);
5484                            pir.removeFilter(pa);
5485                            changed = true;
5486                            continue;
5487                        }
5488                        for (int j=0; j<N; j++) {
5489                            final ResolveInfo ri = query.get(j);
5490                            if (!ri.activityInfo.applicationInfo.packageName
5491                                    .equals(ai.applicationInfo.packageName)) {
5492                                continue;
5493                            }
5494                            if (!ri.activityInfo.name.equals(ai.name)) {
5495                                continue;
5496                            }
5497
5498                            if (removeMatches) {
5499                                pir.removeFilter(pa);
5500                                changed = true;
5501                                if (DEBUG_PREFERRED) {
5502                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5503                                }
5504                                break;
5505                            }
5506
5507                            // Okay we found a previously set preferred or last chosen app.
5508                            // If the result set is different from when this
5509                            // was created, we need to clear it and re-ask the
5510                            // user their preference, if we're looking for an "always" type entry.
5511                            if (always && !pa.mPref.sameSet(query)) {
5512                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5513                                        + intent + " type " + resolvedType);
5514                                if (DEBUG_PREFERRED) {
5515                                    Slog.v(TAG, "Removing preferred activity since set changed "
5516                                            + pa.mPref.mComponent);
5517                                }
5518                                pir.removeFilter(pa);
5519                                // Re-add the filter as a "last chosen" entry (!always)
5520                                PreferredActivity lastChosen = new PreferredActivity(
5521                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5522                                pir.addFilter(lastChosen);
5523                                changed = true;
5524                                return null;
5525                            }
5526
5527                            // Yay! Either the set matched or we're looking for the last chosen
5528                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5529                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5530                            return ri;
5531                        }
5532                    }
5533                } finally {
5534                    if (changed) {
5535                        if (DEBUG_PREFERRED) {
5536                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5537                        }
5538                        scheduleWritePackageRestrictionsLocked(userId);
5539                    }
5540                }
5541            }
5542        }
5543        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5544        return null;
5545    }
5546
5547    /*
5548     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5549     */
5550    @Override
5551    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5552            int targetUserId) {
5553        mContext.enforceCallingOrSelfPermission(
5554                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5555        List<CrossProfileIntentFilter> matches =
5556                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5557        if (matches != null) {
5558            int size = matches.size();
5559            for (int i = 0; i < size; i++) {
5560                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5561            }
5562        }
5563        if (hasWebURI(intent)) {
5564            // cross-profile app linking works only towards the parent.
5565            final UserInfo parent = getProfileParent(sourceUserId);
5566            synchronized(mPackages) {
5567                int flags = updateFlagsForResolve(0, parent.id, intent);
5568                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5569                        intent, resolvedType, flags, sourceUserId, parent.id);
5570                return xpDomainInfo != null;
5571            }
5572        }
5573        return false;
5574    }
5575
5576    private UserInfo getProfileParent(int userId) {
5577        final long identity = Binder.clearCallingIdentity();
5578        try {
5579            return sUserManager.getProfileParent(userId);
5580        } finally {
5581            Binder.restoreCallingIdentity(identity);
5582        }
5583    }
5584
5585    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5586            String resolvedType, int userId) {
5587        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5588        if (resolver != null) {
5589            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5590                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5591        }
5592        return null;
5593    }
5594
5595    @Override
5596    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5597            String resolvedType, int flags, int userId) {
5598        try {
5599            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5600
5601            return new ParceledListSlice<>(
5602                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5603        } finally {
5604            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5605        }
5606    }
5607
5608    /**
5609     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5610     * ephemeral, returns {@code null}.
5611     */
5612    private String getEphemeralPackageName(int callingUid) {
5613        final int appId = UserHandle.getAppId(callingUid);
5614        synchronized (mPackages) {
5615            final Object obj = mSettings.getUserIdLPr(appId);
5616            if (obj instanceof PackageSetting) {
5617                final PackageSetting ps = (PackageSetting) obj;
5618                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5619            }
5620        }
5621        return null;
5622    }
5623
5624    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5625            String resolvedType, int flags, int userId) {
5626        if (!sUserManager.exists(userId)) return Collections.emptyList();
5627        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5628        flags = updateFlagsForResolve(flags, userId, intent);
5629        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5630                false /* requireFullPermission */, false /* checkShell */,
5631                "query intent activities");
5632        ComponentName comp = intent.getComponent();
5633        if (comp == null) {
5634            if (intent.getSelector() != null) {
5635                intent = intent.getSelector();
5636                comp = intent.getComponent();
5637            }
5638        }
5639
5640        if (comp != null) {
5641            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5642            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5643            if (ai != null) {
5644                // When specifying an explicit component, we prevent the activity from being
5645                // used when either 1) the calling package is normal and the activity is within
5646                // an ephemeral application or 2) the calling package is ephemeral and the
5647                // activity is not visible to ephemeral applications.
5648                boolean matchEphemeral =
5649                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5650                boolean ephemeralVisibleOnly =
5651                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5652                boolean blockResolution =
5653                        (!matchEphemeral && ephemeralPkgName == null
5654                                && (ai.applicationInfo.privateFlags
5655                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5656                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5657                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5658                if (!blockResolution) {
5659                    final ResolveInfo ri = new ResolveInfo();
5660                    ri.activityInfo = ai;
5661                    list.add(ri);
5662                }
5663            }
5664            return list;
5665        }
5666
5667        // reader
5668        boolean sortResult = false;
5669        boolean addEphemeral = false;
5670        List<ResolveInfo> result;
5671        final String pkgName = intent.getPackage();
5672        synchronized (mPackages) {
5673            if (pkgName == null) {
5674                List<CrossProfileIntentFilter> matchingFilters =
5675                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5676                // Check for results that need to skip the current profile.
5677                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5678                        resolvedType, flags, userId);
5679                if (xpResolveInfo != null) {
5680                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5681                    xpResult.add(xpResolveInfo);
5682                    return filterForEphemeral(
5683                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5684                }
5685
5686                // Check for results in the current profile.
5687                result = filterIfNotSystemUser(mActivities.queryIntent(
5688                        intent, resolvedType, flags, userId), userId);
5689                addEphemeral =
5690                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5691
5692                // Check for cross profile results.
5693                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5694                xpResolveInfo = queryCrossProfileIntents(
5695                        matchingFilters, intent, resolvedType, flags, userId,
5696                        hasNonNegativePriorityResult);
5697                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5698                    boolean isVisibleToUser = filterIfNotSystemUser(
5699                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5700                    if (isVisibleToUser) {
5701                        result.add(xpResolveInfo);
5702                        sortResult = true;
5703                    }
5704                }
5705                if (hasWebURI(intent)) {
5706                    CrossProfileDomainInfo xpDomainInfo = null;
5707                    final UserInfo parent = getProfileParent(userId);
5708                    if (parent != null) {
5709                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5710                                flags, userId, parent.id);
5711                    }
5712                    if (xpDomainInfo != null) {
5713                        if (xpResolveInfo != null) {
5714                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5715                            // in the result.
5716                            result.remove(xpResolveInfo);
5717                        }
5718                        if (result.size() == 0 && !addEphemeral) {
5719                            // No result in current profile, but found candidate in parent user.
5720                            // And we are not going to add emphemeral app, so we can return the
5721                            // result straight away.
5722                            result.add(xpDomainInfo.resolveInfo);
5723                            return filterForEphemeral(result, ephemeralPkgName);
5724                        }
5725                    } else if (result.size() <= 1 && !addEphemeral) {
5726                        // No result in parent user and <= 1 result in current profile, and we
5727                        // are not going to add emphemeral app, so we can return the result without
5728                        // further processing.
5729                        return filterForEphemeral(result, ephemeralPkgName);
5730                    }
5731                    // We have more than one candidate (combining results from current and parent
5732                    // profile), so we need filtering and sorting.
5733                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5734                            intent, flags, result, xpDomainInfo, userId);
5735                    sortResult = true;
5736                }
5737            } else {
5738                final PackageParser.Package pkg = mPackages.get(pkgName);
5739                if (pkg != null) {
5740                    result = filterForEphemeral(filterIfNotSystemUser(
5741                            mActivities.queryIntentForPackage(
5742                                    intent, resolvedType, flags, pkg.activities, userId),
5743                            userId), ephemeralPkgName);
5744                } else {
5745                    // the caller wants to resolve for a particular package; however, there
5746                    // were no installed results, so, try to find an ephemeral result
5747                    addEphemeral = isEphemeralAllowed(
5748                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5749                    result = new ArrayList<ResolveInfo>();
5750                }
5751            }
5752        }
5753        if (addEphemeral) {
5754            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5755            final EphemeralRequest requestObject = new EphemeralRequest(
5756                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5757                    null /*launchIntent*/, null /*callingPackage*/, userId);
5758            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5759                    mContext, mEphemeralResolverConnection, requestObject);
5760            if (intentInfo != null) {
5761                if (DEBUG_EPHEMERAL) {
5762                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5763                }
5764                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5765                ephemeralInstaller.ephemeralResponse = intentInfo;
5766                // make sure this resolver is the default
5767                ephemeralInstaller.isDefault = true;
5768                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5769                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5770                // add a non-generic filter
5771                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5772                ephemeralInstaller.filter.addDataPath(
5773                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5774                result.add(ephemeralInstaller);
5775            }
5776            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5777        }
5778        if (sortResult) {
5779            Collections.sort(result, mResolvePrioritySorter);
5780        }
5781        return filterForEphemeral(result, ephemeralPkgName);
5782    }
5783
5784    private static class CrossProfileDomainInfo {
5785        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5786        ResolveInfo resolveInfo;
5787        /* Best domain verification status of the activities found in the other profile */
5788        int bestDomainVerificationStatus;
5789    }
5790
5791    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5792            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5793        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5794                sourceUserId)) {
5795            return null;
5796        }
5797        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5798                resolvedType, flags, parentUserId);
5799
5800        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5801            return null;
5802        }
5803        CrossProfileDomainInfo result = null;
5804        int size = resultTargetUser.size();
5805        for (int i = 0; i < size; i++) {
5806            ResolveInfo riTargetUser = resultTargetUser.get(i);
5807            // Intent filter verification is only for filters that specify a host. So don't return
5808            // those that handle all web uris.
5809            if (riTargetUser.handleAllWebDataURI) {
5810                continue;
5811            }
5812            String packageName = riTargetUser.activityInfo.packageName;
5813            PackageSetting ps = mSettings.mPackages.get(packageName);
5814            if (ps == null) {
5815                continue;
5816            }
5817            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5818            int status = (int)(verificationState >> 32);
5819            if (result == null) {
5820                result = new CrossProfileDomainInfo();
5821                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5822                        sourceUserId, parentUserId);
5823                result.bestDomainVerificationStatus = status;
5824            } else {
5825                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5826                        result.bestDomainVerificationStatus);
5827            }
5828        }
5829        // Don't consider matches with status NEVER across profiles.
5830        if (result != null && result.bestDomainVerificationStatus
5831                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5832            return null;
5833        }
5834        return result;
5835    }
5836
5837    /**
5838     * Verification statuses are ordered from the worse to the best, except for
5839     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5840     */
5841    private int bestDomainVerificationStatus(int status1, int status2) {
5842        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5843            return status2;
5844        }
5845        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5846            return status1;
5847        }
5848        return (int) MathUtils.max(status1, status2);
5849    }
5850
5851    private boolean isUserEnabled(int userId) {
5852        long callingId = Binder.clearCallingIdentity();
5853        try {
5854            UserInfo userInfo = sUserManager.getUserInfo(userId);
5855            return userInfo != null && userInfo.isEnabled();
5856        } finally {
5857            Binder.restoreCallingIdentity(callingId);
5858        }
5859    }
5860
5861    /**
5862     * Filter out activities with systemUserOnly flag set, when current user is not System.
5863     *
5864     * @return filtered list
5865     */
5866    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5867        if (userId == UserHandle.USER_SYSTEM) {
5868            return resolveInfos;
5869        }
5870        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5871            ResolveInfo info = resolveInfos.get(i);
5872            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5873                resolveInfos.remove(i);
5874            }
5875        }
5876        return resolveInfos;
5877    }
5878
5879    /**
5880     * Filters out ephemeral activities.
5881     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5882     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5883     *
5884     * @param resolveInfos The pre-filtered list of resolved activities
5885     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5886     *          is performed.
5887     * @return A filtered list of resolved activities.
5888     */
5889    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5890            String ephemeralPkgName) {
5891        if (ephemeralPkgName == null) {
5892            return resolveInfos;
5893        }
5894        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5895            ResolveInfo info = resolveInfos.get(i);
5896            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5897            // allow activities that are defined in the provided package
5898            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5899                continue;
5900            }
5901            // allow activities that have been explicitly exposed to ephemeral apps
5902            if (!isEphemeralApp
5903                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5904                continue;
5905            }
5906            resolveInfos.remove(i);
5907        }
5908        return resolveInfos;
5909    }
5910
5911    /**
5912     * @param resolveInfos list of resolve infos in descending priority order
5913     * @return if the list contains a resolve info with non-negative priority
5914     */
5915    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5916        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5917    }
5918
5919    private static boolean hasWebURI(Intent intent) {
5920        if (intent.getData() == null) {
5921            return false;
5922        }
5923        final String scheme = intent.getScheme();
5924        if (TextUtils.isEmpty(scheme)) {
5925            return false;
5926        }
5927        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5928    }
5929
5930    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5931            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5932            int userId) {
5933        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5934
5935        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5936            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5937                    candidates.size());
5938        }
5939
5940        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5941        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5942        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5943        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5944        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5945        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5946
5947        synchronized (mPackages) {
5948            final int count = candidates.size();
5949            // First, try to use linked apps. Partition the candidates into four lists:
5950            // one for the final results, one for the "do not use ever", one for "undefined status"
5951            // and finally one for "browser app type".
5952            for (int n=0; n<count; n++) {
5953                ResolveInfo info = candidates.get(n);
5954                String packageName = info.activityInfo.packageName;
5955                PackageSetting ps = mSettings.mPackages.get(packageName);
5956                if (ps != null) {
5957                    // Add to the special match all list (Browser use case)
5958                    if (info.handleAllWebDataURI) {
5959                        matchAllList.add(info);
5960                        continue;
5961                    }
5962                    // Try to get the status from User settings first
5963                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5964                    int status = (int)(packedStatus >> 32);
5965                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5966                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5967                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
5968                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5969                                    + " : linkgen=" + linkGeneration);
5970                        }
5971                        // Use link-enabled generation as preferredOrder, i.e.
5972                        // prefer newly-enabled over earlier-enabled.
5973                        info.preferredOrder = linkGeneration;
5974                        alwaysList.add(info);
5975                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5976                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
5977                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5978                        }
5979                        neverList.add(info);
5980                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5981                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
5982                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5983                        }
5984                        alwaysAskList.add(info);
5985                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5986                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5987                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
5988                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5989                        }
5990                        undefinedList.add(info);
5991                    }
5992                }
5993            }
5994
5995            // We'll want to include browser possibilities in a few cases
5996            boolean includeBrowser = false;
5997
5998            // First try to add the "always" resolution(s) for the current user, if any
5999            if (alwaysList.size() > 0) {
6000                result.addAll(alwaysList);
6001            } else {
6002                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6003                result.addAll(undefinedList);
6004                // Maybe add one for the other profile.
6005                if (xpDomainInfo != null && (
6006                        xpDomainInfo.bestDomainVerificationStatus
6007                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6008                    result.add(xpDomainInfo.resolveInfo);
6009                }
6010                includeBrowser = true;
6011            }
6012
6013            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6014            // If there were 'always' entries their preferred order has been set, so we also
6015            // back that off to make the alternatives equivalent
6016            if (alwaysAskList.size() > 0) {
6017                for (ResolveInfo i : result) {
6018                    i.preferredOrder = 0;
6019                }
6020                result.addAll(alwaysAskList);
6021                includeBrowser = true;
6022            }
6023
6024            if (includeBrowser) {
6025                // Also add browsers (all of them or only the default one)
6026                if (DEBUG_DOMAIN_VERIFICATION) {
6027                    Slog.v(TAG, "   ...including browsers in candidate set");
6028                }
6029                if ((matchFlags & MATCH_ALL) != 0) {
6030                    result.addAll(matchAllList);
6031                } else {
6032                    // Browser/generic handling case.  If there's a default browser, go straight
6033                    // to that (but only if there is no other higher-priority match).
6034                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6035                    int maxMatchPrio = 0;
6036                    ResolveInfo defaultBrowserMatch = null;
6037                    final int numCandidates = matchAllList.size();
6038                    for (int n = 0; n < numCandidates; n++) {
6039                        ResolveInfo info = matchAllList.get(n);
6040                        // track the highest overall match priority...
6041                        if (info.priority > maxMatchPrio) {
6042                            maxMatchPrio = info.priority;
6043                        }
6044                        // ...and the highest-priority default browser match
6045                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6046                            if (defaultBrowserMatch == null
6047                                    || (defaultBrowserMatch.priority < info.priority)) {
6048                                if (debug) {
6049                                    Slog.v(TAG, "Considering default browser match " + info);
6050                                }
6051                                defaultBrowserMatch = info;
6052                            }
6053                        }
6054                    }
6055                    if (defaultBrowserMatch != null
6056                            && defaultBrowserMatch.priority >= maxMatchPrio
6057                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6058                    {
6059                        if (debug) {
6060                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6061                        }
6062                        result.add(defaultBrowserMatch);
6063                    } else {
6064                        result.addAll(matchAllList);
6065                    }
6066                }
6067
6068                // If there is nothing selected, add all candidates and remove the ones that the user
6069                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6070                if (result.size() == 0) {
6071                    result.addAll(candidates);
6072                    result.removeAll(neverList);
6073                }
6074            }
6075        }
6076        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6077            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6078                    result.size());
6079            for (ResolveInfo info : result) {
6080                Slog.v(TAG, "  + " + info.activityInfo);
6081            }
6082        }
6083        return result;
6084    }
6085
6086    // Returns a packed value as a long:
6087    //
6088    // high 'int'-sized word: link status: undefined/ask/never/always.
6089    // low 'int'-sized word: relative priority among 'always' results.
6090    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6091        long result = ps.getDomainVerificationStatusForUser(userId);
6092        // if none available, get the master status
6093        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6094            if (ps.getIntentFilterVerificationInfo() != null) {
6095                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6096            }
6097        }
6098        return result;
6099    }
6100
6101    private ResolveInfo querySkipCurrentProfileIntents(
6102            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6103            int flags, int sourceUserId) {
6104        if (matchingFilters != null) {
6105            int size = matchingFilters.size();
6106            for (int i = 0; i < size; i ++) {
6107                CrossProfileIntentFilter filter = matchingFilters.get(i);
6108                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6109                    // Checking if there are activities in the target user that can handle the
6110                    // intent.
6111                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6112                            resolvedType, flags, sourceUserId);
6113                    if (resolveInfo != null) {
6114                        return resolveInfo;
6115                    }
6116                }
6117            }
6118        }
6119        return null;
6120    }
6121
6122    // Return matching ResolveInfo in target user if any.
6123    private ResolveInfo queryCrossProfileIntents(
6124            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6125            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6126        if (matchingFilters != null) {
6127            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6128            // match the same intent. For performance reasons, it is better not to
6129            // run queryIntent twice for the same userId
6130            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6131            int size = matchingFilters.size();
6132            for (int i = 0; i < size; i++) {
6133                CrossProfileIntentFilter filter = matchingFilters.get(i);
6134                int targetUserId = filter.getTargetUserId();
6135                boolean skipCurrentProfile =
6136                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6137                boolean skipCurrentProfileIfNoMatchFound =
6138                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6139                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6140                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6141                    // Checking if there are activities in the target user that can handle the
6142                    // intent.
6143                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6144                            resolvedType, flags, sourceUserId);
6145                    if (resolveInfo != null) return resolveInfo;
6146                    alreadyTriedUserIds.put(targetUserId, true);
6147                }
6148            }
6149        }
6150        return null;
6151    }
6152
6153    /**
6154     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6155     * will forward the intent to the filter's target user.
6156     * Otherwise, returns null.
6157     */
6158    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6159            String resolvedType, int flags, int sourceUserId) {
6160        int targetUserId = filter.getTargetUserId();
6161        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6162                resolvedType, flags, targetUserId);
6163        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6164            // If all the matches in the target profile are suspended, return null.
6165            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6166                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6167                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6168                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6169                            targetUserId);
6170                }
6171            }
6172        }
6173        return null;
6174    }
6175
6176    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6177            int sourceUserId, int targetUserId) {
6178        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6179        long ident = Binder.clearCallingIdentity();
6180        boolean targetIsProfile;
6181        try {
6182            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6183        } finally {
6184            Binder.restoreCallingIdentity(ident);
6185        }
6186        String className;
6187        if (targetIsProfile) {
6188            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6189        } else {
6190            className = FORWARD_INTENT_TO_PARENT;
6191        }
6192        ComponentName forwardingActivityComponentName = new ComponentName(
6193                mAndroidApplication.packageName, className);
6194        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6195                sourceUserId);
6196        if (!targetIsProfile) {
6197            forwardingActivityInfo.showUserIcon = targetUserId;
6198            forwardingResolveInfo.noResourceId = true;
6199        }
6200        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6201        forwardingResolveInfo.priority = 0;
6202        forwardingResolveInfo.preferredOrder = 0;
6203        forwardingResolveInfo.match = 0;
6204        forwardingResolveInfo.isDefault = true;
6205        forwardingResolveInfo.filter = filter;
6206        forwardingResolveInfo.targetUserId = targetUserId;
6207        return forwardingResolveInfo;
6208    }
6209
6210    @Override
6211    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6212            Intent[] specifics, String[] specificTypes, Intent intent,
6213            String resolvedType, int flags, int userId) {
6214        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6215                specificTypes, intent, resolvedType, flags, userId));
6216    }
6217
6218    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6219            Intent[] specifics, String[] specificTypes, Intent intent,
6220            String resolvedType, int flags, int userId) {
6221        if (!sUserManager.exists(userId)) return Collections.emptyList();
6222        flags = updateFlagsForResolve(flags, userId, intent);
6223        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6224                false /* requireFullPermission */, false /* checkShell */,
6225                "query intent activity options");
6226        final String resultsAction = intent.getAction();
6227
6228        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6229                | PackageManager.GET_RESOLVED_FILTER, userId);
6230
6231        if (DEBUG_INTENT_MATCHING) {
6232            Log.v(TAG, "Query " + intent + ": " + results);
6233        }
6234
6235        int specificsPos = 0;
6236        int N;
6237
6238        // todo: note that the algorithm used here is O(N^2).  This
6239        // isn't a problem in our current environment, but if we start running
6240        // into situations where we have more than 5 or 10 matches then this
6241        // should probably be changed to something smarter...
6242
6243        // First we go through and resolve each of the specific items
6244        // that were supplied, taking care of removing any corresponding
6245        // duplicate items in the generic resolve list.
6246        if (specifics != null) {
6247            for (int i=0; i<specifics.length; i++) {
6248                final Intent sintent = specifics[i];
6249                if (sintent == null) {
6250                    continue;
6251                }
6252
6253                if (DEBUG_INTENT_MATCHING) {
6254                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6255                }
6256
6257                String action = sintent.getAction();
6258                if (resultsAction != null && resultsAction.equals(action)) {
6259                    // If this action was explicitly requested, then don't
6260                    // remove things that have it.
6261                    action = null;
6262                }
6263
6264                ResolveInfo ri = null;
6265                ActivityInfo ai = null;
6266
6267                ComponentName comp = sintent.getComponent();
6268                if (comp == null) {
6269                    ri = resolveIntent(
6270                        sintent,
6271                        specificTypes != null ? specificTypes[i] : null,
6272                            flags, userId);
6273                    if (ri == null) {
6274                        continue;
6275                    }
6276                    if (ri == mResolveInfo) {
6277                        // ACK!  Must do something better with this.
6278                    }
6279                    ai = ri.activityInfo;
6280                    comp = new ComponentName(ai.applicationInfo.packageName,
6281                            ai.name);
6282                } else {
6283                    ai = getActivityInfo(comp, flags, userId);
6284                    if (ai == null) {
6285                        continue;
6286                    }
6287                }
6288
6289                // Look for any generic query activities that are duplicates
6290                // of this specific one, and remove them from the results.
6291                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6292                N = results.size();
6293                int j;
6294                for (j=specificsPos; j<N; j++) {
6295                    ResolveInfo sri = results.get(j);
6296                    if ((sri.activityInfo.name.equals(comp.getClassName())
6297                            && sri.activityInfo.applicationInfo.packageName.equals(
6298                                    comp.getPackageName()))
6299                        || (action != null && sri.filter.matchAction(action))) {
6300                        results.remove(j);
6301                        if (DEBUG_INTENT_MATCHING) Log.v(
6302                            TAG, "Removing duplicate item from " + j
6303                            + " due to specific " + specificsPos);
6304                        if (ri == null) {
6305                            ri = sri;
6306                        }
6307                        j--;
6308                        N--;
6309                    }
6310                }
6311
6312                // Add this specific item to its proper place.
6313                if (ri == null) {
6314                    ri = new ResolveInfo();
6315                    ri.activityInfo = ai;
6316                }
6317                results.add(specificsPos, ri);
6318                ri.specificIndex = i;
6319                specificsPos++;
6320            }
6321        }
6322
6323        // Now we go through the remaining generic results and remove any
6324        // duplicate actions that are found here.
6325        N = results.size();
6326        for (int i=specificsPos; i<N-1; i++) {
6327            final ResolveInfo rii = results.get(i);
6328            if (rii.filter == null) {
6329                continue;
6330            }
6331
6332            // Iterate over all of the actions of this result's intent
6333            // filter...  typically this should be just one.
6334            final Iterator<String> it = rii.filter.actionsIterator();
6335            if (it == null) {
6336                continue;
6337            }
6338            while (it.hasNext()) {
6339                final String action = it.next();
6340                if (resultsAction != null && resultsAction.equals(action)) {
6341                    // If this action was explicitly requested, then don't
6342                    // remove things that have it.
6343                    continue;
6344                }
6345                for (int j=i+1; j<N; j++) {
6346                    final ResolveInfo rij = results.get(j);
6347                    if (rij.filter != null && rij.filter.hasAction(action)) {
6348                        results.remove(j);
6349                        if (DEBUG_INTENT_MATCHING) Log.v(
6350                            TAG, "Removing duplicate item from " + j
6351                            + " due to action " + action + " at " + i);
6352                        j--;
6353                        N--;
6354                    }
6355                }
6356            }
6357
6358            // If the caller didn't request filter information, drop it now
6359            // so we don't have to marshall/unmarshall it.
6360            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6361                rii.filter = null;
6362            }
6363        }
6364
6365        // Filter out the caller activity if so requested.
6366        if (caller != null) {
6367            N = results.size();
6368            for (int i=0; i<N; i++) {
6369                ActivityInfo ainfo = results.get(i).activityInfo;
6370                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6371                        && caller.getClassName().equals(ainfo.name)) {
6372                    results.remove(i);
6373                    break;
6374                }
6375            }
6376        }
6377
6378        // If the caller didn't request filter information,
6379        // drop them now so we don't have to
6380        // marshall/unmarshall it.
6381        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6382            N = results.size();
6383            for (int i=0; i<N; i++) {
6384                results.get(i).filter = null;
6385            }
6386        }
6387
6388        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6389        return results;
6390    }
6391
6392    @Override
6393    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6394            String resolvedType, int flags, int userId) {
6395        return new ParceledListSlice<>(
6396                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6397    }
6398
6399    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6400            String resolvedType, int flags, int userId) {
6401        if (!sUserManager.exists(userId)) return Collections.emptyList();
6402        flags = updateFlagsForResolve(flags, userId, intent);
6403        ComponentName comp = intent.getComponent();
6404        if (comp == null) {
6405            if (intent.getSelector() != null) {
6406                intent = intent.getSelector();
6407                comp = intent.getComponent();
6408            }
6409        }
6410        if (comp != null) {
6411            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6412            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6413            if (ai != null) {
6414                ResolveInfo ri = new ResolveInfo();
6415                ri.activityInfo = ai;
6416                list.add(ri);
6417            }
6418            return list;
6419        }
6420
6421        // reader
6422        synchronized (mPackages) {
6423            String pkgName = intent.getPackage();
6424            if (pkgName == null) {
6425                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6426            }
6427            final PackageParser.Package pkg = mPackages.get(pkgName);
6428            if (pkg != null) {
6429                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6430                        userId);
6431            }
6432            return Collections.emptyList();
6433        }
6434    }
6435
6436    @Override
6437    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6438        if (!sUserManager.exists(userId)) return null;
6439        flags = updateFlagsForResolve(flags, userId, intent);
6440        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6441        if (query != null) {
6442            if (query.size() >= 1) {
6443                // If there is more than one service with the same priority,
6444                // just arbitrarily pick the first one.
6445                return query.get(0);
6446            }
6447        }
6448        return null;
6449    }
6450
6451    @Override
6452    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6453            String resolvedType, int flags, int userId) {
6454        return new ParceledListSlice<>(
6455                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6456    }
6457
6458    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6459            String resolvedType, int flags, int userId) {
6460        if (!sUserManager.exists(userId)) return Collections.emptyList();
6461        flags = updateFlagsForResolve(flags, userId, intent);
6462        ComponentName comp = intent.getComponent();
6463        if (comp == null) {
6464            if (intent.getSelector() != null) {
6465                intent = intent.getSelector();
6466                comp = intent.getComponent();
6467            }
6468        }
6469        if (comp != null) {
6470            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6471            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6472            if (si != null) {
6473                final ResolveInfo ri = new ResolveInfo();
6474                ri.serviceInfo = si;
6475                list.add(ri);
6476            }
6477            return list;
6478        }
6479
6480        // reader
6481        synchronized (mPackages) {
6482            String pkgName = intent.getPackage();
6483            if (pkgName == null) {
6484                return mServices.queryIntent(intent, resolvedType, flags, userId);
6485            }
6486            final PackageParser.Package pkg = mPackages.get(pkgName);
6487            if (pkg != null) {
6488                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6489                        userId);
6490            }
6491            return Collections.emptyList();
6492        }
6493    }
6494
6495    @Override
6496    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6497            String resolvedType, int flags, int userId) {
6498        return new ParceledListSlice<>(
6499                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6500    }
6501
6502    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6503            Intent intent, String resolvedType, int flags, int userId) {
6504        if (!sUserManager.exists(userId)) return Collections.emptyList();
6505        flags = updateFlagsForResolve(flags, userId, intent);
6506        ComponentName comp = intent.getComponent();
6507        if (comp == null) {
6508            if (intent.getSelector() != null) {
6509                intent = intent.getSelector();
6510                comp = intent.getComponent();
6511            }
6512        }
6513        if (comp != null) {
6514            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6515            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6516            if (pi != null) {
6517                final ResolveInfo ri = new ResolveInfo();
6518                ri.providerInfo = pi;
6519                list.add(ri);
6520            }
6521            return list;
6522        }
6523
6524        // reader
6525        synchronized (mPackages) {
6526            String pkgName = intent.getPackage();
6527            if (pkgName == null) {
6528                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6529            }
6530            final PackageParser.Package pkg = mPackages.get(pkgName);
6531            if (pkg != null) {
6532                return mProviders.queryIntentForPackage(
6533                        intent, resolvedType, flags, pkg.providers, userId);
6534            }
6535            return Collections.emptyList();
6536        }
6537    }
6538
6539    @Override
6540    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6541        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6542        flags = updateFlagsForPackage(flags, userId, null);
6543        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6544        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6545                true /* requireFullPermission */, false /* checkShell */,
6546                "get installed packages");
6547
6548        // writer
6549        synchronized (mPackages) {
6550            ArrayList<PackageInfo> list;
6551            if (listUninstalled) {
6552                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6553                for (PackageSetting ps : mSettings.mPackages.values()) {
6554                    final PackageInfo pi;
6555                    if (ps.pkg != null) {
6556                        pi = generatePackageInfo(ps, flags, userId);
6557                    } else {
6558                        pi = generatePackageInfo(ps, flags, userId);
6559                    }
6560                    if (pi != null) {
6561                        list.add(pi);
6562                    }
6563                }
6564            } else {
6565                list = new ArrayList<PackageInfo>(mPackages.size());
6566                for (PackageParser.Package p : mPackages.values()) {
6567                    final PackageInfo pi =
6568                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6569                    if (pi != null) {
6570                        list.add(pi);
6571                    }
6572                }
6573            }
6574
6575            return new ParceledListSlice<PackageInfo>(list);
6576        }
6577    }
6578
6579    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6580            String[] permissions, boolean[] tmp, int flags, int userId) {
6581        int numMatch = 0;
6582        final PermissionsState permissionsState = ps.getPermissionsState();
6583        for (int i=0; i<permissions.length; i++) {
6584            final String permission = permissions[i];
6585            if (permissionsState.hasPermission(permission, userId)) {
6586                tmp[i] = true;
6587                numMatch++;
6588            } else {
6589                tmp[i] = false;
6590            }
6591        }
6592        if (numMatch == 0) {
6593            return;
6594        }
6595        final PackageInfo pi;
6596        if (ps.pkg != null) {
6597            pi = generatePackageInfo(ps, flags, userId);
6598        } else {
6599            pi = generatePackageInfo(ps, flags, userId);
6600        }
6601        // The above might return null in cases of uninstalled apps or install-state
6602        // skew across users/profiles.
6603        if (pi != null) {
6604            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6605                if (numMatch == permissions.length) {
6606                    pi.requestedPermissions = permissions;
6607                } else {
6608                    pi.requestedPermissions = new String[numMatch];
6609                    numMatch = 0;
6610                    for (int i=0; i<permissions.length; i++) {
6611                        if (tmp[i]) {
6612                            pi.requestedPermissions[numMatch] = permissions[i];
6613                            numMatch++;
6614                        }
6615                    }
6616                }
6617            }
6618            list.add(pi);
6619        }
6620    }
6621
6622    @Override
6623    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6624            String[] permissions, int flags, int userId) {
6625        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6626        flags = updateFlagsForPackage(flags, userId, permissions);
6627        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6628                true /* requireFullPermission */, false /* checkShell */,
6629                "get packages holding permissions");
6630        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6631
6632        // writer
6633        synchronized (mPackages) {
6634            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6635            boolean[] tmpBools = new boolean[permissions.length];
6636            if (listUninstalled) {
6637                for (PackageSetting ps : mSettings.mPackages.values()) {
6638                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6639                            userId);
6640                }
6641            } else {
6642                for (PackageParser.Package pkg : mPackages.values()) {
6643                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6644                    if (ps != null) {
6645                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6646                                userId);
6647                    }
6648                }
6649            }
6650
6651            return new ParceledListSlice<PackageInfo>(list);
6652        }
6653    }
6654
6655    @Override
6656    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6657        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6658        flags = updateFlagsForApplication(flags, userId, null);
6659        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6660
6661        // writer
6662        synchronized (mPackages) {
6663            ArrayList<ApplicationInfo> list;
6664            if (listUninstalled) {
6665                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6666                for (PackageSetting ps : mSettings.mPackages.values()) {
6667                    ApplicationInfo ai;
6668                    int effectiveFlags = flags;
6669                    if (ps.isSystem()) {
6670                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6671                    }
6672                    if (ps.pkg != null) {
6673                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6674                                ps.readUserState(userId), userId);
6675                    } else {
6676                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6677                                userId);
6678                    }
6679                    if (ai != null) {
6680                        list.add(ai);
6681                    }
6682                }
6683            } else {
6684                list = new ArrayList<ApplicationInfo>(mPackages.size());
6685                for (PackageParser.Package p : mPackages.values()) {
6686                    if (p.mExtras != null) {
6687                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6688                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6689                        if (ai != null) {
6690                            list.add(ai);
6691                        }
6692                    }
6693                }
6694            }
6695
6696            return new ParceledListSlice<ApplicationInfo>(list);
6697        }
6698    }
6699
6700    @Override
6701    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6702        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6703            return null;
6704        }
6705
6706        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6707                "getEphemeralApplications");
6708        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6709                true /* requireFullPermission */, false /* checkShell */,
6710                "getEphemeralApplications");
6711        synchronized (mPackages) {
6712            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6713                    .getEphemeralApplicationsLPw(userId);
6714            if (ephemeralApps != null) {
6715                return new ParceledListSlice<>(ephemeralApps);
6716            }
6717        }
6718        return null;
6719    }
6720
6721    @Override
6722    public boolean isEphemeralApplication(String packageName, int userId) {
6723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6724                true /* requireFullPermission */, false /* checkShell */,
6725                "isEphemeral");
6726        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6727            return false;
6728        }
6729
6730        if (!isCallerSameApp(packageName)) {
6731            return false;
6732        }
6733        synchronized (mPackages) {
6734            PackageParser.Package pkg = mPackages.get(packageName);
6735            if (pkg != null) {
6736                return pkg.applicationInfo.isEphemeralApp();
6737            }
6738        }
6739        return false;
6740    }
6741
6742    @Override
6743    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6744        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6745            return null;
6746        }
6747
6748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6749                true /* requireFullPermission */, false /* checkShell */,
6750                "getCookie");
6751        if (!isCallerSameApp(packageName)) {
6752            return null;
6753        }
6754        synchronized (mPackages) {
6755            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6756                    packageName, userId);
6757        }
6758    }
6759
6760    @Override
6761    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6762        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6763            return true;
6764        }
6765
6766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6767                true /* requireFullPermission */, true /* checkShell */,
6768                "setCookie");
6769        if (!isCallerSameApp(packageName)) {
6770            return false;
6771        }
6772        synchronized (mPackages) {
6773            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6774                    packageName, cookie, userId);
6775        }
6776    }
6777
6778    @Override
6779    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6780        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6781            return null;
6782        }
6783
6784        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6785                "getEphemeralApplicationIcon");
6786        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6787                true /* requireFullPermission */, false /* checkShell */,
6788                "getEphemeralApplicationIcon");
6789        synchronized (mPackages) {
6790            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6791                    packageName, userId);
6792        }
6793    }
6794
6795    private boolean isCallerSameApp(String packageName) {
6796        PackageParser.Package pkg = mPackages.get(packageName);
6797        return pkg != null
6798                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6799    }
6800
6801    @Override
6802    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6803        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6804    }
6805
6806    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6807        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6808
6809        // reader
6810        synchronized (mPackages) {
6811            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6812            final int userId = UserHandle.getCallingUserId();
6813            while (i.hasNext()) {
6814                final PackageParser.Package p = i.next();
6815                if (p.applicationInfo == null) continue;
6816
6817                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6818                        && !p.applicationInfo.isDirectBootAware();
6819                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6820                        && p.applicationInfo.isDirectBootAware();
6821
6822                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6823                        && (!mSafeMode || isSystemApp(p))
6824                        && (matchesUnaware || matchesAware)) {
6825                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6826                    if (ps != null) {
6827                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6828                                ps.readUserState(userId), userId);
6829                        if (ai != null) {
6830                            finalList.add(ai);
6831                        }
6832                    }
6833                }
6834            }
6835        }
6836
6837        return finalList;
6838    }
6839
6840    @Override
6841    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6842        if (!sUserManager.exists(userId)) return null;
6843        flags = updateFlagsForComponent(flags, userId, name);
6844        // reader
6845        synchronized (mPackages) {
6846            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6847            PackageSetting ps = provider != null
6848                    ? mSettings.mPackages.get(provider.owner.packageName)
6849                    : null;
6850            return ps != null
6851                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6852                    ? PackageParser.generateProviderInfo(provider, flags,
6853                            ps.readUserState(userId), userId)
6854                    : null;
6855        }
6856    }
6857
6858    /**
6859     * @deprecated
6860     */
6861    @Deprecated
6862    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6863        // reader
6864        synchronized (mPackages) {
6865            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6866                    .entrySet().iterator();
6867            final int userId = UserHandle.getCallingUserId();
6868            while (i.hasNext()) {
6869                Map.Entry<String, PackageParser.Provider> entry = i.next();
6870                PackageParser.Provider p = entry.getValue();
6871                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6872
6873                if (ps != null && p.syncable
6874                        && (!mSafeMode || (p.info.applicationInfo.flags
6875                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6876                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6877                            ps.readUserState(userId), userId);
6878                    if (info != null) {
6879                        outNames.add(entry.getKey());
6880                        outInfo.add(info);
6881                    }
6882                }
6883            }
6884        }
6885    }
6886
6887    @Override
6888    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6889            int uid, int flags) {
6890        final int userId = processName != null ? UserHandle.getUserId(uid)
6891                : UserHandle.getCallingUserId();
6892        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6893        flags = updateFlagsForComponent(flags, userId, processName);
6894
6895        ArrayList<ProviderInfo> finalList = null;
6896        // reader
6897        synchronized (mPackages) {
6898            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6899            while (i.hasNext()) {
6900                final PackageParser.Provider p = i.next();
6901                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6902                if (ps != null && p.info.authority != null
6903                        && (processName == null
6904                                || (p.info.processName.equals(processName)
6905                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6906                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6907                    if (finalList == null) {
6908                        finalList = new ArrayList<ProviderInfo>(3);
6909                    }
6910                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6911                            ps.readUserState(userId), userId);
6912                    if (info != null) {
6913                        finalList.add(info);
6914                    }
6915                }
6916            }
6917        }
6918
6919        if (finalList != null) {
6920            Collections.sort(finalList, mProviderInitOrderSorter);
6921            return new ParceledListSlice<ProviderInfo>(finalList);
6922        }
6923
6924        return ParceledListSlice.emptyList();
6925    }
6926
6927    @Override
6928    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6929        // reader
6930        synchronized (mPackages) {
6931            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6932            return PackageParser.generateInstrumentationInfo(i, flags);
6933        }
6934    }
6935
6936    @Override
6937    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6938            String targetPackage, int flags) {
6939        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6940    }
6941
6942    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6943            int flags) {
6944        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6945
6946        // reader
6947        synchronized (mPackages) {
6948            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6949            while (i.hasNext()) {
6950                final PackageParser.Instrumentation p = i.next();
6951                if (targetPackage == null
6952                        || targetPackage.equals(p.info.targetPackage)) {
6953                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6954                            flags);
6955                    if (ii != null) {
6956                        finalList.add(ii);
6957                    }
6958                }
6959            }
6960        }
6961
6962        return finalList;
6963    }
6964
6965    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6966        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6967        if (overlays == null) {
6968            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6969            return;
6970        }
6971        for (PackageParser.Package opkg : overlays.values()) {
6972            // Not much to do if idmap fails: we already logged the error
6973            // and we certainly don't want to abort installation of pkg simply
6974            // because an overlay didn't fit properly. For these reasons,
6975            // ignore the return value of createIdmapForPackagePairLI.
6976            createIdmapForPackagePairLI(pkg, opkg);
6977        }
6978    }
6979
6980    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6981            PackageParser.Package opkg) {
6982        if (!opkg.mTrustedOverlay) {
6983            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6984                    opkg.baseCodePath + ": overlay not trusted");
6985            return false;
6986        }
6987        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6988        if (overlaySet == null) {
6989            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6990                    opkg.baseCodePath + " but target package has no known overlays");
6991            return false;
6992        }
6993        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6994        // TODO: generate idmap for split APKs
6995        try {
6996            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6997        } catch (InstallerException e) {
6998            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6999                    + opkg.baseCodePath);
7000            return false;
7001        }
7002        PackageParser.Package[] overlayArray =
7003            overlaySet.values().toArray(new PackageParser.Package[0]);
7004        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7005            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7006                return p1.mOverlayPriority - p2.mOverlayPriority;
7007            }
7008        };
7009        Arrays.sort(overlayArray, cmp);
7010
7011        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7012        int i = 0;
7013        for (PackageParser.Package p : overlayArray) {
7014            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7015        }
7016        return true;
7017    }
7018
7019    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7020        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7021        try {
7022            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7023        } finally {
7024            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7025        }
7026    }
7027
7028    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7029        final File[] files = dir.listFiles();
7030        if (ArrayUtils.isEmpty(files)) {
7031            Log.d(TAG, "No files in app dir " + dir);
7032            return;
7033        }
7034
7035        if (DEBUG_PACKAGE_SCANNING) {
7036            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7037                    + " flags=0x" + Integer.toHexString(parseFlags));
7038        }
7039        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7040                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7041
7042        // Submit files for parsing in parallel
7043        int fileCount = 0;
7044        for (File file : files) {
7045            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7046                    && !PackageInstallerService.isStageName(file.getName());
7047            if (!isPackage) {
7048                // Ignore entries which are not packages
7049                continue;
7050            }
7051            parallelPackageParser.submit(file, parseFlags);
7052            fileCount++;
7053        }
7054
7055        // Process results one by one
7056        for (; fileCount > 0; fileCount--) {
7057            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7058            Throwable throwable = parseResult.throwable;
7059            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7060
7061            if (throwable == null) {
7062                try {
7063                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7064                            currentTime, null);
7065                } catch (PackageManagerException e) {
7066                    errorCode = e.error;
7067                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7068                }
7069            } else if (throwable instanceof PackageParser.PackageParserException) {
7070                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7071                        throwable;
7072                errorCode = e.error;
7073                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7074            } else {
7075                throw new IllegalStateException("Unexpected exception occurred while parsing "
7076                        + parseResult.scanFile, throwable);
7077            }
7078
7079            // Delete invalid userdata apps
7080            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7081                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7082                logCriticalInfo(Log.WARN,
7083                        "Deleting invalid package at " + parseResult.scanFile);
7084                removeCodePathLI(parseResult.scanFile);
7085            }
7086        }
7087        parallelPackageParser.close();
7088    }
7089
7090    private static File getSettingsProblemFile() {
7091        File dataDir = Environment.getDataDirectory();
7092        File systemDir = new File(dataDir, "system");
7093        File fname = new File(systemDir, "uiderrors.txt");
7094        return fname;
7095    }
7096
7097    static void reportSettingsProblem(int priority, String msg) {
7098        logCriticalInfo(priority, msg);
7099    }
7100
7101    static void logCriticalInfo(int priority, String msg) {
7102        Slog.println(priority, TAG, msg);
7103        EventLogTags.writePmCriticalInfo(msg);
7104        try {
7105            File fname = getSettingsProblemFile();
7106            FileOutputStream out = new FileOutputStream(fname, true);
7107            PrintWriter pw = new FastPrintWriter(out);
7108            SimpleDateFormat formatter = new SimpleDateFormat();
7109            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7110            pw.println(dateString + ": " + msg);
7111            pw.close();
7112            FileUtils.setPermissions(
7113                    fname.toString(),
7114                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7115                    -1, -1);
7116        } catch (java.io.IOException e) {
7117        }
7118    }
7119
7120    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7121        if (srcFile.isDirectory()) {
7122            final File baseFile = new File(pkg.baseCodePath);
7123            long maxModifiedTime = baseFile.lastModified();
7124            if (pkg.splitCodePaths != null) {
7125                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7126                    final File splitFile = new File(pkg.splitCodePaths[i]);
7127                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7128                }
7129            }
7130            return maxModifiedTime;
7131        }
7132        return srcFile.lastModified();
7133    }
7134
7135    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7136            final int policyFlags) throws PackageManagerException {
7137        // When upgrading from pre-N MR1, verify the package time stamp using the package
7138        // directory and not the APK file.
7139        final long lastModifiedTime = mIsPreNMR1Upgrade
7140                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7141        if (ps != null
7142                && ps.codePath.equals(srcFile)
7143                && ps.timeStamp == lastModifiedTime
7144                && !isCompatSignatureUpdateNeeded(pkg)
7145                && !isRecoverSignatureUpdateNeeded(pkg)) {
7146            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7147            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7148            ArraySet<PublicKey> signingKs;
7149            synchronized (mPackages) {
7150                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7151            }
7152            if (ps.signatures.mSignatures != null
7153                    && ps.signatures.mSignatures.length != 0
7154                    && signingKs != null) {
7155                // Optimization: reuse the existing cached certificates
7156                // if the package appears to be unchanged.
7157                pkg.mSignatures = ps.signatures.mSignatures;
7158                pkg.mSigningKeys = signingKs;
7159                return;
7160            }
7161
7162            Slog.w(TAG, "PackageSetting for " + ps.name
7163                    + " is missing signatures.  Collecting certs again to recover them.");
7164        } else {
7165            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7166        }
7167
7168        try {
7169            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7170            PackageParser.collectCertificates(pkg, policyFlags);
7171        } catch (PackageParserException e) {
7172            throw PackageManagerException.from(e);
7173        } finally {
7174            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7175        }
7176    }
7177
7178    /**
7179     *  Traces a package scan.
7180     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7181     */
7182    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7183            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7184        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7185        try {
7186            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7187        } finally {
7188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7189        }
7190    }
7191
7192    /**
7193     *  Scans a package and returns the newly parsed package.
7194     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7195     */
7196    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7197            long currentTime, UserHandle user) throws PackageManagerException {
7198        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7199        PackageParser pp = new PackageParser();
7200        pp.setSeparateProcesses(mSeparateProcesses);
7201        pp.setOnlyCoreApps(mOnlyCore);
7202        pp.setDisplayMetrics(mMetrics);
7203
7204        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7205            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7206        }
7207
7208        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7209        final PackageParser.Package pkg;
7210        try {
7211            pkg = pp.parsePackage(scanFile, parseFlags);
7212        } catch (PackageParserException e) {
7213            throw PackageManagerException.from(e);
7214        } finally {
7215            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7216        }
7217
7218        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7219    }
7220
7221    /**
7222     *  Scans a package and returns the newly parsed package.
7223     *  @throws PackageManagerException on a parse error.
7224     */
7225    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7226            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7227            throws PackageManagerException {
7228        // If the package has children and this is the first dive in the function
7229        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7230        // packages (parent and children) would be successfully scanned before the
7231        // actual scan since scanning mutates internal state and we want to atomically
7232        // install the package and its children.
7233        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7234            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7235                scanFlags |= SCAN_CHECK_ONLY;
7236            }
7237        } else {
7238            scanFlags &= ~SCAN_CHECK_ONLY;
7239        }
7240
7241        // Scan the parent
7242        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7243                scanFlags, currentTime, user);
7244
7245        // Scan the children
7246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7247        for (int i = 0; i < childCount; i++) {
7248            PackageParser.Package childPackage = pkg.childPackages.get(i);
7249            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7250                    currentTime, user);
7251        }
7252
7253
7254        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7255            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7256        }
7257
7258        return scannedPkg;
7259    }
7260
7261    /**
7262     *  Scans a package and returns the newly parsed package.
7263     *  @throws PackageManagerException on a parse error.
7264     */
7265    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7266            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7267            throws PackageManagerException {
7268        PackageSetting ps = null;
7269        PackageSetting updatedPkg;
7270        // reader
7271        synchronized (mPackages) {
7272            // Look to see if we already know about this package.
7273            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7274            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7275                // This package has been renamed to its original name.  Let's
7276                // use that.
7277                ps = mSettings.getPackageLPr(oldName);
7278            }
7279            // If there was no original package, see one for the real package name.
7280            if (ps == null) {
7281                ps = mSettings.getPackageLPr(pkg.packageName);
7282            }
7283            // Check to see if this package could be hiding/updating a system
7284            // package.  Must look for it either under the original or real
7285            // package name depending on our state.
7286            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7287            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7288
7289            // If this is a package we don't know about on the system partition, we
7290            // may need to remove disabled child packages on the system partition
7291            // or may need to not add child packages if the parent apk is updated
7292            // on the data partition and no longer defines this child package.
7293            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7294                // If this is a parent package for an updated system app and this system
7295                // app got an OTA update which no longer defines some of the child packages
7296                // we have to prune them from the disabled system packages.
7297                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7298                if (disabledPs != null) {
7299                    final int scannedChildCount = (pkg.childPackages != null)
7300                            ? pkg.childPackages.size() : 0;
7301                    final int disabledChildCount = disabledPs.childPackageNames != null
7302                            ? disabledPs.childPackageNames.size() : 0;
7303                    for (int i = 0; i < disabledChildCount; i++) {
7304                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7305                        boolean disabledPackageAvailable = false;
7306                        for (int j = 0; j < scannedChildCount; j++) {
7307                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7308                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7309                                disabledPackageAvailable = true;
7310                                break;
7311                            }
7312                         }
7313                         if (!disabledPackageAvailable) {
7314                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7315                         }
7316                    }
7317                }
7318            }
7319        }
7320
7321        boolean updatedPkgBetter = false;
7322        // First check if this is a system package that may involve an update
7323        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7324            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7325            // it needs to drop FLAG_PRIVILEGED.
7326            if (locationIsPrivileged(scanFile)) {
7327                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7328            } else {
7329                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7330            }
7331
7332            if (ps != null && !ps.codePath.equals(scanFile)) {
7333                // The path has changed from what was last scanned...  check the
7334                // version of the new path against what we have stored to determine
7335                // what to do.
7336                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7337                if (pkg.mVersionCode <= ps.versionCode) {
7338                    // The system package has been updated and the code path does not match
7339                    // Ignore entry. Skip it.
7340                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7341                            + " ignored: updated version " + ps.versionCode
7342                            + " better than this " + pkg.mVersionCode);
7343                    if (!updatedPkg.codePath.equals(scanFile)) {
7344                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7345                                + ps.name + " changing from " + updatedPkg.codePathString
7346                                + " to " + scanFile);
7347                        updatedPkg.codePath = scanFile;
7348                        updatedPkg.codePathString = scanFile.toString();
7349                        updatedPkg.resourcePath = scanFile;
7350                        updatedPkg.resourcePathString = scanFile.toString();
7351                    }
7352                    updatedPkg.pkg = pkg;
7353                    updatedPkg.versionCode = pkg.mVersionCode;
7354
7355                    // Update the disabled system child packages to point to the package too.
7356                    final int childCount = updatedPkg.childPackageNames != null
7357                            ? updatedPkg.childPackageNames.size() : 0;
7358                    for (int i = 0; i < childCount; i++) {
7359                        String childPackageName = updatedPkg.childPackageNames.get(i);
7360                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7361                                childPackageName);
7362                        if (updatedChildPkg != null) {
7363                            updatedChildPkg.pkg = pkg;
7364                            updatedChildPkg.versionCode = pkg.mVersionCode;
7365                        }
7366                    }
7367
7368                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7369                            + scanFile + " ignored: updated version " + ps.versionCode
7370                            + " better than this " + pkg.mVersionCode);
7371                } else {
7372                    // The current app on the system partition is better than
7373                    // what we have updated to on the data partition; switch
7374                    // back to the system partition version.
7375                    // At this point, its safely assumed that package installation for
7376                    // apps in system partition will go through. If not there won't be a working
7377                    // version of the app
7378                    // writer
7379                    synchronized (mPackages) {
7380                        // Just remove the loaded entries from package lists.
7381                        mPackages.remove(ps.name);
7382                    }
7383
7384                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7385                            + " reverting from " + ps.codePathString
7386                            + ": new version " + pkg.mVersionCode
7387                            + " better than installed " + ps.versionCode);
7388
7389                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7390                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7391                    synchronized (mInstallLock) {
7392                        args.cleanUpResourcesLI();
7393                    }
7394                    synchronized (mPackages) {
7395                        mSettings.enableSystemPackageLPw(ps.name);
7396                    }
7397                    updatedPkgBetter = true;
7398                }
7399            }
7400        }
7401
7402        if (updatedPkg != null) {
7403            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7404            // initially
7405            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7406
7407            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7408            // flag set initially
7409            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7410                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7411            }
7412        }
7413
7414        // Verify certificates against what was last scanned
7415        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7416
7417        /*
7418         * A new system app appeared, but we already had a non-system one of the
7419         * same name installed earlier.
7420         */
7421        boolean shouldHideSystemApp = false;
7422        if (updatedPkg == null && ps != null
7423                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7424            /*
7425             * Check to make sure the signatures match first. If they don't,
7426             * wipe the installed application and its data.
7427             */
7428            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7429                    != PackageManager.SIGNATURE_MATCH) {
7430                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7431                        + " signatures don't match existing userdata copy; removing");
7432                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7433                        "scanPackageInternalLI")) {
7434                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7435                }
7436                ps = null;
7437            } else {
7438                /*
7439                 * If the newly-added system app is an older version than the
7440                 * already installed version, hide it. It will be scanned later
7441                 * and re-added like an update.
7442                 */
7443                if (pkg.mVersionCode <= ps.versionCode) {
7444                    shouldHideSystemApp = true;
7445                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7446                            + " but new version " + pkg.mVersionCode + " better than installed "
7447                            + ps.versionCode + "; hiding system");
7448                } else {
7449                    /*
7450                     * The newly found system app is a newer version that the
7451                     * one previously installed. Simply remove the
7452                     * already-installed application and replace it with our own
7453                     * while keeping the application data.
7454                     */
7455                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7456                            + " reverting from " + ps.codePathString + ": new version "
7457                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7458                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7459                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7460                    synchronized (mInstallLock) {
7461                        args.cleanUpResourcesLI();
7462                    }
7463                }
7464            }
7465        }
7466
7467        // The apk is forward locked (not public) if its code and resources
7468        // are kept in different files. (except for app in either system or
7469        // vendor path).
7470        // TODO grab this value from PackageSettings
7471        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7472            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7473                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7474            }
7475        }
7476
7477        // TODO: extend to support forward-locked splits
7478        String resourcePath = null;
7479        String baseResourcePath = null;
7480        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7481            if (ps != null && ps.resourcePathString != null) {
7482                resourcePath = ps.resourcePathString;
7483                baseResourcePath = ps.resourcePathString;
7484            } else {
7485                // Should not happen at all. Just log an error.
7486                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7487            }
7488        } else {
7489            resourcePath = pkg.codePath;
7490            baseResourcePath = pkg.baseCodePath;
7491        }
7492
7493        // Set application objects path explicitly.
7494        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7495        pkg.setApplicationInfoCodePath(pkg.codePath);
7496        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7497        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7498        pkg.setApplicationInfoResourcePath(resourcePath);
7499        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7500        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7501
7502        // Note that we invoke the following method only if we are about to unpack an application
7503        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7504                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7505
7506        /*
7507         * If the system app should be overridden by a previously installed
7508         * data, hide the system app now and let the /data/app scan pick it up
7509         * again.
7510         */
7511        if (shouldHideSystemApp) {
7512            synchronized (mPackages) {
7513                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7514            }
7515        }
7516
7517        return scannedPkg;
7518    }
7519
7520    private static String fixProcessName(String defProcessName,
7521            String processName) {
7522        if (processName == null) {
7523            return defProcessName;
7524        }
7525        return processName;
7526    }
7527
7528    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7529            throws PackageManagerException {
7530        if (pkgSetting.signatures.mSignatures != null) {
7531            // Already existing package. Make sure signatures match
7532            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7533                    == PackageManager.SIGNATURE_MATCH;
7534            if (!match) {
7535                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7536                        == PackageManager.SIGNATURE_MATCH;
7537            }
7538            if (!match) {
7539                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7540                        == PackageManager.SIGNATURE_MATCH;
7541            }
7542            if (!match) {
7543                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7544                        + pkg.packageName + " signatures do not match the "
7545                        + "previously installed version; ignoring!");
7546            }
7547        }
7548
7549        // Check for shared user signatures
7550        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7551            // Already existing package. Make sure signatures match
7552            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7553                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7554            if (!match) {
7555                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7556                        == PackageManager.SIGNATURE_MATCH;
7557            }
7558            if (!match) {
7559                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7560                        == PackageManager.SIGNATURE_MATCH;
7561            }
7562            if (!match) {
7563                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7564                        "Package " + pkg.packageName
7565                        + " has no signatures that match those in shared user "
7566                        + pkgSetting.sharedUser.name + "; ignoring!");
7567            }
7568        }
7569    }
7570
7571    /**
7572     * Enforces that only the system UID or root's UID can call a method exposed
7573     * via Binder.
7574     *
7575     * @param message used as message if SecurityException is thrown
7576     * @throws SecurityException if the caller is not system or root
7577     */
7578    private static final void enforceSystemOrRoot(String message) {
7579        final int uid = Binder.getCallingUid();
7580        if (uid != Process.SYSTEM_UID && uid != 0) {
7581            throw new SecurityException(message);
7582        }
7583    }
7584
7585    @Override
7586    public void performFstrimIfNeeded() {
7587        enforceSystemOrRoot("Only the system can request fstrim");
7588
7589        // Before everything else, see whether we need to fstrim.
7590        try {
7591            IStorageManager sm = PackageHelper.getStorageManager();
7592            if (sm != null) {
7593                boolean doTrim = false;
7594                final long interval = android.provider.Settings.Global.getLong(
7595                        mContext.getContentResolver(),
7596                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7597                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7598                if (interval > 0) {
7599                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7600                    if (timeSinceLast > interval) {
7601                        doTrim = true;
7602                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7603                                + "; running immediately");
7604                    }
7605                }
7606                if (doTrim) {
7607                    final boolean dexOptDialogShown;
7608                    synchronized (mPackages) {
7609                        dexOptDialogShown = mDexOptDialogShown;
7610                    }
7611                    if (!isFirstBoot() && dexOptDialogShown) {
7612                        try {
7613                            ActivityManager.getService().showBootMessage(
7614                                    mContext.getResources().getString(
7615                                            R.string.android_upgrading_fstrim), true);
7616                        } catch (RemoteException e) {
7617                        }
7618                    }
7619                    sm.runMaintenance();
7620                }
7621            } else {
7622                Slog.e(TAG, "storageManager service unavailable!");
7623            }
7624        } catch (RemoteException e) {
7625            // Can't happen; StorageManagerService is local
7626        }
7627    }
7628
7629    @Override
7630    public void updatePackagesIfNeeded() {
7631        enforceSystemOrRoot("Only the system can request package update");
7632
7633        // We need to re-extract after an OTA.
7634        boolean causeUpgrade = isUpgrade();
7635
7636        // First boot or factory reset.
7637        // Note: we also handle devices that are upgrading to N right now as if it is their
7638        //       first boot, as they do not have profile data.
7639        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7640
7641        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7642        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7643
7644        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7645            return;
7646        }
7647
7648        List<PackageParser.Package> pkgs;
7649        synchronized (mPackages) {
7650            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7651        }
7652
7653        final long startTime = System.nanoTime();
7654        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7655                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7656
7657        final int elapsedTimeSeconds =
7658                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7659
7660        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7661        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7662        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7663        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7664        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7665    }
7666
7667    /**
7668     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7669     * containing statistics about the invocation. The array consists of three elements,
7670     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7671     * and {@code numberOfPackagesFailed}.
7672     */
7673    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7674            String compilerFilter) {
7675
7676        int numberOfPackagesVisited = 0;
7677        int numberOfPackagesOptimized = 0;
7678        int numberOfPackagesSkipped = 0;
7679        int numberOfPackagesFailed = 0;
7680        final int numberOfPackagesToDexopt = pkgs.size();
7681
7682        for (PackageParser.Package pkg : pkgs) {
7683            numberOfPackagesVisited++;
7684
7685            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7686                if (DEBUG_DEXOPT) {
7687                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7688                }
7689                numberOfPackagesSkipped++;
7690                continue;
7691            }
7692
7693            if (DEBUG_DEXOPT) {
7694                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7695                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7696            }
7697
7698            if (showDialog) {
7699                try {
7700                    ActivityManager.getService().showBootMessage(
7701                            mContext.getResources().getString(R.string.android_upgrading_apk,
7702                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7703                } catch (RemoteException e) {
7704                }
7705                synchronized (mPackages) {
7706                    mDexOptDialogShown = true;
7707                }
7708            }
7709
7710            // If the OTA updates a system app which was previously preopted to a non-preopted state
7711            // the app might end up being verified at runtime. That's because by default the apps
7712            // are verify-profile but for preopted apps there's no profile.
7713            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7714            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7715            // filter (by default interpret-only).
7716            // Note that at this stage unused apps are already filtered.
7717            if (isSystemApp(pkg) &&
7718                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7719                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7720                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7721            }
7722
7723            // checkProfiles is false to avoid merging profiles during boot which
7724            // might interfere with background compilation (b/28612421).
7725            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7726            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7727            // trade-off worth doing to save boot time work.
7728            int dexOptStatus = performDexOptTraced(pkg.packageName,
7729                    false /* checkProfiles */,
7730                    compilerFilter,
7731                    false /* force */);
7732            switch (dexOptStatus) {
7733                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7734                    numberOfPackagesOptimized++;
7735                    break;
7736                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7737                    numberOfPackagesSkipped++;
7738                    break;
7739                case PackageDexOptimizer.DEX_OPT_FAILED:
7740                    numberOfPackagesFailed++;
7741                    break;
7742                default:
7743                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7744                    break;
7745            }
7746        }
7747
7748        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7749                numberOfPackagesFailed };
7750    }
7751
7752    @Override
7753    public void notifyPackageUse(String packageName, int reason) {
7754        synchronized (mPackages) {
7755            PackageParser.Package p = mPackages.get(packageName);
7756            if (p == null) {
7757                return;
7758            }
7759            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7760        }
7761    }
7762
7763    @Override
7764    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7765        int userId = UserHandle.getCallingUserId();
7766        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7767        if (ai == null) {
7768            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7769                + loadingPackageName + ", user=" + userId);
7770            return;
7771        }
7772        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7773    }
7774
7775    // TODO: this is not used nor needed. Delete it.
7776    @Override
7777    public boolean performDexOptIfNeeded(String packageName) {
7778        int dexOptStatus = performDexOptTraced(packageName,
7779                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7780        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7781    }
7782
7783    @Override
7784    public boolean performDexOpt(String packageName,
7785            boolean checkProfiles, int compileReason, boolean force) {
7786        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7787                getCompilerFilterForReason(compileReason), force);
7788        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7789    }
7790
7791    @Override
7792    public boolean performDexOptMode(String packageName,
7793            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7794        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7795                targetCompilerFilter, force);
7796        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7797    }
7798
7799    private int performDexOptTraced(String packageName,
7800                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7802        try {
7803            return performDexOptInternal(packageName, checkProfiles,
7804                    targetCompilerFilter, force);
7805        } finally {
7806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7807        }
7808    }
7809
7810    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7811    // if the package can now be considered up to date for the given filter.
7812    private int performDexOptInternal(String packageName,
7813                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7814        PackageParser.Package p;
7815        synchronized (mPackages) {
7816            p = mPackages.get(packageName);
7817            if (p == null) {
7818                // Package could not be found. Report failure.
7819                return PackageDexOptimizer.DEX_OPT_FAILED;
7820            }
7821            mPackageUsage.maybeWriteAsync(mPackages);
7822            mCompilerStats.maybeWriteAsync();
7823        }
7824        long callingId = Binder.clearCallingIdentity();
7825        try {
7826            synchronized (mInstallLock) {
7827                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7828                        targetCompilerFilter, force);
7829            }
7830        } finally {
7831            Binder.restoreCallingIdentity(callingId);
7832        }
7833    }
7834
7835    public ArraySet<String> getOptimizablePackages() {
7836        ArraySet<String> pkgs = new ArraySet<String>();
7837        synchronized (mPackages) {
7838            for (PackageParser.Package p : mPackages.values()) {
7839                if (PackageDexOptimizer.canOptimizePackage(p)) {
7840                    pkgs.add(p.packageName);
7841                }
7842            }
7843        }
7844        return pkgs;
7845    }
7846
7847    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7848            boolean checkProfiles, String targetCompilerFilter,
7849            boolean force) {
7850        // Select the dex optimizer based on the force parameter.
7851        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7852        //       allocate an object here.
7853        PackageDexOptimizer pdo = force
7854                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7855                : mPackageDexOptimizer;
7856
7857        // Optimize all dependencies first. Note: we ignore the return value and march on
7858        // on errors.
7859        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7860        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7861        if (!deps.isEmpty()) {
7862            for (PackageParser.Package depPackage : deps) {
7863                // TODO: Analyze and investigate if we (should) profile libraries.
7864                // Currently this will do a full compilation of the library by default.
7865                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7866                        false /* checkProfiles */,
7867                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7868                        getOrCreateCompilerPackageStats(depPackage));
7869            }
7870        }
7871        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7872                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7873    }
7874
7875    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7876        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7877            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7878            Set<String> collectedNames = new HashSet<>();
7879            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7880
7881            retValue.remove(p);
7882
7883            return retValue;
7884        } else {
7885            return Collections.emptyList();
7886        }
7887    }
7888
7889    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7890            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7891        if (!collectedNames.contains(p.packageName)) {
7892            collectedNames.add(p.packageName);
7893            collected.add(p);
7894
7895            if (p.usesLibraries != null) {
7896                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7897            }
7898            if (p.usesOptionalLibraries != null) {
7899                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7900                        collectedNames);
7901            }
7902        }
7903    }
7904
7905    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7906            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7907        for (String libName : libs) {
7908            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7909            if (libPkg != null) {
7910                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7911            }
7912        }
7913    }
7914
7915    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7916        synchronized (mPackages) {
7917            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7918            if (lib != null && lib.apk != null) {
7919                return mPackages.get(lib.apk);
7920            }
7921        }
7922        return null;
7923    }
7924
7925    public void shutdown() {
7926        mPackageUsage.writeNow(mPackages);
7927        mCompilerStats.writeNow();
7928    }
7929
7930    @Override
7931    public void dumpProfiles(String packageName) {
7932        PackageParser.Package pkg;
7933        synchronized (mPackages) {
7934            pkg = mPackages.get(packageName);
7935            if (pkg == null) {
7936                throw new IllegalArgumentException("Unknown package: " + packageName);
7937            }
7938        }
7939        /* Only the shell, root, or the app user should be able to dump profiles. */
7940        int callingUid = Binder.getCallingUid();
7941        if (callingUid != Process.SHELL_UID &&
7942            callingUid != Process.ROOT_UID &&
7943            callingUid != pkg.applicationInfo.uid) {
7944            throw new SecurityException("dumpProfiles");
7945        }
7946
7947        synchronized (mInstallLock) {
7948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7949            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7950            try {
7951                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7952                String codePaths = TextUtils.join(";", allCodePaths);
7953                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7954            } catch (InstallerException e) {
7955                Slog.w(TAG, "Failed to dump profiles", e);
7956            }
7957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7958        }
7959    }
7960
7961    @Override
7962    public void forceDexOpt(String packageName) {
7963        enforceSystemOrRoot("forceDexOpt");
7964
7965        PackageParser.Package pkg;
7966        synchronized (mPackages) {
7967            pkg = mPackages.get(packageName);
7968            if (pkg == null) {
7969                throw new IllegalArgumentException("Unknown package: " + packageName);
7970            }
7971        }
7972
7973        synchronized (mInstallLock) {
7974            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7975
7976            // Whoever is calling forceDexOpt wants a fully compiled package.
7977            // Don't use profiles since that may cause compilation to be skipped.
7978            final int res = performDexOptInternalWithDependenciesLI(pkg,
7979                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7980                    true /* force */);
7981
7982            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7983            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7984                throw new IllegalStateException("Failed to dexopt: " + res);
7985            }
7986        }
7987    }
7988
7989    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7990        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7991            Slog.w(TAG, "Unable to update from " + oldPkg.name
7992                    + " to " + newPkg.packageName
7993                    + ": old package not in system partition");
7994            return false;
7995        } else if (mPackages.get(oldPkg.name) != null) {
7996            Slog.w(TAG, "Unable to update from " + oldPkg.name
7997                    + " to " + newPkg.packageName
7998                    + ": old package still exists");
7999            return false;
8000        }
8001        return true;
8002    }
8003
8004    void removeCodePathLI(File codePath) {
8005        if (codePath.isDirectory()) {
8006            try {
8007                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8008            } catch (InstallerException e) {
8009                Slog.w(TAG, "Failed to remove code path", e);
8010            }
8011        } else {
8012            codePath.delete();
8013        }
8014    }
8015
8016    private int[] resolveUserIds(int userId) {
8017        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8018    }
8019
8020    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8021        if (pkg == null) {
8022            Slog.wtf(TAG, "Package was null!", new Throwable());
8023            return;
8024        }
8025        clearAppDataLeafLIF(pkg, userId, flags);
8026        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8027        for (int i = 0; i < childCount; i++) {
8028            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8029        }
8030    }
8031
8032    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8033        final PackageSetting ps;
8034        synchronized (mPackages) {
8035            ps = mSettings.mPackages.get(pkg.packageName);
8036        }
8037        for (int realUserId : resolveUserIds(userId)) {
8038            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8039            try {
8040                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8041                        ceDataInode);
8042            } catch (InstallerException e) {
8043                Slog.w(TAG, String.valueOf(e));
8044            }
8045        }
8046    }
8047
8048    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8049        if (pkg == null) {
8050            Slog.wtf(TAG, "Package was null!", new Throwable());
8051            return;
8052        }
8053        destroyAppDataLeafLIF(pkg, userId, flags);
8054        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8055        for (int i = 0; i < childCount; i++) {
8056            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8057        }
8058    }
8059
8060    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8061        final PackageSetting ps;
8062        synchronized (mPackages) {
8063            ps = mSettings.mPackages.get(pkg.packageName);
8064        }
8065        for (int realUserId : resolveUserIds(userId)) {
8066            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8067            try {
8068                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8069                        ceDataInode);
8070            } catch (InstallerException e) {
8071                Slog.w(TAG, String.valueOf(e));
8072            }
8073        }
8074    }
8075
8076    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8077        if (pkg == null) {
8078            Slog.wtf(TAG, "Package was null!", new Throwable());
8079            return;
8080        }
8081        destroyAppProfilesLeafLIF(pkg);
8082        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8083        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8084        for (int i = 0; i < childCount; i++) {
8085            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8086            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8087                    true /* removeBaseMarker */);
8088        }
8089    }
8090
8091    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8092            boolean removeBaseMarker) {
8093        if (pkg.isForwardLocked()) {
8094            return;
8095        }
8096
8097        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8098            try {
8099                path = PackageManagerServiceUtils.realpath(new File(path));
8100            } catch (IOException e) {
8101                // TODO: Should we return early here ?
8102                Slog.w(TAG, "Failed to get canonical path", e);
8103                continue;
8104            }
8105
8106            final String useMarker = path.replace('/', '@');
8107            for (int realUserId : resolveUserIds(userId)) {
8108                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8109                if (removeBaseMarker) {
8110                    File foreignUseMark = new File(profileDir, useMarker);
8111                    if (foreignUseMark.exists()) {
8112                        if (!foreignUseMark.delete()) {
8113                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8114                                    + pkg.packageName);
8115                        }
8116                    }
8117                }
8118
8119                File[] markers = profileDir.listFiles();
8120                if (markers != null) {
8121                    final String searchString = "@" + pkg.packageName + "@";
8122                    // We also delete all markers that contain the package name we're
8123                    // uninstalling. These are associated with secondary dex-files belonging
8124                    // to the package. Reconstructing the path of these dex files is messy
8125                    // in general.
8126                    for (File marker : markers) {
8127                        if (marker.getName().indexOf(searchString) > 0) {
8128                            if (!marker.delete()) {
8129                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8130                                    + pkg.packageName);
8131                            }
8132                        }
8133                    }
8134                }
8135            }
8136        }
8137    }
8138
8139    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8140        try {
8141            mInstaller.destroyAppProfiles(pkg.packageName);
8142        } catch (InstallerException e) {
8143            Slog.w(TAG, String.valueOf(e));
8144        }
8145    }
8146
8147    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8148        if (pkg == null) {
8149            Slog.wtf(TAG, "Package was null!", new Throwable());
8150            return;
8151        }
8152        clearAppProfilesLeafLIF(pkg);
8153        // We don't remove the base foreign use marker when clearing profiles because
8154        // we will rename it when the app is updated. Unlike the actual profile contents,
8155        // the foreign use marker is good across installs.
8156        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8157        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8158        for (int i = 0; i < childCount; i++) {
8159            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8160        }
8161    }
8162
8163    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8164        try {
8165            mInstaller.clearAppProfiles(pkg.packageName);
8166        } catch (InstallerException e) {
8167            Slog.w(TAG, String.valueOf(e));
8168        }
8169    }
8170
8171    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8172            long lastUpdateTime) {
8173        // Set parent install/update time
8174        PackageSetting ps = (PackageSetting) pkg.mExtras;
8175        if (ps != null) {
8176            ps.firstInstallTime = firstInstallTime;
8177            ps.lastUpdateTime = lastUpdateTime;
8178        }
8179        // Set children install/update time
8180        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8181        for (int i = 0; i < childCount; i++) {
8182            PackageParser.Package childPkg = pkg.childPackages.get(i);
8183            ps = (PackageSetting) childPkg.mExtras;
8184            if (ps != null) {
8185                ps.firstInstallTime = firstInstallTime;
8186                ps.lastUpdateTime = lastUpdateTime;
8187            }
8188        }
8189    }
8190
8191    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8192            PackageParser.Package changingLib) {
8193        if (file.path != null) {
8194            usesLibraryFiles.add(file.path);
8195            return;
8196        }
8197        PackageParser.Package p = mPackages.get(file.apk);
8198        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8199            // If we are doing this while in the middle of updating a library apk,
8200            // then we need to make sure to use that new apk for determining the
8201            // dependencies here.  (We haven't yet finished committing the new apk
8202            // to the package manager state.)
8203            if (p == null || p.packageName.equals(changingLib.packageName)) {
8204                p = changingLib;
8205            }
8206        }
8207        if (p != null) {
8208            usesLibraryFiles.addAll(p.getAllCodePaths());
8209        }
8210    }
8211
8212    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8213            PackageParser.Package changingLib) throws PackageManagerException {
8214        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8215            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8216            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8217            for (int i=0; i<N; i++) {
8218                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8219                if (file == null) {
8220                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8221                            "Package " + pkg.packageName + " requires unavailable shared library "
8222                            + pkg.usesLibraries.get(i) + "; failing!");
8223                }
8224                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8225            }
8226            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8227            for (int i=0; i<N; i++) {
8228                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8229                if (file == null) {
8230                    Slog.w(TAG, "Package " + pkg.packageName
8231                            + " desires unavailable shared library "
8232                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8233                } else {
8234                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8235                }
8236            }
8237            N = usesLibraryFiles.size();
8238            if (N > 0) {
8239                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8240            } else {
8241                pkg.usesLibraryFiles = null;
8242            }
8243        }
8244    }
8245
8246    private static boolean hasString(List<String> list, List<String> which) {
8247        if (list == null) {
8248            return false;
8249        }
8250        for (int i=list.size()-1; i>=0; i--) {
8251            for (int j=which.size()-1; j>=0; j--) {
8252                if (which.get(j).equals(list.get(i))) {
8253                    return true;
8254                }
8255            }
8256        }
8257        return false;
8258    }
8259
8260    private void updateAllSharedLibrariesLPw() {
8261        for (PackageParser.Package pkg : mPackages.values()) {
8262            try {
8263                updateSharedLibrariesLPr(pkg, null);
8264            } catch (PackageManagerException e) {
8265                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8266            }
8267        }
8268    }
8269
8270    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8271            PackageParser.Package changingPkg) {
8272        ArrayList<PackageParser.Package> res = null;
8273        for (PackageParser.Package pkg : mPackages.values()) {
8274            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8275                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8276                if (res == null) {
8277                    res = new ArrayList<PackageParser.Package>();
8278                }
8279                res.add(pkg);
8280                try {
8281                    updateSharedLibrariesLPr(pkg, changingPkg);
8282                } catch (PackageManagerException e) {
8283                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8284                }
8285            }
8286        }
8287        return res;
8288    }
8289
8290    /**
8291     * Derive the value of the {@code cpuAbiOverride} based on the provided
8292     * value and an optional stored value from the package settings.
8293     */
8294    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8295        String cpuAbiOverride = null;
8296
8297        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8298            cpuAbiOverride = null;
8299        } else if (abiOverride != null) {
8300            cpuAbiOverride = abiOverride;
8301        } else if (settings != null) {
8302            cpuAbiOverride = settings.cpuAbiOverrideString;
8303        }
8304
8305        return cpuAbiOverride;
8306    }
8307
8308    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8309            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8310                    throws PackageManagerException {
8311        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8312        // If the package has children and this is the first dive in the function
8313        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8314        // whether all packages (parent and children) would be successfully scanned
8315        // before the actual scan since scanning mutates internal state and we want
8316        // to atomically install the package and its children.
8317        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8318            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8319                scanFlags |= SCAN_CHECK_ONLY;
8320            }
8321        } else {
8322            scanFlags &= ~SCAN_CHECK_ONLY;
8323        }
8324
8325        final PackageParser.Package scannedPkg;
8326        try {
8327            // Scan the parent
8328            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8329            // Scan the children
8330            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8331            for (int i = 0; i < childCount; i++) {
8332                PackageParser.Package childPkg = pkg.childPackages.get(i);
8333                scanPackageLI(childPkg, policyFlags,
8334                        scanFlags, currentTime, user);
8335            }
8336        } finally {
8337            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8338        }
8339
8340        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8341            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8342        }
8343
8344        return scannedPkg;
8345    }
8346
8347    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8348            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8349        boolean success = false;
8350        try {
8351            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8352                    currentTime, user);
8353            success = true;
8354            return res;
8355        } finally {
8356            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8357                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8358                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8359                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8360                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8361            }
8362        }
8363    }
8364
8365    /**
8366     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8367     */
8368    private static boolean apkHasCode(String fileName) {
8369        StrictJarFile jarFile = null;
8370        try {
8371            jarFile = new StrictJarFile(fileName,
8372                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8373            return jarFile.findEntry("classes.dex") != null;
8374        } catch (IOException ignore) {
8375        } finally {
8376            try {
8377                if (jarFile != null) {
8378                    jarFile.close();
8379                }
8380            } catch (IOException ignore) {}
8381        }
8382        return false;
8383    }
8384
8385    /**
8386     * Enforces code policy for the package. This ensures that if an APK has
8387     * declared hasCode="true" in its manifest that the APK actually contains
8388     * code.
8389     *
8390     * @throws PackageManagerException If bytecode could not be found when it should exist
8391     */
8392    private static void assertCodePolicy(PackageParser.Package pkg)
8393            throws PackageManagerException {
8394        final boolean shouldHaveCode =
8395                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8396        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8397            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8398                    "Package " + pkg.baseCodePath + " code is missing");
8399        }
8400
8401        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8402            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8403                final boolean splitShouldHaveCode =
8404                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8405                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8406                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8407                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8408                }
8409            }
8410        }
8411    }
8412
8413    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8414            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8415                    throws PackageManagerException {
8416        if (DEBUG_PACKAGE_SCANNING) {
8417            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8418                Log.d(TAG, "Scanning package " + pkg.packageName);
8419        }
8420
8421        applyPolicy(pkg, policyFlags);
8422
8423        assertPackageIsValid(pkg, policyFlags, scanFlags);
8424
8425        // Initialize package source and resource directories
8426        final File scanFile = new File(pkg.codePath);
8427        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8428        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8429
8430        SharedUserSetting suid = null;
8431        PackageSetting pkgSetting = null;
8432
8433        // Getting the package setting may have a side-effect, so if we
8434        // are only checking if scan would succeed, stash a copy of the
8435        // old setting to restore at the end.
8436        PackageSetting nonMutatedPs = null;
8437
8438        // We keep references to the derived CPU Abis from settings in oder to reuse
8439        // them in the case where we're not upgrading or booting for the first time.
8440        String primaryCpuAbiFromSettings = null;
8441        String secondaryCpuAbiFromSettings = null;
8442
8443        // writer
8444        synchronized (mPackages) {
8445            if (pkg.mSharedUserId != null) {
8446                // SIDE EFFECTS; may potentially allocate a new shared user
8447                suid = mSettings.getSharedUserLPw(
8448                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8449                if (DEBUG_PACKAGE_SCANNING) {
8450                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8451                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8452                                + "): packages=" + suid.packages);
8453                }
8454            }
8455
8456            // Check if we are renaming from an original package name.
8457            PackageSetting origPackage = null;
8458            String realName = null;
8459            if (pkg.mOriginalPackages != null) {
8460                // This package may need to be renamed to a previously
8461                // installed name.  Let's check on that...
8462                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8463                if (pkg.mOriginalPackages.contains(renamed)) {
8464                    // This package had originally been installed as the
8465                    // original name, and we have already taken care of
8466                    // transitioning to the new one.  Just update the new
8467                    // one to continue using the old name.
8468                    realName = pkg.mRealPackage;
8469                    if (!pkg.packageName.equals(renamed)) {
8470                        // Callers into this function may have already taken
8471                        // care of renaming the package; only do it here if
8472                        // it is not already done.
8473                        pkg.setPackageName(renamed);
8474                    }
8475                } else {
8476                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8477                        if ((origPackage = mSettings.getPackageLPr(
8478                                pkg.mOriginalPackages.get(i))) != null) {
8479                            // We do have the package already installed under its
8480                            // original name...  should we use it?
8481                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8482                                // New package is not compatible with original.
8483                                origPackage = null;
8484                                continue;
8485                            } else if (origPackage.sharedUser != null) {
8486                                // Make sure uid is compatible between packages.
8487                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8488                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8489                                            + " to " + pkg.packageName + ": old uid "
8490                                            + origPackage.sharedUser.name
8491                                            + " differs from " + pkg.mSharedUserId);
8492                                    origPackage = null;
8493                                    continue;
8494                                }
8495                                // TODO: Add case when shared user id is added [b/28144775]
8496                            } else {
8497                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8498                                        + pkg.packageName + " to old name " + origPackage.name);
8499                            }
8500                            break;
8501                        }
8502                    }
8503                }
8504            }
8505
8506            if (mTransferedPackages.contains(pkg.packageName)) {
8507                Slog.w(TAG, "Package " + pkg.packageName
8508                        + " was transferred to another, but its .apk remains");
8509            }
8510
8511            // See comments in nonMutatedPs declaration
8512            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8513                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8514                if (foundPs != null) {
8515                    nonMutatedPs = new PackageSetting(foundPs);
8516                }
8517            }
8518
8519            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8520                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8521                if (foundPs != null) {
8522                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8523                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8524                }
8525            }
8526
8527            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8528            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8529                PackageManagerService.reportSettingsProblem(Log.WARN,
8530                        "Package " + pkg.packageName + " shared user changed from "
8531                                + (pkgSetting.sharedUser != null
8532                                        ? pkgSetting.sharedUser.name : "<nothing>")
8533                                + " to "
8534                                + (suid != null ? suid.name : "<nothing>")
8535                                + "; replacing with new");
8536                pkgSetting = null;
8537            }
8538            final PackageSetting oldPkgSetting =
8539                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8540            final PackageSetting disabledPkgSetting =
8541                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8542            if (pkgSetting == null) {
8543                final String parentPackageName = (pkg.parentPackage != null)
8544                        ? pkg.parentPackage.packageName : null;
8545                // REMOVE SharedUserSetting from method; update in a separate call
8546                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8547                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8548                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8549                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8550                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8551                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8552                        UserManagerService.getInstance());
8553                // SIDE EFFECTS; updates system state; move elsewhere
8554                if (origPackage != null) {
8555                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8556                }
8557                mSettings.addUserToSettingLPw(pkgSetting);
8558            } else {
8559                // REMOVE SharedUserSetting from method; update in a separate call.
8560                //
8561                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8562                // secondaryCpuAbi are not known at this point so we always update them
8563                // to null here, only to reset them at a later point.
8564                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8565                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8566                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8567                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8568                        UserManagerService.getInstance());
8569            }
8570            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8571            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8572
8573            // SIDE EFFECTS; modifies system state; move elsewhere
8574            if (pkgSetting.origPackage != null) {
8575                // If we are first transitioning from an original package,
8576                // fix up the new package's name now.  We need to do this after
8577                // looking up the package under its new name, so getPackageLP
8578                // can take care of fiddling things correctly.
8579                pkg.setPackageName(origPackage.name);
8580
8581                // File a report about this.
8582                String msg = "New package " + pkgSetting.realName
8583                        + " renamed to replace old package " + pkgSetting.name;
8584                reportSettingsProblem(Log.WARN, msg);
8585
8586                // Make a note of it.
8587                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8588                    mTransferedPackages.add(origPackage.name);
8589                }
8590
8591                // No longer need to retain this.
8592                pkgSetting.origPackage = null;
8593            }
8594
8595            // SIDE EFFECTS; modifies system state; move elsewhere
8596            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8597                // Make a note of it.
8598                mTransferedPackages.add(pkg.packageName);
8599            }
8600
8601            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8602                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8603            }
8604
8605            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8606                // Check all shared libraries and map to their actual file path.
8607                // We only do this here for apps not on a system dir, because those
8608                // are the only ones that can fail an install due to this.  We
8609                // will take care of the system apps by updating all of their
8610                // library paths after the scan is done.
8611                updateSharedLibrariesLPr(pkg, null);
8612            }
8613
8614            if (mFoundPolicyFile) {
8615                SELinuxMMAC.assignSeinfoValue(pkg);
8616            }
8617
8618            pkg.applicationInfo.uid = pkgSetting.appId;
8619            pkg.mExtras = pkgSetting;
8620            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8621                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8622                    // We just determined the app is signed correctly, so bring
8623                    // over the latest parsed certs.
8624                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8625                } else {
8626                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8627                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8628                                "Package " + pkg.packageName + " upgrade keys do not match the "
8629                                + "previously installed version");
8630                    } else {
8631                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8632                        String msg = "System package " + pkg.packageName
8633                                + " signature changed; retaining data.";
8634                        reportSettingsProblem(Log.WARN, msg);
8635                    }
8636                }
8637            } else {
8638                try {
8639                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8640                    verifySignaturesLP(pkgSetting, pkg);
8641                    // We just determined the app is signed correctly, so bring
8642                    // over the latest parsed certs.
8643                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8644                } catch (PackageManagerException e) {
8645                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8646                        throw e;
8647                    }
8648                    // The signature has changed, but this package is in the system
8649                    // image...  let's recover!
8650                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8651                    // However...  if this package is part of a shared user, but it
8652                    // doesn't match the signature of the shared user, let's fail.
8653                    // What this means is that you can't change the signatures
8654                    // associated with an overall shared user, which doesn't seem all
8655                    // that unreasonable.
8656                    if (pkgSetting.sharedUser != null) {
8657                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8658                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8659                            throw new PackageManagerException(
8660                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8661                                    "Signature mismatch for shared user: "
8662                                            + pkgSetting.sharedUser);
8663                        }
8664                    }
8665                    // File a report about this.
8666                    String msg = "System package " + pkg.packageName
8667                            + " signature changed; retaining data.";
8668                    reportSettingsProblem(Log.WARN, msg);
8669                }
8670            }
8671
8672            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8673                // This package wants to adopt ownership of permissions from
8674                // another package.
8675                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8676                    final String origName = pkg.mAdoptPermissions.get(i);
8677                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8678                    if (orig != null) {
8679                        if (verifyPackageUpdateLPr(orig, pkg)) {
8680                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8681                                    + pkg.packageName);
8682                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8683                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8684                        }
8685                    }
8686                }
8687            }
8688        }
8689
8690        pkg.applicationInfo.processName = fixProcessName(
8691                pkg.applicationInfo.packageName,
8692                pkg.applicationInfo.processName);
8693
8694        if (pkg != mPlatformPackage) {
8695            // Get all of our default paths setup
8696            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8697        }
8698
8699        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8700
8701        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8702            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8703                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8704                derivePackageAbi(
8705                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8706                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8707
8708                // Some system apps still use directory structure for native libraries
8709                // in which case we might end up not detecting abi solely based on apk
8710                // structure. Try to detect abi based on directory structure.
8711                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8712                        pkg.applicationInfo.primaryCpuAbi == null) {
8713                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8714                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8715                }
8716            } else {
8717                // This is not a first boot or an upgrade, don't bother deriving the
8718                // ABI during the scan. Instead, trust the value that was stored in the
8719                // package setting.
8720                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8721                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8722
8723                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8724
8725                if (DEBUG_ABI_SELECTION) {
8726                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8727                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8728                        pkg.applicationInfo.secondaryCpuAbi);
8729                }
8730            }
8731        } else {
8732            if ((scanFlags & SCAN_MOVE) != 0) {
8733                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8734                // but we already have this packages package info in the PackageSetting. We just
8735                // use that and derive the native library path based on the new codepath.
8736                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8737                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8738            }
8739
8740            // Set native library paths again. For moves, the path will be updated based on the
8741            // ABIs we've determined above. For non-moves, the path will be updated based on the
8742            // ABIs we determined during compilation, but the path will depend on the final
8743            // package path (after the rename away from the stage path).
8744            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8745        }
8746
8747        // This is a special case for the "system" package, where the ABI is
8748        // dictated by the zygote configuration (and init.rc). We should keep track
8749        // of this ABI so that we can deal with "normal" applications that run under
8750        // the same UID correctly.
8751        if (mPlatformPackage == pkg) {
8752            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8753                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8754        }
8755
8756        // If there's a mismatch between the abi-override in the package setting
8757        // and the abiOverride specified for the install. Warn about this because we
8758        // would've already compiled the app without taking the package setting into
8759        // account.
8760        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8761            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8762                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8763                        " for package " + pkg.packageName);
8764            }
8765        }
8766
8767        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8768        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8769        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8770
8771        // Copy the derived override back to the parsed package, so that we can
8772        // update the package settings accordingly.
8773        pkg.cpuAbiOverride = cpuAbiOverride;
8774
8775        if (DEBUG_ABI_SELECTION) {
8776            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8777                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8778                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8779        }
8780
8781        // Push the derived path down into PackageSettings so we know what to
8782        // clean up at uninstall time.
8783        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8784
8785        if (DEBUG_ABI_SELECTION) {
8786            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8787                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8788                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8789        }
8790
8791        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8792        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8793            // We don't do this here during boot because we can do it all
8794            // at once after scanning all existing packages.
8795            //
8796            // We also do this *before* we perform dexopt on this package, so that
8797            // we can avoid redundant dexopts, and also to make sure we've got the
8798            // code and package path correct.
8799            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8800        }
8801
8802        if (mFactoryTest && pkg.requestedPermissions.contains(
8803                android.Manifest.permission.FACTORY_TEST)) {
8804            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8805        }
8806
8807        if (isSystemApp(pkg)) {
8808            pkgSetting.isOrphaned = true;
8809        }
8810
8811        // Take care of first install / last update times.
8812        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8813        if (currentTime != 0) {
8814            if (pkgSetting.firstInstallTime == 0) {
8815                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8816            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8817                pkgSetting.lastUpdateTime = currentTime;
8818            }
8819        } else if (pkgSetting.firstInstallTime == 0) {
8820            // We need *something*.  Take time time stamp of the file.
8821            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8822        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8823            if (scanFileTime != pkgSetting.timeStamp) {
8824                // A package on the system image has changed; consider this
8825                // to be an update.
8826                pkgSetting.lastUpdateTime = scanFileTime;
8827            }
8828        }
8829        pkgSetting.setTimeStamp(scanFileTime);
8830
8831        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8832            if (nonMutatedPs != null) {
8833                synchronized (mPackages) {
8834                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8835                }
8836            }
8837        } else {
8838            // Modify state for the given package setting
8839            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8840                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8841        }
8842        return pkg;
8843    }
8844
8845    /**
8846     * Applies policy to the parsed package based upon the given policy flags.
8847     * Ensures the package is in a good state.
8848     * <p>
8849     * Implementation detail: This method must NOT have any side effect. It would
8850     * ideally be static, but, it requires locks to read system state.
8851     */
8852    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8853        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8854            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8855            if (pkg.applicationInfo.isDirectBootAware()) {
8856                // we're direct boot aware; set for all components
8857                for (PackageParser.Service s : pkg.services) {
8858                    s.info.encryptionAware = s.info.directBootAware = true;
8859                }
8860                for (PackageParser.Provider p : pkg.providers) {
8861                    p.info.encryptionAware = p.info.directBootAware = true;
8862                }
8863                for (PackageParser.Activity a : pkg.activities) {
8864                    a.info.encryptionAware = a.info.directBootAware = true;
8865                }
8866                for (PackageParser.Activity r : pkg.receivers) {
8867                    r.info.encryptionAware = r.info.directBootAware = true;
8868                }
8869            }
8870        } else {
8871            // Only allow system apps to be flagged as core apps.
8872            pkg.coreApp = false;
8873            // clear flags not applicable to regular apps
8874            pkg.applicationInfo.privateFlags &=
8875                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8876            pkg.applicationInfo.privateFlags &=
8877                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8878        }
8879        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8880
8881        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8882            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8883        }
8884
8885        if (!isSystemApp(pkg)) {
8886            // Only system apps can use these features.
8887            pkg.mOriginalPackages = null;
8888            pkg.mRealPackage = null;
8889            pkg.mAdoptPermissions = null;
8890        }
8891    }
8892
8893    /**
8894     * Asserts the parsed package is valid according to teh given policy. If the
8895     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8896     * <p>
8897     * Implementation detail: This method must NOT have any side effects. It would
8898     * ideally be static, but, it requires locks to read system state.
8899     *
8900     * @throws PackageManagerException If the package fails any of the validation checks
8901     */
8902    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8903            throws PackageManagerException {
8904        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8905            assertCodePolicy(pkg);
8906        }
8907
8908        if (pkg.applicationInfo.getCodePath() == null ||
8909                pkg.applicationInfo.getResourcePath() == null) {
8910            // Bail out. The resource and code paths haven't been set.
8911            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8912                    "Code and resource paths haven't been set correctly");
8913        }
8914
8915        // Make sure we're not adding any bogus keyset info
8916        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8917        ksms.assertScannedPackageValid(pkg);
8918
8919        synchronized (mPackages) {
8920            // The special "android" package can only be defined once
8921            if (pkg.packageName.equals("android")) {
8922                if (mAndroidApplication != null) {
8923                    Slog.w(TAG, "*************************************************");
8924                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8925                    Slog.w(TAG, " codePath=" + pkg.codePath);
8926                    Slog.w(TAG, "*************************************************");
8927                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8928                            "Core android package being redefined.  Skipping.");
8929                }
8930            }
8931
8932            // A package name must be unique; don't allow duplicates
8933            if (mPackages.containsKey(pkg.packageName)
8934                    || mSharedLibraries.containsKey(pkg.packageName)) {
8935                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8936                        "Application package " + pkg.packageName
8937                        + " already installed.  Skipping duplicate.");
8938            }
8939
8940            // Only privileged apps and updated privileged apps can add child packages.
8941            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8942                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8943                    throw new PackageManagerException("Only privileged apps can add child "
8944                            + "packages. Ignoring package " + pkg.packageName);
8945                }
8946                final int childCount = pkg.childPackages.size();
8947                for (int i = 0; i < childCount; i++) {
8948                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8949                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8950                            childPkg.packageName)) {
8951                        throw new PackageManagerException("Can't override child of "
8952                                + "another disabled app. Ignoring package " + pkg.packageName);
8953                    }
8954                }
8955            }
8956
8957            // If we're only installing presumed-existing packages, require that the
8958            // scanned APK is both already known and at the path previously established
8959            // for it.  Previously unknown packages we pick up normally, but if we have an
8960            // a priori expectation about this package's install presence, enforce it.
8961            // With a singular exception for new system packages. When an OTA contains
8962            // a new system package, we allow the codepath to change from a system location
8963            // to the user-installed location. If we don't allow this change, any newer,
8964            // user-installed version of the application will be ignored.
8965            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8966                if (mExpectingBetter.containsKey(pkg.packageName)) {
8967                    logCriticalInfo(Log.WARN,
8968                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8969                } else {
8970                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8971                    if (known != null) {
8972                        if (DEBUG_PACKAGE_SCANNING) {
8973                            Log.d(TAG, "Examining " + pkg.codePath
8974                                    + " and requiring known paths " + known.codePathString
8975                                    + " & " + known.resourcePathString);
8976                        }
8977                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8978                                || !pkg.applicationInfo.getResourcePath().equals(
8979                                        known.resourcePathString)) {
8980                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8981                                    "Application package " + pkg.packageName
8982                                    + " found at " + pkg.applicationInfo.getCodePath()
8983                                    + " but expected at " + known.codePathString
8984                                    + "; ignoring.");
8985                        }
8986                    }
8987                }
8988            }
8989
8990            // Verify that this new package doesn't have any content providers
8991            // that conflict with existing packages.  Only do this if the
8992            // package isn't already installed, since we don't want to break
8993            // things that are installed.
8994            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8995                final int N = pkg.providers.size();
8996                int i;
8997                for (i=0; i<N; i++) {
8998                    PackageParser.Provider p = pkg.providers.get(i);
8999                    if (p.info.authority != null) {
9000                        String names[] = p.info.authority.split(";");
9001                        for (int j = 0; j < names.length; j++) {
9002                            if (mProvidersByAuthority.containsKey(names[j])) {
9003                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9004                                final String otherPackageName =
9005                                        ((other != null && other.getComponentName() != null) ?
9006                                                other.getComponentName().getPackageName() : "?");
9007                                throw new PackageManagerException(
9008                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9009                                        "Can't install because provider name " + names[j]
9010                                                + " (in package " + pkg.applicationInfo.packageName
9011                                                + ") is already used by " + otherPackageName);
9012                            }
9013                        }
9014                    }
9015                }
9016            }
9017        }
9018    }
9019
9020    /**
9021     * Adds a scanned package to the system. When this method is finished, the package will
9022     * be available for query, resolution, etc...
9023     */
9024    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9025            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9026        final String pkgName = pkg.packageName;
9027        if (mCustomResolverComponentName != null &&
9028                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9029            setUpCustomResolverActivity(pkg);
9030        }
9031
9032        if (pkg.packageName.equals("android")) {
9033            synchronized (mPackages) {
9034                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9035                    // Set up information for our fall-back user intent resolution activity.
9036                    mPlatformPackage = pkg;
9037                    pkg.mVersionCode = mSdkVersion;
9038                    mAndroidApplication = pkg.applicationInfo;
9039
9040                    if (!mResolverReplaced) {
9041                        mResolveActivity.applicationInfo = mAndroidApplication;
9042                        mResolveActivity.name = ResolverActivity.class.getName();
9043                        mResolveActivity.packageName = mAndroidApplication.packageName;
9044                        mResolveActivity.processName = "system:ui";
9045                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9046                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9047                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9048                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9049                        mResolveActivity.exported = true;
9050                        mResolveActivity.enabled = true;
9051                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9052                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9053                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9054                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9055                                | ActivityInfo.CONFIG_ORIENTATION
9056                                | ActivityInfo.CONFIG_KEYBOARD
9057                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9058                        mResolveInfo.activityInfo = mResolveActivity;
9059                        mResolveInfo.priority = 0;
9060                        mResolveInfo.preferredOrder = 0;
9061                        mResolveInfo.match = 0;
9062                        mResolveComponentName = new ComponentName(
9063                                mAndroidApplication.packageName, mResolveActivity.name);
9064                    }
9065                }
9066            }
9067        }
9068
9069        ArrayList<PackageParser.Package> clientLibPkgs = null;
9070        // writer
9071        synchronized (mPackages) {
9072            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9073                // Only system apps can add new shared libraries.
9074                if (pkg.libraryNames != null) {
9075                    for (int i=0; i<pkg.libraryNames.size(); i++) {
9076                        String name = pkg.libraryNames.get(i);
9077                        boolean allowed = false;
9078                        if (pkg.isUpdatedSystemApp()) {
9079                            // New library entries can only be added through the
9080                            // system image.  This is important to get rid of a lot
9081                            // of nasty edge cases: for example if we allowed a non-
9082                            // system update of the app to add a library, then uninstalling
9083                            // the update would make the library go away, and assumptions
9084                            // we made such as through app install filtering would now
9085                            // have allowed apps on the device which aren't compatible
9086                            // with it.  Better to just have the restriction here, be
9087                            // conservative, and create many fewer cases that can negatively
9088                            // impact the user experience.
9089                            final PackageSetting sysPs = mSettings
9090                                    .getDisabledSystemPkgLPr(pkg.packageName);
9091                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9092                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
9093                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9094                                        allowed = true;
9095                                        break;
9096                                    }
9097                                }
9098                            }
9099                        } else {
9100                            allowed = true;
9101                        }
9102                        if (allowed) {
9103                            if (!mSharedLibraries.containsKey(name)) {
9104                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
9105                            } else if (!name.equals(pkg.packageName)) {
9106                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9107                                        + name + " already exists; skipping");
9108                            }
9109                        } else {
9110                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9111                                    + name + " that is not declared on system image; skipping");
9112                        }
9113                    }
9114                    if ((scanFlags & SCAN_BOOTING) == 0) {
9115                        // If we are not booting, we need to update any applications
9116                        // that are clients of our shared library.  If we are booting,
9117                        // this will all be done once the scan is complete.
9118                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9119                    }
9120                }
9121            }
9122        }
9123
9124        if ((scanFlags & SCAN_BOOTING) != 0) {
9125            // No apps can run during boot scan, so they don't need to be frozen
9126        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9127            // Caller asked to not kill app, so it's probably not frozen
9128        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9129            // Caller asked us to ignore frozen check for some reason; they
9130            // probably didn't know the package name
9131        } else {
9132            // We're doing major surgery on this package, so it better be frozen
9133            // right now to keep it from launching
9134            checkPackageFrozen(pkgName);
9135        }
9136
9137        // Also need to kill any apps that are dependent on the library.
9138        if (clientLibPkgs != null) {
9139            for (int i=0; i<clientLibPkgs.size(); i++) {
9140                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9141                killApplication(clientPkg.applicationInfo.packageName,
9142                        clientPkg.applicationInfo.uid, "update lib");
9143            }
9144        }
9145
9146        // writer
9147        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9148
9149        boolean createIdmapFailed = false;
9150        synchronized (mPackages) {
9151            // We don't expect installation to fail beyond this point
9152
9153            if (pkgSetting.pkg != null) {
9154                // Note that |user| might be null during the initial boot scan. If a codePath
9155                // for an app has changed during a boot scan, it's due to an app update that's
9156                // part of the system partition and marker changes must be applied to all users.
9157                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9158                final int[] userIds = resolveUserIds(userId);
9159                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9160            }
9161
9162            // Add the new setting to mSettings
9163            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9164            // Add the new setting to mPackages
9165            mPackages.put(pkg.applicationInfo.packageName, pkg);
9166            // Make sure we don't accidentally delete its data.
9167            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9168            while (iter.hasNext()) {
9169                PackageCleanItem item = iter.next();
9170                if (pkgName.equals(item.packageName)) {
9171                    iter.remove();
9172                }
9173            }
9174
9175            // Add the package's KeySets to the global KeySetManagerService
9176            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9177            ksms.addScannedPackageLPw(pkg);
9178
9179            int N = pkg.providers.size();
9180            StringBuilder r = null;
9181            int i;
9182            for (i=0; i<N; i++) {
9183                PackageParser.Provider p = pkg.providers.get(i);
9184                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9185                        p.info.processName);
9186                mProviders.addProvider(p);
9187                p.syncable = p.info.isSyncable;
9188                if (p.info.authority != null) {
9189                    String names[] = p.info.authority.split(";");
9190                    p.info.authority = null;
9191                    for (int j = 0; j < names.length; j++) {
9192                        if (j == 1 && p.syncable) {
9193                            // We only want the first authority for a provider to possibly be
9194                            // syncable, so if we already added this provider using a different
9195                            // authority clear the syncable flag. We copy the provider before
9196                            // changing it because the mProviders object contains a reference
9197                            // to a provider that we don't want to change.
9198                            // Only do this for the second authority since the resulting provider
9199                            // object can be the same for all future authorities for this provider.
9200                            p = new PackageParser.Provider(p);
9201                            p.syncable = false;
9202                        }
9203                        if (!mProvidersByAuthority.containsKey(names[j])) {
9204                            mProvidersByAuthority.put(names[j], p);
9205                            if (p.info.authority == null) {
9206                                p.info.authority = names[j];
9207                            } else {
9208                                p.info.authority = p.info.authority + ";" + names[j];
9209                            }
9210                            if (DEBUG_PACKAGE_SCANNING) {
9211                                if (chatty)
9212                                    Log.d(TAG, "Registered content provider: " + names[j]
9213                                            + ", className = " + p.info.name + ", isSyncable = "
9214                                            + p.info.isSyncable);
9215                            }
9216                        } else {
9217                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9218                            Slog.w(TAG, "Skipping provider name " + names[j] +
9219                                    " (in package " + pkg.applicationInfo.packageName +
9220                                    "): name already used by "
9221                                    + ((other != null && other.getComponentName() != null)
9222                                            ? other.getComponentName().getPackageName() : "?"));
9223                        }
9224                    }
9225                }
9226                if (chatty) {
9227                    if (r == null) {
9228                        r = new StringBuilder(256);
9229                    } else {
9230                        r.append(' ');
9231                    }
9232                    r.append(p.info.name);
9233                }
9234            }
9235            if (r != null) {
9236                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9237            }
9238
9239            N = pkg.services.size();
9240            r = null;
9241            for (i=0; i<N; i++) {
9242                PackageParser.Service s = pkg.services.get(i);
9243                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9244                        s.info.processName);
9245                mServices.addService(s);
9246                if (chatty) {
9247                    if (r == null) {
9248                        r = new StringBuilder(256);
9249                    } else {
9250                        r.append(' ');
9251                    }
9252                    r.append(s.info.name);
9253                }
9254            }
9255            if (r != null) {
9256                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9257            }
9258
9259            N = pkg.receivers.size();
9260            r = null;
9261            for (i=0; i<N; i++) {
9262                PackageParser.Activity a = pkg.receivers.get(i);
9263                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9264                        a.info.processName);
9265                mReceivers.addActivity(a, "receiver");
9266                if (chatty) {
9267                    if (r == null) {
9268                        r = new StringBuilder(256);
9269                    } else {
9270                        r.append(' ');
9271                    }
9272                    r.append(a.info.name);
9273                }
9274            }
9275            if (r != null) {
9276                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9277            }
9278
9279            N = pkg.activities.size();
9280            r = null;
9281            for (i=0; i<N; i++) {
9282                PackageParser.Activity a = pkg.activities.get(i);
9283                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9284                        a.info.processName);
9285                mActivities.addActivity(a, "activity");
9286                if (chatty) {
9287                    if (r == null) {
9288                        r = new StringBuilder(256);
9289                    } else {
9290                        r.append(' ');
9291                    }
9292                    r.append(a.info.name);
9293                }
9294            }
9295            if (r != null) {
9296                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9297            }
9298
9299            N = pkg.permissionGroups.size();
9300            r = null;
9301            for (i=0; i<N; i++) {
9302                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9303                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9304                final String curPackageName = cur == null ? null : cur.info.packageName;
9305                // Dont allow ephemeral apps to define new permission groups.
9306                if (pkg.applicationInfo.isEphemeralApp()) {
9307                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9308                            + pg.info.packageName
9309                            + " ignored: ephemeral apps cannot define new permission groups.");
9310                    continue;
9311                }
9312                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9313                if (cur == null || isPackageUpdate) {
9314                    mPermissionGroups.put(pg.info.name, pg);
9315                    if (chatty) {
9316                        if (r == null) {
9317                            r = new StringBuilder(256);
9318                        } else {
9319                            r.append(' ');
9320                        }
9321                        if (isPackageUpdate) {
9322                            r.append("UPD:");
9323                        }
9324                        r.append(pg.info.name);
9325                    }
9326                } else {
9327                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9328                            + pg.info.packageName + " ignored: original from "
9329                            + cur.info.packageName);
9330                    if (chatty) {
9331                        if (r == null) {
9332                            r = new StringBuilder(256);
9333                        } else {
9334                            r.append(' ');
9335                        }
9336                        r.append("DUP:");
9337                        r.append(pg.info.name);
9338                    }
9339                }
9340            }
9341            if (r != null) {
9342                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9343            }
9344
9345            N = pkg.permissions.size();
9346            r = null;
9347            for (i=0; i<N; i++) {
9348                PackageParser.Permission p = pkg.permissions.get(i);
9349
9350                // Dont allow ephemeral apps to define new permissions.
9351                if (pkg.applicationInfo.isEphemeralApp()) {
9352                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9353                            + p.info.packageName
9354                            + " ignored: ephemeral apps cannot define new permissions.");
9355                    continue;
9356                }
9357
9358                // Assume by default that we did not install this permission into the system.
9359                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9360
9361                // Now that permission groups have a special meaning, we ignore permission
9362                // groups for legacy apps to prevent unexpected behavior. In particular,
9363                // permissions for one app being granted to someone just becase they happen
9364                // to be in a group defined by another app (before this had no implications).
9365                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9366                    p.group = mPermissionGroups.get(p.info.group);
9367                    // Warn for a permission in an unknown group.
9368                    if (p.info.group != null && p.group == null) {
9369                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9370                                + p.info.packageName + " in an unknown group " + p.info.group);
9371                    }
9372                }
9373
9374                ArrayMap<String, BasePermission> permissionMap =
9375                        p.tree ? mSettings.mPermissionTrees
9376                                : mSettings.mPermissions;
9377                BasePermission bp = permissionMap.get(p.info.name);
9378
9379                // Allow system apps to redefine non-system permissions
9380                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9381                    final boolean currentOwnerIsSystem = (bp.perm != null
9382                            && isSystemApp(bp.perm.owner));
9383                    if (isSystemApp(p.owner)) {
9384                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9385                            // It's a built-in permission and no owner, take ownership now
9386                            bp.packageSetting = pkgSetting;
9387                            bp.perm = p;
9388                            bp.uid = pkg.applicationInfo.uid;
9389                            bp.sourcePackage = p.info.packageName;
9390                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9391                        } else if (!currentOwnerIsSystem) {
9392                            String msg = "New decl " + p.owner + " of permission  "
9393                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9394                            reportSettingsProblem(Log.WARN, msg);
9395                            bp = null;
9396                        }
9397                    }
9398                }
9399
9400                if (bp == null) {
9401                    bp = new BasePermission(p.info.name, p.info.packageName,
9402                            BasePermission.TYPE_NORMAL);
9403                    permissionMap.put(p.info.name, bp);
9404                }
9405
9406                if (bp.perm == null) {
9407                    if (bp.sourcePackage == null
9408                            || bp.sourcePackage.equals(p.info.packageName)) {
9409                        BasePermission tree = findPermissionTreeLP(p.info.name);
9410                        if (tree == null
9411                                || tree.sourcePackage.equals(p.info.packageName)) {
9412                            bp.packageSetting = pkgSetting;
9413                            bp.perm = p;
9414                            bp.uid = pkg.applicationInfo.uid;
9415                            bp.sourcePackage = p.info.packageName;
9416                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9417                            if (chatty) {
9418                                if (r == null) {
9419                                    r = new StringBuilder(256);
9420                                } else {
9421                                    r.append(' ');
9422                                }
9423                                r.append(p.info.name);
9424                            }
9425                        } else {
9426                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9427                                    + p.info.packageName + " ignored: base tree "
9428                                    + tree.name + " is from package "
9429                                    + tree.sourcePackage);
9430                        }
9431                    } else {
9432                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9433                                + p.info.packageName + " ignored: original from "
9434                                + bp.sourcePackage);
9435                    }
9436                } else if (chatty) {
9437                    if (r == null) {
9438                        r = new StringBuilder(256);
9439                    } else {
9440                        r.append(' ');
9441                    }
9442                    r.append("DUP:");
9443                    r.append(p.info.name);
9444                }
9445                if (bp.perm == p) {
9446                    bp.protectionLevel = p.info.protectionLevel;
9447                }
9448            }
9449
9450            if (r != null) {
9451                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9452            }
9453
9454            N = pkg.instrumentation.size();
9455            r = null;
9456            for (i=0; i<N; i++) {
9457                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9458                a.info.packageName = pkg.applicationInfo.packageName;
9459                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9460                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9461                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9462                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9463                a.info.dataDir = pkg.applicationInfo.dataDir;
9464                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9465                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9466                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9467                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9468                mInstrumentation.put(a.getComponentName(), a);
9469                if (chatty) {
9470                    if (r == null) {
9471                        r = new StringBuilder(256);
9472                    } else {
9473                        r.append(' ');
9474                    }
9475                    r.append(a.info.name);
9476                }
9477            }
9478            if (r != null) {
9479                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9480            }
9481
9482            if (pkg.protectedBroadcasts != null) {
9483                N = pkg.protectedBroadcasts.size();
9484                for (i=0; i<N; i++) {
9485                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9486                }
9487            }
9488
9489            // Create idmap files for pairs of (packages, overlay packages).
9490            // Note: "android", ie framework-res.apk, is handled by native layers.
9491            if (pkg.mOverlayTarget != null) {
9492                // This is an overlay package.
9493                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9494                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9495                        mOverlays.put(pkg.mOverlayTarget,
9496                                new ArrayMap<String, PackageParser.Package>());
9497                    }
9498                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9499                    map.put(pkg.packageName, pkg);
9500                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9501                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9502                        createIdmapFailed = true;
9503                    }
9504                }
9505            } else if (mOverlays.containsKey(pkg.packageName) &&
9506                    !pkg.packageName.equals("android")) {
9507                // This is a regular package, with one or more known overlay packages.
9508                createIdmapsForPackageLI(pkg);
9509            }
9510        }
9511
9512        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9513
9514        if (createIdmapFailed) {
9515            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9516                    "scanPackageLI failed to createIdmap");
9517        }
9518    }
9519
9520    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9521            PackageParser.Package update, int[] userIds) {
9522        if (existing.applicationInfo == null || update.applicationInfo == null) {
9523            // This isn't due to an app installation.
9524            return;
9525        }
9526
9527        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9528        final File newCodePath = new File(update.applicationInfo.getCodePath());
9529
9530        // The codePath hasn't changed, so there's nothing for us to do.
9531        if (Objects.equals(oldCodePath, newCodePath)) {
9532            return;
9533        }
9534
9535        File canonicalNewCodePath;
9536        try {
9537            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9538        } catch (IOException e) {
9539            Slog.w(TAG, "Failed to get canonical path.", e);
9540            return;
9541        }
9542
9543        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9544        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9545        // that the last component of the path (i.e, the name) doesn't need canonicalization
9546        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9547        // but may change in the future. Hopefully this function won't exist at that point.
9548        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9549                oldCodePath.getName());
9550
9551        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9552        // with "@".
9553        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9554        if (!oldMarkerPrefix.endsWith("@")) {
9555            oldMarkerPrefix += "@";
9556        }
9557        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9558        if (!newMarkerPrefix.endsWith("@")) {
9559            newMarkerPrefix += "@";
9560        }
9561
9562        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9563        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9564        for (String updatedPath : updatedPaths) {
9565            String updatedPathName = new File(updatedPath).getName();
9566            markerSuffixes.add(updatedPathName.replace('/', '@'));
9567        }
9568
9569        for (int userId : userIds) {
9570            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9571
9572            for (String markerSuffix : markerSuffixes) {
9573                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9574                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9575                if (oldForeignUseMark.exists()) {
9576                    try {
9577                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9578                                newForeignUseMark.getAbsolutePath());
9579                    } catch (ErrnoException e) {
9580                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9581                        oldForeignUseMark.delete();
9582                    }
9583                }
9584            }
9585        }
9586    }
9587
9588    /**
9589     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9590     * is derived purely on the basis of the contents of {@code scanFile} and
9591     * {@code cpuAbiOverride}.
9592     *
9593     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9594     */
9595    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9596                                 String cpuAbiOverride, boolean extractLibs,
9597                                 File appLib32InstallDir)
9598            throws PackageManagerException {
9599        // Give ourselves some initial paths; we'll come back for another
9600        // pass once we've determined ABI below.
9601        setNativeLibraryPaths(pkg, appLib32InstallDir);
9602
9603        // We would never need to extract libs for forward-locked and external packages,
9604        // since the container service will do it for us. We shouldn't attempt to
9605        // extract libs from system app when it was not updated.
9606        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9607                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9608            extractLibs = false;
9609        }
9610
9611        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9612        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9613
9614        NativeLibraryHelper.Handle handle = null;
9615        try {
9616            handle = NativeLibraryHelper.Handle.create(pkg);
9617            // TODO(multiArch): This can be null for apps that didn't go through the
9618            // usual installation process. We can calculate it again, like we
9619            // do during install time.
9620            //
9621            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9622            // unnecessary.
9623            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9624
9625            // Null out the abis so that they can be recalculated.
9626            pkg.applicationInfo.primaryCpuAbi = null;
9627            pkg.applicationInfo.secondaryCpuAbi = null;
9628            if (isMultiArch(pkg.applicationInfo)) {
9629                // Warn if we've set an abiOverride for multi-lib packages..
9630                // By definition, we need to copy both 32 and 64 bit libraries for
9631                // such packages.
9632                if (pkg.cpuAbiOverride != null
9633                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9634                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9635                }
9636
9637                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9638                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9639                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9640                    if (extractLibs) {
9641                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9642                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9643                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9644                                useIsaSpecificSubdirs);
9645                    } else {
9646                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9647                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9648                    }
9649                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9650                }
9651
9652                maybeThrowExceptionForMultiArchCopy(
9653                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9654
9655                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9656                    if (extractLibs) {
9657                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9658                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9659                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9660                                useIsaSpecificSubdirs);
9661                    } else {
9662                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9663                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9664                    }
9665                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9666                }
9667
9668                maybeThrowExceptionForMultiArchCopy(
9669                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9670
9671                if (abi64 >= 0) {
9672                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9673                }
9674
9675                if (abi32 >= 0) {
9676                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9677                    if (abi64 >= 0) {
9678                        if (pkg.use32bitAbi) {
9679                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9680                            pkg.applicationInfo.primaryCpuAbi = abi;
9681                        } else {
9682                            pkg.applicationInfo.secondaryCpuAbi = abi;
9683                        }
9684                    } else {
9685                        pkg.applicationInfo.primaryCpuAbi = abi;
9686                    }
9687                }
9688
9689            } else {
9690                String[] abiList = (cpuAbiOverride != null) ?
9691                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9692
9693                // Enable gross and lame hacks for apps that are built with old
9694                // SDK tools. We must scan their APKs for renderscript bitcode and
9695                // not launch them if it's present. Don't bother checking on devices
9696                // that don't have 64 bit support.
9697                boolean needsRenderScriptOverride = false;
9698                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9699                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9700                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9701                    needsRenderScriptOverride = true;
9702                }
9703
9704                final int copyRet;
9705                if (extractLibs) {
9706                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9707                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9708                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9709                } else {
9710                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9711                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9712                }
9713                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9714
9715                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9716                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9717                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9718                }
9719
9720                if (copyRet >= 0) {
9721                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9722                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9723                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9724                } else if (needsRenderScriptOverride) {
9725                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9726                }
9727            }
9728        } catch (IOException ioe) {
9729            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9730        } finally {
9731            IoUtils.closeQuietly(handle);
9732        }
9733
9734        // Now that we've calculated the ABIs and determined if it's an internal app,
9735        // we will go ahead and populate the nativeLibraryPath.
9736        setNativeLibraryPaths(pkg, appLib32InstallDir);
9737    }
9738
9739    /**
9740     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9741     * i.e, so that all packages can be run inside a single process if required.
9742     *
9743     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9744     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9745     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9746     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9747     * updating a package that belongs to a shared user.
9748     *
9749     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9750     * adds unnecessary complexity.
9751     */
9752    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9753            PackageParser.Package scannedPackage) {
9754        String requiredInstructionSet = null;
9755        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9756            requiredInstructionSet = VMRuntime.getInstructionSet(
9757                     scannedPackage.applicationInfo.primaryCpuAbi);
9758        }
9759
9760        PackageSetting requirer = null;
9761        for (PackageSetting ps : packagesForUser) {
9762            // If packagesForUser contains scannedPackage, we skip it. This will happen
9763            // when scannedPackage is an update of an existing package. Without this check,
9764            // we will never be able to change the ABI of any package belonging to a shared
9765            // user, even if it's compatible with other packages.
9766            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9767                if (ps.primaryCpuAbiString == null) {
9768                    continue;
9769                }
9770
9771                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9772                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9773                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9774                    // this but there's not much we can do.
9775                    String errorMessage = "Instruction set mismatch, "
9776                            + ((requirer == null) ? "[caller]" : requirer)
9777                            + " requires " + requiredInstructionSet + " whereas " + ps
9778                            + " requires " + instructionSet;
9779                    Slog.w(TAG, errorMessage);
9780                }
9781
9782                if (requiredInstructionSet == null) {
9783                    requiredInstructionSet = instructionSet;
9784                    requirer = ps;
9785                }
9786            }
9787        }
9788
9789        if (requiredInstructionSet != null) {
9790            String adjustedAbi;
9791            if (requirer != null) {
9792                // requirer != null implies that either scannedPackage was null or that scannedPackage
9793                // did not require an ABI, in which case we have to adjust scannedPackage to match
9794                // the ABI of the set (which is the same as requirer's ABI)
9795                adjustedAbi = requirer.primaryCpuAbiString;
9796                if (scannedPackage != null) {
9797                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9798                }
9799            } else {
9800                // requirer == null implies that we're updating all ABIs in the set to
9801                // match scannedPackage.
9802                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9803            }
9804
9805            for (PackageSetting ps : packagesForUser) {
9806                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9807                    if (ps.primaryCpuAbiString != null) {
9808                        continue;
9809                    }
9810
9811                    ps.primaryCpuAbiString = adjustedAbi;
9812                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9813                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9814                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9815                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9816                                + " (requirer="
9817                                + (requirer == null ? "null" : requirer.pkg.packageName)
9818                                + ", scannedPackage="
9819                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9820                                + ")");
9821                        try {
9822                            mInstaller.rmdex(ps.codePathString,
9823                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9824                        } catch (InstallerException ignored) {
9825                        }
9826                    }
9827                }
9828            }
9829        }
9830    }
9831
9832    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9833        synchronized (mPackages) {
9834            mResolverReplaced = true;
9835            // Set up information for custom user intent resolution activity.
9836            mResolveActivity.applicationInfo = pkg.applicationInfo;
9837            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9838            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9839            mResolveActivity.processName = pkg.applicationInfo.packageName;
9840            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9841            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9842                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9843            mResolveActivity.theme = 0;
9844            mResolveActivity.exported = true;
9845            mResolveActivity.enabled = true;
9846            mResolveInfo.activityInfo = mResolveActivity;
9847            mResolveInfo.priority = 0;
9848            mResolveInfo.preferredOrder = 0;
9849            mResolveInfo.match = 0;
9850            mResolveComponentName = mCustomResolverComponentName;
9851            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9852                    mResolveComponentName);
9853        }
9854    }
9855
9856    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9857        if (installerComponent == null) {
9858            if (DEBUG_EPHEMERAL) {
9859                Slog.d(TAG, "Clear ephemeral installer activity");
9860            }
9861            mEphemeralInstallerActivity.applicationInfo = null;
9862            return;
9863        }
9864
9865        if (DEBUG_EPHEMERAL) {
9866            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9867        }
9868        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9869        // Set up information for ephemeral installer activity
9870        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9871        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9872        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9873        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9874        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9875        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9876                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9877        mEphemeralInstallerActivity.theme = 0;
9878        mEphemeralInstallerActivity.exported = true;
9879        mEphemeralInstallerActivity.enabled = true;
9880        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9881        mEphemeralInstallerInfo.priority = 0;
9882        mEphemeralInstallerInfo.preferredOrder = 1;
9883        mEphemeralInstallerInfo.isDefault = true;
9884        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9885                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9886    }
9887
9888    private static String calculateBundledApkRoot(final String codePathString) {
9889        final File codePath = new File(codePathString);
9890        final File codeRoot;
9891        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9892            codeRoot = Environment.getRootDirectory();
9893        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9894            codeRoot = Environment.getOemDirectory();
9895        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9896            codeRoot = Environment.getVendorDirectory();
9897        } else {
9898            // Unrecognized code path; take its top real segment as the apk root:
9899            // e.g. /something/app/blah.apk => /something
9900            try {
9901                File f = codePath.getCanonicalFile();
9902                File parent = f.getParentFile();    // non-null because codePath is a file
9903                File tmp;
9904                while ((tmp = parent.getParentFile()) != null) {
9905                    f = parent;
9906                    parent = tmp;
9907                }
9908                codeRoot = f;
9909                Slog.w(TAG, "Unrecognized code path "
9910                        + codePath + " - using " + codeRoot);
9911            } catch (IOException e) {
9912                // Can't canonicalize the code path -- shenanigans?
9913                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9914                return Environment.getRootDirectory().getPath();
9915            }
9916        }
9917        return codeRoot.getPath();
9918    }
9919
9920    /**
9921     * Derive and set the location of native libraries for the given package,
9922     * which varies depending on where and how the package was installed.
9923     */
9924    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9925        final ApplicationInfo info = pkg.applicationInfo;
9926        final String codePath = pkg.codePath;
9927        final File codeFile = new File(codePath);
9928        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9929        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9930
9931        info.nativeLibraryRootDir = null;
9932        info.nativeLibraryRootRequiresIsa = false;
9933        info.nativeLibraryDir = null;
9934        info.secondaryNativeLibraryDir = null;
9935
9936        if (isApkFile(codeFile)) {
9937            // Monolithic install
9938            if (bundledApp) {
9939                // If "/system/lib64/apkname" exists, assume that is the per-package
9940                // native library directory to use; otherwise use "/system/lib/apkname".
9941                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9942                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9943                        getPrimaryInstructionSet(info));
9944
9945                // This is a bundled system app so choose the path based on the ABI.
9946                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9947                // is just the default path.
9948                final String apkName = deriveCodePathName(codePath);
9949                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9950                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9951                        apkName).getAbsolutePath();
9952
9953                if (info.secondaryCpuAbi != null) {
9954                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9955                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9956                            secondaryLibDir, apkName).getAbsolutePath();
9957                }
9958            } else if (asecApp) {
9959                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9960                        .getAbsolutePath();
9961            } else {
9962                final String apkName = deriveCodePathName(codePath);
9963                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9964                        .getAbsolutePath();
9965            }
9966
9967            info.nativeLibraryRootRequiresIsa = false;
9968            info.nativeLibraryDir = info.nativeLibraryRootDir;
9969        } else {
9970            // Cluster install
9971            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9972            info.nativeLibraryRootRequiresIsa = true;
9973
9974            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9975                    getPrimaryInstructionSet(info)).getAbsolutePath();
9976
9977            if (info.secondaryCpuAbi != null) {
9978                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9979                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9980            }
9981        }
9982    }
9983
9984    /**
9985     * Calculate the abis and roots for a bundled app. These can uniquely
9986     * be determined from the contents of the system partition, i.e whether
9987     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9988     * of this information, and instead assume that the system was built
9989     * sensibly.
9990     */
9991    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9992                                           PackageSetting pkgSetting) {
9993        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9994
9995        // If "/system/lib64/apkname" exists, assume that is the per-package
9996        // native library directory to use; otherwise use "/system/lib/apkname".
9997        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9998        setBundledAppAbi(pkg, apkRoot, apkName);
9999        // pkgSetting might be null during rescan following uninstall of updates
10000        // to a bundled app, so accommodate that possibility.  The settings in
10001        // that case will be established later from the parsed package.
10002        //
10003        // If the settings aren't null, sync them up with what we've just derived.
10004        // note that apkRoot isn't stored in the package settings.
10005        if (pkgSetting != null) {
10006            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10007            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10008        }
10009    }
10010
10011    /**
10012     * Deduces the ABI of a bundled app and sets the relevant fields on the
10013     * parsed pkg object.
10014     *
10015     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10016     *        under which system libraries are installed.
10017     * @param apkName the name of the installed package.
10018     */
10019    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10020        final File codeFile = new File(pkg.codePath);
10021
10022        final boolean has64BitLibs;
10023        final boolean has32BitLibs;
10024        if (isApkFile(codeFile)) {
10025            // Monolithic install
10026            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10027            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10028        } else {
10029            // Cluster install
10030            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10031            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10032                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10033                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10034                has64BitLibs = (new File(rootDir, isa)).exists();
10035            } else {
10036                has64BitLibs = false;
10037            }
10038            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10039                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10040                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10041                has32BitLibs = (new File(rootDir, isa)).exists();
10042            } else {
10043                has32BitLibs = false;
10044            }
10045        }
10046
10047        if (has64BitLibs && !has32BitLibs) {
10048            // The package has 64 bit libs, but not 32 bit libs. Its primary
10049            // ABI should be 64 bit. We can safely assume here that the bundled
10050            // native libraries correspond to the most preferred ABI in the list.
10051
10052            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10053            pkg.applicationInfo.secondaryCpuAbi = null;
10054        } else if (has32BitLibs && !has64BitLibs) {
10055            // The package has 32 bit libs but not 64 bit libs. Its primary
10056            // ABI should be 32 bit.
10057
10058            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10059            pkg.applicationInfo.secondaryCpuAbi = null;
10060        } else if (has32BitLibs && has64BitLibs) {
10061            // The application has both 64 and 32 bit bundled libraries. We check
10062            // here that the app declares multiArch support, and warn if it doesn't.
10063            //
10064            // We will be lenient here and record both ABIs. The primary will be the
10065            // ABI that's higher on the list, i.e, a device that's configured to prefer
10066            // 64 bit apps will see a 64 bit primary ABI,
10067
10068            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10069                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10070            }
10071
10072            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10073                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10074                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10075            } else {
10076                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10077                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10078            }
10079        } else {
10080            pkg.applicationInfo.primaryCpuAbi = null;
10081            pkg.applicationInfo.secondaryCpuAbi = null;
10082        }
10083    }
10084
10085    private void killApplication(String pkgName, int appId, String reason) {
10086        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10087    }
10088
10089    private void killApplication(String pkgName, int appId, int userId, String reason) {
10090        // Request the ActivityManager to kill the process(only for existing packages)
10091        // so that we do not end up in a confused state while the user is still using the older
10092        // version of the application while the new one gets installed.
10093        final long token = Binder.clearCallingIdentity();
10094        try {
10095            IActivityManager am = ActivityManager.getService();
10096            if (am != null) {
10097                try {
10098                    am.killApplication(pkgName, appId, userId, reason);
10099                } catch (RemoteException e) {
10100                }
10101            }
10102        } finally {
10103            Binder.restoreCallingIdentity(token);
10104        }
10105    }
10106
10107    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10108        // Remove the parent package setting
10109        PackageSetting ps = (PackageSetting) pkg.mExtras;
10110        if (ps != null) {
10111            removePackageLI(ps, chatty);
10112        }
10113        // Remove the child package setting
10114        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10115        for (int i = 0; i < childCount; i++) {
10116            PackageParser.Package childPkg = pkg.childPackages.get(i);
10117            ps = (PackageSetting) childPkg.mExtras;
10118            if (ps != null) {
10119                removePackageLI(ps, chatty);
10120            }
10121        }
10122    }
10123
10124    void removePackageLI(PackageSetting ps, boolean chatty) {
10125        if (DEBUG_INSTALL) {
10126            if (chatty)
10127                Log.d(TAG, "Removing package " + ps.name);
10128        }
10129
10130        // writer
10131        synchronized (mPackages) {
10132            mPackages.remove(ps.name);
10133            final PackageParser.Package pkg = ps.pkg;
10134            if (pkg != null) {
10135                cleanPackageDataStructuresLILPw(pkg, chatty);
10136            }
10137        }
10138    }
10139
10140    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10141        if (DEBUG_INSTALL) {
10142            if (chatty)
10143                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10144        }
10145
10146        // writer
10147        synchronized (mPackages) {
10148            // Remove the parent package
10149            mPackages.remove(pkg.applicationInfo.packageName);
10150            cleanPackageDataStructuresLILPw(pkg, chatty);
10151
10152            // Remove the child packages
10153            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10154            for (int i = 0; i < childCount; i++) {
10155                PackageParser.Package childPkg = pkg.childPackages.get(i);
10156                mPackages.remove(childPkg.applicationInfo.packageName);
10157                cleanPackageDataStructuresLILPw(childPkg, chatty);
10158            }
10159        }
10160    }
10161
10162    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10163        int N = pkg.providers.size();
10164        StringBuilder r = null;
10165        int i;
10166        for (i=0; i<N; i++) {
10167            PackageParser.Provider p = pkg.providers.get(i);
10168            mProviders.removeProvider(p);
10169            if (p.info.authority == null) {
10170
10171                /* There was another ContentProvider with this authority when
10172                 * this app was installed so this authority is null,
10173                 * Ignore it as we don't have to unregister the provider.
10174                 */
10175                continue;
10176            }
10177            String names[] = p.info.authority.split(";");
10178            for (int j = 0; j < names.length; j++) {
10179                if (mProvidersByAuthority.get(names[j]) == p) {
10180                    mProvidersByAuthority.remove(names[j]);
10181                    if (DEBUG_REMOVE) {
10182                        if (chatty)
10183                            Log.d(TAG, "Unregistered content provider: " + names[j]
10184                                    + ", className = " + p.info.name + ", isSyncable = "
10185                                    + p.info.isSyncable);
10186                    }
10187                }
10188            }
10189            if (DEBUG_REMOVE && chatty) {
10190                if (r == null) {
10191                    r = new StringBuilder(256);
10192                } else {
10193                    r.append(' ');
10194                }
10195                r.append(p.info.name);
10196            }
10197        }
10198        if (r != null) {
10199            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10200        }
10201
10202        N = pkg.services.size();
10203        r = null;
10204        for (i=0; i<N; i++) {
10205            PackageParser.Service s = pkg.services.get(i);
10206            mServices.removeService(s);
10207            if (chatty) {
10208                if (r == null) {
10209                    r = new StringBuilder(256);
10210                } else {
10211                    r.append(' ');
10212                }
10213                r.append(s.info.name);
10214            }
10215        }
10216        if (r != null) {
10217            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10218        }
10219
10220        N = pkg.receivers.size();
10221        r = null;
10222        for (i=0; i<N; i++) {
10223            PackageParser.Activity a = pkg.receivers.get(i);
10224            mReceivers.removeActivity(a, "receiver");
10225            if (DEBUG_REMOVE && chatty) {
10226                if (r == null) {
10227                    r = new StringBuilder(256);
10228                } else {
10229                    r.append(' ');
10230                }
10231                r.append(a.info.name);
10232            }
10233        }
10234        if (r != null) {
10235            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10236        }
10237
10238        N = pkg.activities.size();
10239        r = null;
10240        for (i=0; i<N; i++) {
10241            PackageParser.Activity a = pkg.activities.get(i);
10242            mActivities.removeActivity(a, "activity");
10243            if (DEBUG_REMOVE && chatty) {
10244                if (r == null) {
10245                    r = new StringBuilder(256);
10246                } else {
10247                    r.append(' ');
10248                }
10249                r.append(a.info.name);
10250            }
10251        }
10252        if (r != null) {
10253            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10254        }
10255
10256        N = pkg.permissions.size();
10257        r = null;
10258        for (i=0; i<N; i++) {
10259            PackageParser.Permission p = pkg.permissions.get(i);
10260            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10261            if (bp == null) {
10262                bp = mSettings.mPermissionTrees.get(p.info.name);
10263            }
10264            if (bp != null && bp.perm == p) {
10265                bp.perm = null;
10266                if (DEBUG_REMOVE && chatty) {
10267                    if (r == null) {
10268                        r = new StringBuilder(256);
10269                    } else {
10270                        r.append(' ');
10271                    }
10272                    r.append(p.info.name);
10273                }
10274            }
10275            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10276                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10277                if (appOpPkgs != null) {
10278                    appOpPkgs.remove(pkg.packageName);
10279                }
10280            }
10281        }
10282        if (r != null) {
10283            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10284        }
10285
10286        N = pkg.requestedPermissions.size();
10287        r = null;
10288        for (i=0; i<N; i++) {
10289            String perm = pkg.requestedPermissions.get(i);
10290            BasePermission bp = mSettings.mPermissions.get(perm);
10291            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10292                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10293                if (appOpPkgs != null) {
10294                    appOpPkgs.remove(pkg.packageName);
10295                    if (appOpPkgs.isEmpty()) {
10296                        mAppOpPermissionPackages.remove(perm);
10297                    }
10298                }
10299            }
10300        }
10301        if (r != null) {
10302            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10303        }
10304
10305        N = pkg.instrumentation.size();
10306        r = null;
10307        for (i=0; i<N; i++) {
10308            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10309            mInstrumentation.remove(a.getComponentName());
10310            if (DEBUG_REMOVE && chatty) {
10311                if (r == null) {
10312                    r = new StringBuilder(256);
10313                } else {
10314                    r.append(' ');
10315                }
10316                r.append(a.info.name);
10317            }
10318        }
10319        if (r != null) {
10320            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10321        }
10322
10323        r = null;
10324        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10325            // Only system apps can hold shared libraries.
10326            if (pkg.libraryNames != null) {
10327                for (i=0; i<pkg.libraryNames.size(); i++) {
10328                    String name = pkg.libraryNames.get(i);
10329                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10330                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10331                        mSharedLibraries.remove(name);
10332                        if (DEBUG_REMOVE && chatty) {
10333                            if (r == null) {
10334                                r = new StringBuilder(256);
10335                            } else {
10336                                r.append(' ');
10337                            }
10338                            r.append(name);
10339                        }
10340                    }
10341                }
10342            }
10343        }
10344        if (r != null) {
10345            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10346        }
10347    }
10348
10349    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10350        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10351            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10352                return true;
10353            }
10354        }
10355        return false;
10356    }
10357
10358    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10359    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10360    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10361
10362    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10363        // Update the parent permissions
10364        updatePermissionsLPw(pkg.packageName, pkg, flags);
10365        // Update the child permissions
10366        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10367        for (int i = 0; i < childCount; i++) {
10368            PackageParser.Package childPkg = pkg.childPackages.get(i);
10369            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10370        }
10371    }
10372
10373    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10374            int flags) {
10375        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10376        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10377    }
10378
10379    private void updatePermissionsLPw(String changingPkg,
10380            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10381        // Make sure there are no dangling permission trees.
10382        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10383        while (it.hasNext()) {
10384            final BasePermission bp = it.next();
10385            if (bp.packageSetting == null) {
10386                // We may not yet have parsed the package, so just see if
10387                // we still know about its settings.
10388                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10389            }
10390            if (bp.packageSetting == null) {
10391                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10392                        + " from package " + bp.sourcePackage);
10393                it.remove();
10394            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10395                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10396                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10397                            + " from package " + bp.sourcePackage);
10398                    flags |= UPDATE_PERMISSIONS_ALL;
10399                    it.remove();
10400                }
10401            }
10402        }
10403
10404        // Make sure all dynamic permissions have been assigned to a package,
10405        // and make sure there are no dangling permissions.
10406        it = mSettings.mPermissions.values().iterator();
10407        while (it.hasNext()) {
10408            final BasePermission bp = it.next();
10409            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10410                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10411                        + bp.name + " pkg=" + bp.sourcePackage
10412                        + " info=" + bp.pendingInfo);
10413                if (bp.packageSetting == null && bp.pendingInfo != null) {
10414                    final BasePermission tree = findPermissionTreeLP(bp.name);
10415                    if (tree != null && tree.perm != null) {
10416                        bp.packageSetting = tree.packageSetting;
10417                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10418                                new PermissionInfo(bp.pendingInfo));
10419                        bp.perm.info.packageName = tree.perm.info.packageName;
10420                        bp.perm.info.name = bp.name;
10421                        bp.uid = tree.uid;
10422                    }
10423                }
10424            }
10425            if (bp.packageSetting == null) {
10426                // We may not yet have parsed the package, so just see if
10427                // we still know about its settings.
10428                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10429            }
10430            if (bp.packageSetting == null) {
10431                Slog.w(TAG, "Removing dangling permission: " + bp.name
10432                        + " from package " + bp.sourcePackage);
10433                it.remove();
10434            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10435                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10436                    Slog.i(TAG, "Removing old permission: " + bp.name
10437                            + " from package " + bp.sourcePackage);
10438                    flags |= UPDATE_PERMISSIONS_ALL;
10439                    it.remove();
10440                }
10441            }
10442        }
10443
10444        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10445        // Now update the permissions for all packages, in particular
10446        // replace the granted permissions of the system packages.
10447        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10448            for (PackageParser.Package pkg : mPackages.values()) {
10449                if (pkg != pkgInfo) {
10450                    // Only replace for packages on requested volume
10451                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10452                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10453                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10454                    grantPermissionsLPw(pkg, replace, changingPkg);
10455                }
10456            }
10457        }
10458
10459        if (pkgInfo != null) {
10460            // Only replace for packages on requested volume
10461            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10462            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10463                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10464            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10465        }
10466        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10467    }
10468
10469    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10470            String packageOfInterest) {
10471        // IMPORTANT: There are two types of permissions: install and runtime.
10472        // Install time permissions are granted when the app is installed to
10473        // all device users and users added in the future. Runtime permissions
10474        // are granted at runtime explicitly to specific users. Normal and signature
10475        // protected permissions are install time permissions. Dangerous permissions
10476        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10477        // otherwise they are runtime permissions. This function does not manage
10478        // runtime permissions except for the case an app targeting Lollipop MR1
10479        // being upgraded to target a newer SDK, in which case dangerous permissions
10480        // are transformed from install time to runtime ones.
10481
10482        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10483        if (ps == null) {
10484            return;
10485        }
10486
10487        PermissionsState permissionsState = ps.getPermissionsState();
10488        PermissionsState origPermissions = permissionsState;
10489
10490        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10491
10492        boolean runtimePermissionsRevoked = false;
10493        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10494
10495        boolean changedInstallPermission = false;
10496
10497        if (replace) {
10498            ps.installPermissionsFixed = false;
10499            if (!ps.isSharedUser()) {
10500                origPermissions = new PermissionsState(permissionsState);
10501                permissionsState.reset();
10502            } else {
10503                // We need to know only about runtime permission changes since the
10504                // calling code always writes the install permissions state but
10505                // the runtime ones are written only if changed. The only cases of
10506                // changed runtime permissions here are promotion of an install to
10507                // runtime and revocation of a runtime from a shared user.
10508                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10509                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10510                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10511                    runtimePermissionsRevoked = true;
10512                }
10513            }
10514        }
10515
10516        permissionsState.setGlobalGids(mGlobalGids);
10517
10518        final int N = pkg.requestedPermissions.size();
10519        for (int i=0; i<N; i++) {
10520            final String name = pkg.requestedPermissions.get(i);
10521            final BasePermission bp = mSettings.mPermissions.get(name);
10522
10523            if (DEBUG_INSTALL) {
10524                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10525            }
10526
10527            if (bp == null || bp.packageSetting == null) {
10528                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10529                    Slog.w(TAG, "Unknown permission " + name
10530                            + " in package " + pkg.packageName);
10531                }
10532                continue;
10533            }
10534
10535
10536            // Limit ephemeral apps to ephemeral allowed permissions.
10537            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10538                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10539                        + pkg.packageName);
10540                continue;
10541            }
10542
10543            final String perm = bp.name;
10544            boolean allowedSig = false;
10545            int grant = GRANT_DENIED;
10546
10547            // Keep track of app op permissions.
10548            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10549                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10550                if (pkgs == null) {
10551                    pkgs = new ArraySet<>();
10552                    mAppOpPermissionPackages.put(bp.name, pkgs);
10553                }
10554                pkgs.add(pkg.packageName);
10555            }
10556
10557            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10558            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10559                    >= Build.VERSION_CODES.M;
10560            switch (level) {
10561                case PermissionInfo.PROTECTION_NORMAL: {
10562                    // For all apps normal permissions are install time ones.
10563                    grant = GRANT_INSTALL;
10564                } break;
10565
10566                case PermissionInfo.PROTECTION_DANGEROUS: {
10567                    // If a permission review is required for legacy apps we represent
10568                    // their permissions as always granted runtime ones since we need
10569                    // to keep the review required permission flag per user while an
10570                    // install permission's state is shared across all users.
10571                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10572                        // For legacy apps dangerous permissions are install time ones.
10573                        grant = GRANT_INSTALL;
10574                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10575                        // For legacy apps that became modern, install becomes runtime.
10576                        grant = GRANT_UPGRADE;
10577                    } else if (mPromoteSystemApps
10578                            && isSystemApp(ps)
10579                            && mExistingSystemPackages.contains(ps.name)) {
10580                        // For legacy system apps, install becomes runtime.
10581                        // We cannot check hasInstallPermission() for system apps since those
10582                        // permissions were granted implicitly and not persisted pre-M.
10583                        grant = GRANT_UPGRADE;
10584                    } else {
10585                        // For modern apps keep runtime permissions unchanged.
10586                        grant = GRANT_RUNTIME;
10587                    }
10588                } break;
10589
10590                case PermissionInfo.PROTECTION_SIGNATURE: {
10591                    // For all apps signature permissions are install time ones.
10592                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10593                    if (allowedSig) {
10594                        grant = GRANT_INSTALL;
10595                    }
10596                } break;
10597            }
10598
10599            if (DEBUG_INSTALL) {
10600                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10601            }
10602
10603            if (grant != GRANT_DENIED) {
10604                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10605                    // If this is an existing, non-system package, then
10606                    // we can't add any new permissions to it.
10607                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10608                        // Except...  if this is a permission that was added
10609                        // to the platform (note: need to only do this when
10610                        // updating the platform).
10611                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10612                            grant = GRANT_DENIED;
10613                        }
10614                    }
10615                }
10616
10617                switch (grant) {
10618                    case GRANT_INSTALL: {
10619                        // Revoke this as runtime permission to handle the case of
10620                        // a runtime permission being downgraded to an install one.
10621                        // Also in permission review mode we keep dangerous permissions
10622                        // for legacy apps
10623                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10624                            if (origPermissions.getRuntimePermissionState(
10625                                    bp.name, userId) != null) {
10626                                // Revoke the runtime permission and clear the flags.
10627                                origPermissions.revokeRuntimePermission(bp, userId);
10628                                origPermissions.updatePermissionFlags(bp, userId,
10629                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10630                                // If we revoked a permission permission, we have to write.
10631                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10632                                        changedRuntimePermissionUserIds, userId);
10633                            }
10634                        }
10635                        // Grant an install permission.
10636                        if (permissionsState.grantInstallPermission(bp) !=
10637                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10638                            changedInstallPermission = true;
10639                        }
10640                    } break;
10641
10642                    case GRANT_RUNTIME: {
10643                        // Grant previously granted runtime permissions.
10644                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10645                            PermissionState permissionState = origPermissions
10646                                    .getRuntimePermissionState(bp.name, userId);
10647                            int flags = permissionState != null
10648                                    ? permissionState.getFlags() : 0;
10649                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10650                                // Don't propagate the permission in a permission review mode if
10651                                // the former was revoked, i.e. marked to not propagate on upgrade.
10652                                // Note that in a permission review mode install permissions are
10653                                // represented as constantly granted runtime ones since we need to
10654                                // keep a per user state associated with the permission. Also the
10655                                // revoke on upgrade flag is no longer applicable and is reset.
10656                                final boolean revokeOnUpgrade = (flags & PackageManager
10657                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10658                                if (revokeOnUpgrade) {
10659                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10660                                    // Since we changed the flags, we have to write.
10661                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10662                                            changedRuntimePermissionUserIds, userId);
10663                                }
10664                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10665                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
10666                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
10667                                        // If we cannot put the permission as it was,
10668                                        // we have to write.
10669                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10670                                                changedRuntimePermissionUserIds, userId);
10671                                    }
10672                                }
10673
10674                                // If the app supports runtime permissions no need for a review.
10675                                if (mPermissionReviewRequired
10676                                        && appSupportsRuntimePermissions
10677                                        && (flags & PackageManager
10678                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10679                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10680                                    // Since we changed the flags, we have to write.
10681                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10682                                            changedRuntimePermissionUserIds, userId);
10683                                }
10684                            } else if (mPermissionReviewRequired
10685                                    && !appSupportsRuntimePermissions) {
10686                                // For legacy apps that need a permission review, every new
10687                                // runtime permission is granted but it is pending a review.
10688                                // We also need to review only platform defined runtime
10689                                // permissions as these are the only ones the platform knows
10690                                // how to disable the API to simulate revocation as legacy
10691                                // apps don't expect to run with revoked permissions.
10692                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10693                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10694                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10695                                        // We changed the flags, hence have to write.
10696                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10697                                                changedRuntimePermissionUserIds, userId);
10698                                    }
10699                                }
10700                                if (permissionsState.grantRuntimePermission(bp, userId)
10701                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10702                                    // We changed the permission, hence have to write.
10703                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10704                                            changedRuntimePermissionUserIds, userId);
10705                                }
10706                            }
10707                            // Propagate the permission flags.
10708                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10709                        }
10710                    } break;
10711
10712                    case GRANT_UPGRADE: {
10713                        // Grant runtime permissions for a previously held install permission.
10714                        PermissionState permissionState = origPermissions
10715                                .getInstallPermissionState(bp.name);
10716                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10717
10718                        if (origPermissions.revokeInstallPermission(bp)
10719                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10720                            // We will be transferring the permission flags, so clear them.
10721                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10722                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10723                            changedInstallPermission = true;
10724                        }
10725
10726                        // If the permission is not to be promoted to runtime we ignore it and
10727                        // also its other flags as they are not applicable to install permissions.
10728                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10729                            for (int userId : currentUserIds) {
10730                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10731                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10732                                    // Transfer the permission flags.
10733                                    permissionsState.updatePermissionFlags(bp, userId,
10734                                            flags, flags);
10735                                    // If we granted the permission, we have to write.
10736                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10737                                            changedRuntimePermissionUserIds, userId);
10738                                }
10739                            }
10740                        }
10741                    } break;
10742
10743                    default: {
10744                        if (packageOfInterest == null
10745                                || packageOfInterest.equals(pkg.packageName)) {
10746                            Slog.w(TAG, "Not granting permission " + perm
10747                                    + " to package " + pkg.packageName
10748                                    + " because it was previously installed without");
10749                        }
10750                    } break;
10751                }
10752            } else {
10753                if (permissionsState.revokeInstallPermission(bp) !=
10754                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10755                    // Also drop the permission flags.
10756                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10757                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10758                    changedInstallPermission = true;
10759                    Slog.i(TAG, "Un-granting permission " + perm
10760                            + " from package " + pkg.packageName
10761                            + " (protectionLevel=" + bp.protectionLevel
10762                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10763                            + ")");
10764                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10765                    // Don't print warning for app op permissions, since it is fine for them
10766                    // not to be granted, there is a UI for the user to decide.
10767                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10768                        Slog.w(TAG, "Not granting permission " + perm
10769                                + " to package " + pkg.packageName
10770                                + " (protectionLevel=" + bp.protectionLevel
10771                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10772                                + ")");
10773                    }
10774                }
10775            }
10776        }
10777
10778        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10779                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10780            // This is the first that we have heard about this package, so the
10781            // permissions we have now selected are fixed until explicitly
10782            // changed.
10783            ps.installPermissionsFixed = true;
10784        }
10785
10786        // Persist the runtime permissions state for users with changes. If permissions
10787        // were revoked because no app in the shared user declares them we have to
10788        // write synchronously to avoid losing runtime permissions state.
10789        for (int userId : changedRuntimePermissionUserIds) {
10790            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10791        }
10792    }
10793
10794    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10795        boolean allowed = false;
10796        final int NP = PackageParser.NEW_PERMISSIONS.length;
10797        for (int ip=0; ip<NP; ip++) {
10798            final PackageParser.NewPermissionInfo npi
10799                    = PackageParser.NEW_PERMISSIONS[ip];
10800            if (npi.name.equals(perm)
10801                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10802                allowed = true;
10803                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10804                        + pkg.packageName);
10805                break;
10806            }
10807        }
10808        return allowed;
10809    }
10810
10811    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10812            BasePermission bp, PermissionsState origPermissions) {
10813        boolean privilegedPermission = (bp.protectionLevel
10814                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10815        boolean privappPermissionsDisable =
10816                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10817        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10818        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10819        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10820                && !platformPackage && platformPermission) {
10821            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10822                    .getPrivAppPermissions(pkg.packageName);
10823            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10824            if (!whitelisted) {
10825                Slog.w(TAG, "Privileged permission " + perm + " for package "
10826                        + pkg.packageName + " - not in privapp-permissions whitelist");
10827                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10828                    return false;
10829                }
10830            }
10831        }
10832        boolean allowed = (compareSignatures(
10833                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10834                        == PackageManager.SIGNATURE_MATCH)
10835                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10836                        == PackageManager.SIGNATURE_MATCH);
10837        if (!allowed && privilegedPermission) {
10838            if (isSystemApp(pkg)) {
10839                // For updated system applications, a system permission
10840                // is granted only if it had been defined by the original application.
10841                if (pkg.isUpdatedSystemApp()) {
10842                    final PackageSetting sysPs = mSettings
10843                            .getDisabledSystemPkgLPr(pkg.packageName);
10844                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10845                        // If the original was granted this permission, we take
10846                        // that grant decision as read and propagate it to the
10847                        // update.
10848                        if (sysPs.isPrivileged()) {
10849                            allowed = true;
10850                        }
10851                    } else {
10852                        // The system apk may have been updated with an older
10853                        // version of the one on the data partition, but which
10854                        // granted a new system permission that it didn't have
10855                        // before.  In this case we do want to allow the app to
10856                        // now get the new permission if the ancestral apk is
10857                        // privileged to get it.
10858                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10859                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10860                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10861                                    allowed = true;
10862                                    break;
10863                                }
10864                            }
10865                        }
10866                        // Also if a privileged parent package on the system image or any of
10867                        // its children requested a privileged permission, the updated child
10868                        // packages can also get the permission.
10869                        if (pkg.parentPackage != null) {
10870                            final PackageSetting disabledSysParentPs = mSettings
10871                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10872                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10873                                    && disabledSysParentPs.isPrivileged()) {
10874                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10875                                    allowed = true;
10876                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10877                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10878                                    for (int i = 0; i < count; i++) {
10879                                        PackageParser.Package disabledSysChildPkg =
10880                                                disabledSysParentPs.pkg.childPackages.get(i);
10881                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10882                                                perm)) {
10883                                            allowed = true;
10884                                            break;
10885                                        }
10886                                    }
10887                                }
10888                            }
10889                        }
10890                    }
10891                } else {
10892                    allowed = isPrivilegedApp(pkg);
10893                }
10894            }
10895        }
10896        if (!allowed) {
10897            if (!allowed && (bp.protectionLevel
10898                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10899                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10900                // If this was a previously normal/dangerous permission that got moved
10901                // to a system permission as part of the runtime permission redesign, then
10902                // we still want to blindly grant it to old apps.
10903                allowed = true;
10904            }
10905            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10906                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10907                // If this permission is to be granted to the system installer and
10908                // this app is an installer, then it gets the permission.
10909                allowed = true;
10910            }
10911            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10912                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10913                // If this permission is to be granted to the system verifier and
10914                // this app is a verifier, then it gets the permission.
10915                allowed = true;
10916            }
10917            if (!allowed && (bp.protectionLevel
10918                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10919                    && isSystemApp(pkg)) {
10920                // Any pre-installed system app is allowed to get this permission.
10921                allowed = true;
10922            }
10923            if (!allowed && (bp.protectionLevel
10924                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10925                // For development permissions, a development permission
10926                // is granted only if it was already granted.
10927                allowed = origPermissions.hasInstallPermission(perm);
10928            }
10929            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10930                    && pkg.packageName.equals(mSetupWizardPackage)) {
10931                // If this permission is to be granted to the system setup wizard and
10932                // this app is a setup wizard, then it gets the permission.
10933                allowed = true;
10934            }
10935        }
10936        return allowed;
10937    }
10938
10939    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10940        final int permCount = pkg.requestedPermissions.size();
10941        for (int j = 0; j < permCount; j++) {
10942            String requestedPermission = pkg.requestedPermissions.get(j);
10943            if (permission.equals(requestedPermission)) {
10944                return true;
10945            }
10946        }
10947        return false;
10948    }
10949
10950    final class ActivityIntentResolver
10951            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10952        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10953                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10954            if (!sUserManager.exists(userId)) return null;
10955            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10956                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10957                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10958            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10959                    isEphemeral, userId);
10960        }
10961
10962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10963                int userId) {
10964            if (!sUserManager.exists(userId)) return null;
10965            mFlags = flags;
10966            return super.queryIntent(intent, resolvedType,
10967                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10968                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10969                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10970        }
10971
10972        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10973                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10974            if (!sUserManager.exists(userId)) return null;
10975            if (packageActivities == null) {
10976                return null;
10977            }
10978            mFlags = flags;
10979            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10980            final boolean vislbleToEphemeral =
10981                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10982            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10983            final int N = packageActivities.size();
10984            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10985                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10986
10987            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10988            for (int i = 0; i < N; ++i) {
10989                intentFilters = packageActivities.get(i).intents;
10990                if (intentFilters != null && intentFilters.size() > 0) {
10991                    PackageParser.ActivityIntentInfo[] array =
10992                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10993                    intentFilters.toArray(array);
10994                    listCut.add(array);
10995                }
10996            }
10997            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10998                    vislbleToEphemeral, isEphemeral, listCut, userId);
10999        }
11000
11001        /**
11002         * Finds a privileged activity that matches the specified activity names.
11003         */
11004        private PackageParser.Activity findMatchingActivity(
11005                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11006            for (PackageParser.Activity sysActivity : activityList) {
11007                if (sysActivity.info.name.equals(activityInfo.name)) {
11008                    return sysActivity;
11009                }
11010                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11011                    return sysActivity;
11012                }
11013                if (sysActivity.info.targetActivity != null) {
11014                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11015                        return sysActivity;
11016                    }
11017                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11018                        return sysActivity;
11019                    }
11020                }
11021            }
11022            return null;
11023        }
11024
11025        public class IterGenerator<E> {
11026            public Iterator<E> generate(ActivityIntentInfo info) {
11027                return null;
11028            }
11029        }
11030
11031        public class ActionIterGenerator extends IterGenerator<String> {
11032            @Override
11033            public Iterator<String> generate(ActivityIntentInfo info) {
11034                return info.actionsIterator();
11035            }
11036        }
11037
11038        public class CategoriesIterGenerator extends IterGenerator<String> {
11039            @Override
11040            public Iterator<String> generate(ActivityIntentInfo info) {
11041                return info.categoriesIterator();
11042            }
11043        }
11044
11045        public class SchemesIterGenerator extends IterGenerator<String> {
11046            @Override
11047            public Iterator<String> generate(ActivityIntentInfo info) {
11048                return info.schemesIterator();
11049            }
11050        }
11051
11052        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11053            @Override
11054            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11055                return info.authoritiesIterator();
11056            }
11057        }
11058
11059        /**
11060         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11061         * MODIFIED. Do not pass in a list that should not be changed.
11062         */
11063        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11064                IterGenerator<T> generator, Iterator<T> searchIterator) {
11065            // loop through the set of actions; every one must be found in the intent filter
11066            while (searchIterator.hasNext()) {
11067                // we must have at least one filter in the list to consider a match
11068                if (intentList.size() == 0) {
11069                    break;
11070                }
11071
11072                final T searchAction = searchIterator.next();
11073
11074                // loop through the set of intent filters
11075                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11076                while (intentIter.hasNext()) {
11077                    final ActivityIntentInfo intentInfo = intentIter.next();
11078                    boolean selectionFound = false;
11079
11080                    // loop through the intent filter's selection criteria; at least one
11081                    // of them must match the searched criteria
11082                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11083                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11084                        final T intentSelection = intentSelectionIter.next();
11085                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11086                            selectionFound = true;
11087                            break;
11088                        }
11089                    }
11090
11091                    // the selection criteria wasn't found in this filter's set; this filter
11092                    // is not a potential match
11093                    if (!selectionFound) {
11094                        intentIter.remove();
11095                    }
11096                }
11097            }
11098        }
11099
11100        private boolean isProtectedAction(ActivityIntentInfo filter) {
11101            final Iterator<String> actionsIter = filter.actionsIterator();
11102            while (actionsIter != null && actionsIter.hasNext()) {
11103                final String filterAction = actionsIter.next();
11104                if (PROTECTED_ACTIONS.contains(filterAction)) {
11105                    return true;
11106                }
11107            }
11108            return false;
11109        }
11110
11111        /**
11112         * Adjusts the priority of the given intent filter according to policy.
11113         * <p>
11114         * <ul>
11115         * <li>The priority for non privileged applications is capped to '0'</li>
11116         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11117         * <li>The priority for unbundled updates to privileged applications is capped to the
11118         *      priority defined on the system partition</li>
11119         * </ul>
11120         * <p>
11121         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11122         * allowed to obtain any priority on any action.
11123         */
11124        private void adjustPriority(
11125                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11126            // nothing to do; priority is fine as-is
11127            if (intent.getPriority() <= 0) {
11128                return;
11129            }
11130
11131            final ActivityInfo activityInfo = intent.activity.info;
11132            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11133
11134            final boolean privilegedApp =
11135                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11136            if (!privilegedApp) {
11137                // non-privileged applications can never define a priority >0
11138                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11139                        + " package: " + applicationInfo.packageName
11140                        + " activity: " + intent.activity.className
11141                        + " origPrio: " + intent.getPriority());
11142                intent.setPriority(0);
11143                return;
11144            }
11145
11146            if (systemActivities == null) {
11147                // the system package is not disabled; we're parsing the system partition
11148                if (isProtectedAction(intent)) {
11149                    if (mDeferProtectedFilters) {
11150                        // We can't deal with these just yet. No component should ever obtain a
11151                        // >0 priority for a protected actions, with ONE exception -- the setup
11152                        // wizard. The setup wizard, however, cannot be known until we're able to
11153                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11154                        // until all intent filters have been processed. Chicken, meet egg.
11155                        // Let the filter temporarily have a high priority and rectify the
11156                        // priorities after all system packages have been scanned.
11157                        mProtectedFilters.add(intent);
11158                        if (DEBUG_FILTERS) {
11159                            Slog.i(TAG, "Protected action; save for later;"
11160                                    + " package: " + applicationInfo.packageName
11161                                    + " activity: " + intent.activity.className
11162                                    + " origPrio: " + intent.getPriority());
11163                        }
11164                        return;
11165                    } else {
11166                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11167                            Slog.i(TAG, "No setup wizard;"
11168                                + " All protected intents capped to priority 0");
11169                        }
11170                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11171                            if (DEBUG_FILTERS) {
11172                                Slog.i(TAG, "Found setup wizard;"
11173                                    + " allow priority " + intent.getPriority() + ";"
11174                                    + " package: " + intent.activity.info.packageName
11175                                    + " activity: " + intent.activity.className
11176                                    + " priority: " + intent.getPriority());
11177                            }
11178                            // setup wizard gets whatever it wants
11179                            return;
11180                        }
11181                        Slog.w(TAG, "Protected action; cap priority to 0;"
11182                                + " package: " + intent.activity.info.packageName
11183                                + " activity: " + intent.activity.className
11184                                + " origPrio: " + intent.getPriority());
11185                        intent.setPriority(0);
11186                        return;
11187                    }
11188                }
11189                // privileged apps on the system image get whatever priority they request
11190                return;
11191            }
11192
11193            // privileged app unbundled update ... try to find the same activity
11194            final PackageParser.Activity foundActivity =
11195                    findMatchingActivity(systemActivities, activityInfo);
11196            if (foundActivity == null) {
11197                // this is a new activity; it cannot obtain >0 priority
11198                if (DEBUG_FILTERS) {
11199                    Slog.i(TAG, "New activity; cap priority to 0;"
11200                            + " package: " + applicationInfo.packageName
11201                            + " activity: " + intent.activity.className
11202                            + " origPrio: " + intent.getPriority());
11203                }
11204                intent.setPriority(0);
11205                return;
11206            }
11207
11208            // found activity, now check for filter equivalence
11209
11210            // a shallow copy is enough; we modify the list, not its contents
11211            final List<ActivityIntentInfo> intentListCopy =
11212                    new ArrayList<>(foundActivity.intents);
11213            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11214
11215            // find matching action subsets
11216            final Iterator<String> actionsIterator = intent.actionsIterator();
11217            if (actionsIterator != null) {
11218                getIntentListSubset(
11219                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11220                if (intentListCopy.size() == 0) {
11221                    // no more intents to match; we're not equivalent
11222                    if (DEBUG_FILTERS) {
11223                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11224                                + " package: " + applicationInfo.packageName
11225                                + " activity: " + intent.activity.className
11226                                + " origPrio: " + intent.getPriority());
11227                    }
11228                    intent.setPriority(0);
11229                    return;
11230                }
11231            }
11232
11233            // find matching category subsets
11234            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11235            if (categoriesIterator != null) {
11236                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11237                        categoriesIterator);
11238                if (intentListCopy.size() == 0) {
11239                    // no more intents to match; we're not equivalent
11240                    if (DEBUG_FILTERS) {
11241                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11242                                + " package: " + applicationInfo.packageName
11243                                + " activity: " + intent.activity.className
11244                                + " origPrio: " + intent.getPriority());
11245                    }
11246                    intent.setPriority(0);
11247                    return;
11248                }
11249            }
11250
11251            // find matching schemes subsets
11252            final Iterator<String> schemesIterator = intent.schemesIterator();
11253            if (schemesIterator != null) {
11254                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11255                        schemesIterator);
11256                if (intentListCopy.size() == 0) {
11257                    // no more intents to match; we're not equivalent
11258                    if (DEBUG_FILTERS) {
11259                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11260                                + " package: " + applicationInfo.packageName
11261                                + " activity: " + intent.activity.className
11262                                + " origPrio: " + intent.getPriority());
11263                    }
11264                    intent.setPriority(0);
11265                    return;
11266                }
11267            }
11268
11269            // find matching authorities subsets
11270            final Iterator<IntentFilter.AuthorityEntry>
11271                    authoritiesIterator = intent.authoritiesIterator();
11272            if (authoritiesIterator != null) {
11273                getIntentListSubset(intentListCopy,
11274                        new AuthoritiesIterGenerator(),
11275                        authoritiesIterator);
11276                if (intentListCopy.size() == 0) {
11277                    // no more intents to match; we're not equivalent
11278                    if (DEBUG_FILTERS) {
11279                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11280                                + " package: " + applicationInfo.packageName
11281                                + " activity: " + intent.activity.className
11282                                + " origPrio: " + intent.getPriority());
11283                    }
11284                    intent.setPriority(0);
11285                    return;
11286                }
11287            }
11288
11289            // we found matching filter(s); app gets the max priority of all intents
11290            int cappedPriority = 0;
11291            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11292                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11293            }
11294            if (intent.getPriority() > cappedPriority) {
11295                if (DEBUG_FILTERS) {
11296                    Slog.i(TAG, "Found matching filter(s);"
11297                            + " cap priority to " + cappedPriority + ";"
11298                            + " package: " + applicationInfo.packageName
11299                            + " activity: " + intent.activity.className
11300                            + " origPrio: " + intent.getPriority());
11301                }
11302                intent.setPriority(cappedPriority);
11303                return;
11304            }
11305            // all this for nothing; the requested priority was <= what was on the system
11306        }
11307
11308        public final void addActivity(PackageParser.Activity a, String type) {
11309            mActivities.put(a.getComponentName(), a);
11310            if (DEBUG_SHOW_INFO)
11311                Log.v(
11312                TAG, "  " + type + " " +
11313                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11314            if (DEBUG_SHOW_INFO)
11315                Log.v(TAG, "    Class=" + a.info.name);
11316            final int NI = a.intents.size();
11317            for (int j=0; j<NI; j++) {
11318                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11319                if ("activity".equals(type)) {
11320                    final PackageSetting ps =
11321                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11322                    final List<PackageParser.Activity> systemActivities =
11323                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11324                    adjustPriority(systemActivities, intent);
11325                }
11326                if (DEBUG_SHOW_INFO) {
11327                    Log.v(TAG, "    IntentFilter:");
11328                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11329                }
11330                if (!intent.debugCheck()) {
11331                    Log.w(TAG, "==> For Activity " + a.info.name);
11332                }
11333                addFilter(intent);
11334            }
11335        }
11336
11337        public final void removeActivity(PackageParser.Activity a, String type) {
11338            mActivities.remove(a.getComponentName());
11339            if (DEBUG_SHOW_INFO) {
11340                Log.v(TAG, "  " + type + " "
11341                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11342                                : a.info.name) + ":");
11343                Log.v(TAG, "    Class=" + a.info.name);
11344            }
11345            final int NI = a.intents.size();
11346            for (int j=0; j<NI; j++) {
11347                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11348                if (DEBUG_SHOW_INFO) {
11349                    Log.v(TAG, "    IntentFilter:");
11350                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11351                }
11352                removeFilter(intent);
11353            }
11354        }
11355
11356        @Override
11357        protected boolean allowFilterResult(
11358                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11359            ActivityInfo filterAi = filter.activity.info;
11360            for (int i=dest.size()-1; i>=0; i--) {
11361                ActivityInfo destAi = dest.get(i).activityInfo;
11362                if (destAi.name == filterAi.name
11363                        && destAi.packageName == filterAi.packageName) {
11364                    return false;
11365                }
11366            }
11367            return true;
11368        }
11369
11370        @Override
11371        protected ActivityIntentInfo[] newArray(int size) {
11372            return new ActivityIntentInfo[size];
11373        }
11374
11375        @Override
11376        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11377            if (!sUserManager.exists(userId)) return true;
11378            PackageParser.Package p = filter.activity.owner;
11379            if (p != null) {
11380                PackageSetting ps = (PackageSetting)p.mExtras;
11381                if (ps != null) {
11382                    // System apps are never considered stopped for purposes of
11383                    // filtering, because there may be no way for the user to
11384                    // actually re-launch them.
11385                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11386                            && ps.getStopped(userId);
11387                }
11388            }
11389            return false;
11390        }
11391
11392        @Override
11393        protected boolean isPackageForFilter(String packageName,
11394                PackageParser.ActivityIntentInfo info) {
11395            return packageName.equals(info.activity.owner.packageName);
11396        }
11397
11398        @Override
11399        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11400                int match, int userId) {
11401            if (!sUserManager.exists(userId)) return null;
11402            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11403                return null;
11404            }
11405            final PackageParser.Activity activity = info.activity;
11406            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11407            if (ps == null) {
11408                return null;
11409            }
11410            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11411                    ps.readUserState(userId), userId);
11412            if (ai == null) {
11413                return null;
11414            }
11415            final ResolveInfo res = new ResolveInfo();
11416            res.activityInfo = ai;
11417            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11418                res.filter = info;
11419            }
11420            if (info != null) {
11421                res.handleAllWebDataURI = info.handleAllWebDataURI();
11422            }
11423            res.priority = info.getPriority();
11424            res.preferredOrder = activity.owner.mPreferredOrder;
11425            //System.out.println("Result: " + res.activityInfo.className +
11426            //                   " = " + res.priority);
11427            res.match = match;
11428            res.isDefault = info.hasDefault;
11429            res.labelRes = info.labelRes;
11430            res.nonLocalizedLabel = info.nonLocalizedLabel;
11431            if (userNeedsBadging(userId)) {
11432                res.noResourceId = true;
11433            } else {
11434                res.icon = info.icon;
11435            }
11436            res.iconResourceId = info.icon;
11437            res.system = res.activityInfo.applicationInfo.isSystemApp();
11438            return res;
11439        }
11440
11441        @Override
11442        protected void sortResults(List<ResolveInfo> results) {
11443            Collections.sort(results, mResolvePrioritySorter);
11444        }
11445
11446        @Override
11447        protected void dumpFilter(PrintWriter out, String prefix,
11448                PackageParser.ActivityIntentInfo filter) {
11449            out.print(prefix); out.print(
11450                    Integer.toHexString(System.identityHashCode(filter.activity)));
11451                    out.print(' ');
11452                    filter.activity.printComponentShortName(out);
11453                    out.print(" filter ");
11454                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11455        }
11456
11457        @Override
11458        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11459            return filter.activity;
11460        }
11461
11462        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11463            PackageParser.Activity activity = (PackageParser.Activity)label;
11464            out.print(prefix); out.print(
11465                    Integer.toHexString(System.identityHashCode(activity)));
11466                    out.print(' ');
11467                    activity.printComponentShortName(out);
11468            if (count > 1) {
11469                out.print(" ("); out.print(count); out.print(" filters)");
11470            }
11471            out.println();
11472        }
11473
11474        // Keys are String (activity class name), values are Activity.
11475        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11476                = new ArrayMap<ComponentName, PackageParser.Activity>();
11477        private int mFlags;
11478    }
11479
11480    private final class ServiceIntentResolver
11481            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11482        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11483                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11484            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11485            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11486                    isEphemeral, userId);
11487        }
11488
11489        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11490                int userId) {
11491            if (!sUserManager.exists(userId)) return null;
11492            mFlags = flags;
11493            return super.queryIntent(intent, resolvedType,
11494                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11495                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11496                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11497        }
11498
11499        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11500                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11501            if (!sUserManager.exists(userId)) return null;
11502            if (packageServices == null) {
11503                return null;
11504            }
11505            mFlags = flags;
11506            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11507            final boolean vislbleToEphemeral =
11508                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11509            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11510            final int N = packageServices.size();
11511            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11512                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11513
11514            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11515            for (int i = 0; i < N; ++i) {
11516                intentFilters = packageServices.get(i).intents;
11517                if (intentFilters != null && intentFilters.size() > 0) {
11518                    PackageParser.ServiceIntentInfo[] array =
11519                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11520                    intentFilters.toArray(array);
11521                    listCut.add(array);
11522                }
11523            }
11524            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11525                    vislbleToEphemeral, isEphemeral, listCut, userId);
11526        }
11527
11528        public final void addService(PackageParser.Service s) {
11529            mServices.put(s.getComponentName(), s);
11530            if (DEBUG_SHOW_INFO) {
11531                Log.v(TAG, "  "
11532                        + (s.info.nonLocalizedLabel != null
11533                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11534                Log.v(TAG, "    Class=" + s.info.name);
11535            }
11536            final int NI = s.intents.size();
11537            int j;
11538            for (j=0; j<NI; j++) {
11539                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11540                if (DEBUG_SHOW_INFO) {
11541                    Log.v(TAG, "    IntentFilter:");
11542                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11543                }
11544                if (!intent.debugCheck()) {
11545                    Log.w(TAG, "==> For Service " + s.info.name);
11546                }
11547                addFilter(intent);
11548            }
11549        }
11550
11551        public final void removeService(PackageParser.Service s) {
11552            mServices.remove(s.getComponentName());
11553            if (DEBUG_SHOW_INFO) {
11554                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11555                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11556                Log.v(TAG, "    Class=" + s.info.name);
11557            }
11558            final int NI = s.intents.size();
11559            int j;
11560            for (j=0; j<NI; j++) {
11561                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11562                if (DEBUG_SHOW_INFO) {
11563                    Log.v(TAG, "    IntentFilter:");
11564                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11565                }
11566                removeFilter(intent);
11567            }
11568        }
11569
11570        @Override
11571        protected boolean allowFilterResult(
11572                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11573            ServiceInfo filterSi = filter.service.info;
11574            for (int i=dest.size()-1; i>=0; i--) {
11575                ServiceInfo destAi = dest.get(i).serviceInfo;
11576                if (destAi.name == filterSi.name
11577                        && destAi.packageName == filterSi.packageName) {
11578                    return false;
11579                }
11580            }
11581            return true;
11582        }
11583
11584        @Override
11585        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11586            return new PackageParser.ServiceIntentInfo[size];
11587        }
11588
11589        @Override
11590        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11591            if (!sUserManager.exists(userId)) return true;
11592            PackageParser.Package p = filter.service.owner;
11593            if (p != null) {
11594                PackageSetting ps = (PackageSetting)p.mExtras;
11595                if (ps != null) {
11596                    // System apps are never considered stopped for purposes of
11597                    // filtering, because there may be no way for the user to
11598                    // actually re-launch them.
11599                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11600                            && ps.getStopped(userId);
11601                }
11602            }
11603            return false;
11604        }
11605
11606        @Override
11607        protected boolean isPackageForFilter(String packageName,
11608                PackageParser.ServiceIntentInfo info) {
11609            return packageName.equals(info.service.owner.packageName);
11610        }
11611
11612        @Override
11613        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11614                int match, int userId) {
11615            if (!sUserManager.exists(userId)) return null;
11616            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11617            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11618                return null;
11619            }
11620            final PackageParser.Service service = info.service;
11621            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11622            if (ps == null) {
11623                return null;
11624            }
11625            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11626                    ps.readUserState(userId), userId);
11627            if (si == null) {
11628                return null;
11629            }
11630            final ResolveInfo res = new ResolveInfo();
11631            res.serviceInfo = si;
11632            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11633                res.filter = filter;
11634            }
11635            res.priority = info.getPriority();
11636            res.preferredOrder = service.owner.mPreferredOrder;
11637            res.match = match;
11638            res.isDefault = info.hasDefault;
11639            res.labelRes = info.labelRes;
11640            res.nonLocalizedLabel = info.nonLocalizedLabel;
11641            res.icon = info.icon;
11642            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11643            return res;
11644        }
11645
11646        @Override
11647        protected void sortResults(List<ResolveInfo> results) {
11648            Collections.sort(results, mResolvePrioritySorter);
11649        }
11650
11651        @Override
11652        protected void dumpFilter(PrintWriter out, String prefix,
11653                PackageParser.ServiceIntentInfo filter) {
11654            out.print(prefix); out.print(
11655                    Integer.toHexString(System.identityHashCode(filter.service)));
11656                    out.print(' ');
11657                    filter.service.printComponentShortName(out);
11658                    out.print(" filter ");
11659                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11660        }
11661
11662        @Override
11663        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11664            return filter.service;
11665        }
11666
11667        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11668            PackageParser.Service service = (PackageParser.Service)label;
11669            out.print(prefix); out.print(
11670                    Integer.toHexString(System.identityHashCode(service)));
11671                    out.print(' ');
11672                    service.printComponentShortName(out);
11673            if (count > 1) {
11674                out.print(" ("); out.print(count); out.print(" filters)");
11675            }
11676            out.println();
11677        }
11678
11679//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11680//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11681//            final List<ResolveInfo> retList = Lists.newArrayList();
11682//            while (i.hasNext()) {
11683//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11684//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11685//                    retList.add(resolveInfo);
11686//                }
11687//            }
11688//            return retList;
11689//        }
11690
11691        // Keys are String (activity class name), values are Activity.
11692        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11693                = new ArrayMap<ComponentName, PackageParser.Service>();
11694        private int mFlags;
11695    }
11696
11697    private final class ProviderIntentResolver
11698            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11699        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11700                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11701            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11702            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11703                    isEphemeral, userId);
11704        }
11705
11706        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11707                int userId) {
11708            if (!sUserManager.exists(userId))
11709                return null;
11710            mFlags = flags;
11711            return super.queryIntent(intent, resolvedType,
11712                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11713                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11714                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11715        }
11716
11717        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11718                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11719            if (!sUserManager.exists(userId))
11720                return null;
11721            if (packageProviders == null) {
11722                return null;
11723            }
11724            mFlags = flags;
11725            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11726            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11727            final boolean vislbleToEphemeral =
11728                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11729            final int N = packageProviders.size();
11730            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11731                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11732
11733            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11734            for (int i = 0; i < N; ++i) {
11735                intentFilters = packageProviders.get(i).intents;
11736                if (intentFilters != null && intentFilters.size() > 0) {
11737                    PackageParser.ProviderIntentInfo[] array =
11738                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11739                    intentFilters.toArray(array);
11740                    listCut.add(array);
11741                }
11742            }
11743            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11744                    vislbleToEphemeral, isEphemeral, listCut, userId);
11745        }
11746
11747        public final void addProvider(PackageParser.Provider p) {
11748            if (mProviders.containsKey(p.getComponentName())) {
11749                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11750                return;
11751            }
11752
11753            mProviders.put(p.getComponentName(), p);
11754            if (DEBUG_SHOW_INFO) {
11755                Log.v(TAG, "  "
11756                        + (p.info.nonLocalizedLabel != null
11757                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11758                Log.v(TAG, "    Class=" + p.info.name);
11759            }
11760            final int NI = p.intents.size();
11761            int j;
11762            for (j = 0; j < NI; j++) {
11763                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11764                if (DEBUG_SHOW_INFO) {
11765                    Log.v(TAG, "    IntentFilter:");
11766                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11767                }
11768                if (!intent.debugCheck()) {
11769                    Log.w(TAG, "==> For Provider " + p.info.name);
11770                }
11771                addFilter(intent);
11772            }
11773        }
11774
11775        public final void removeProvider(PackageParser.Provider p) {
11776            mProviders.remove(p.getComponentName());
11777            if (DEBUG_SHOW_INFO) {
11778                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11779                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11780                Log.v(TAG, "    Class=" + p.info.name);
11781            }
11782            final int NI = p.intents.size();
11783            int j;
11784            for (j = 0; j < NI; j++) {
11785                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11786                if (DEBUG_SHOW_INFO) {
11787                    Log.v(TAG, "    IntentFilter:");
11788                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11789                }
11790                removeFilter(intent);
11791            }
11792        }
11793
11794        @Override
11795        protected boolean allowFilterResult(
11796                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11797            ProviderInfo filterPi = filter.provider.info;
11798            for (int i = dest.size() - 1; i >= 0; i--) {
11799                ProviderInfo destPi = dest.get(i).providerInfo;
11800                if (destPi.name == filterPi.name
11801                        && destPi.packageName == filterPi.packageName) {
11802                    return false;
11803                }
11804            }
11805            return true;
11806        }
11807
11808        @Override
11809        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11810            return new PackageParser.ProviderIntentInfo[size];
11811        }
11812
11813        @Override
11814        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11815            if (!sUserManager.exists(userId))
11816                return true;
11817            PackageParser.Package p = filter.provider.owner;
11818            if (p != null) {
11819                PackageSetting ps = (PackageSetting) p.mExtras;
11820                if (ps != null) {
11821                    // System apps are never considered stopped for purposes of
11822                    // filtering, because there may be no way for the user to
11823                    // actually re-launch them.
11824                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11825                            && ps.getStopped(userId);
11826                }
11827            }
11828            return false;
11829        }
11830
11831        @Override
11832        protected boolean isPackageForFilter(String packageName,
11833                PackageParser.ProviderIntentInfo info) {
11834            return packageName.equals(info.provider.owner.packageName);
11835        }
11836
11837        @Override
11838        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11839                int match, int userId) {
11840            if (!sUserManager.exists(userId))
11841                return null;
11842            final PackageParser.ProviderIntentInfo info = filter;
11843            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11844                return null;
11845            }
11846            final PackageParser.Provider provider = info.provider;
11847            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11848            if (ps == null) {
11849                return null;
11850            }
11851            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11852                    ps.readUserState(userId), userId);
11853            if (pi == null) {
11854                return null;
11855            }
11856            final ResolveInfo res = new ResolveInfo();
11857            res.providerInfo = pi;
11858            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11859                res.filter = filter;
11860            }
11861            res.priority = info.getPriority();
11862            res.preferredOrder = provider.owner.mPreferredOrder;
11863            res.match = match;
11864            res.isDefault = info.hasDefault;
11865            res.labelRes = info.labelRes;
11866            res.nonLocalizedLabel = info.nonLocalizedLabel;
11867            res.icon = info.icon;
11868            res.system = res.providerInfo.applicationInfo.isSystemApp();
11869            return res;
11870        }
11871
11872        @Override
11873        protected void sortResults(List<ResolveInfo> results) {
11874            Collections.sort(results, mResolvePrioritySorter);
11875        }
11876
11877        @Override
11878        protected void dumpFilter(PrintWriter out, String prefix,
11879                PackageParser.ProviderIntentInfo filter) {
11880            out.print(prefix);
11881            out.print(
11882                    Integer.toHexString(System.identityHashCode(filter.provider)));
11883            out.print(' ');
11884            filter.provider.printComponentShortName(out);
11885            out.print(" filter ");
11886            out.println(Integer.toHexString(System.identityHashCode(filter)));
11887        }
11888
11889        @Override
11890        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11891            return filter.provider;
11892        }
11893
11894        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11895            PackageParser.Provider provider = (PackageParser.Provider)label;
11896            out.print(prefix); out.print(
11897                    Integer.toHexString(System.identityHashCode(provider)));
11898                    out.print(' ');
11899                    provider.printComponentShortName(out);
11900            if (count > 1) {
11901                out.print(" ("); out.print(count); out.print(" filters)");
11902            }
11903            out.println();
11904        }
11905
11906        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11907                = new ArrayMap<ComponentName, PackageParser.Provider>();
11908        private int mFlags;
11909    }
11910
11911    static final class EphemeralIntentResolver
11912            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11913        /**
11914         * The result that has the highest defined order. Ordering applies on a
11915         * per-package basis. Mapping is from package name to Pair of order and
11916         * EphemeralResolveInfo.
11917         * <p>
11918         * NOTE: This is implemented as a field variable for convenience and efficiency.
11919         * By having a field variable, we're able to track filter ordering as soon as
11920         * a non-zero order is defined. Otherwise, multiple loops across the result set
11921         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11922         * this needs to be contained entirely within {@link #filterResults()}.
11923         */
11924        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11925
11926        @Override
11927        protected EphemeralResponse[] newArray(int size) {
11928            return new EphemeralResponse[size];
11929        }
11930
11931        @Override
11932        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11933            return true;
11934        }
11935
11936        @Override
11937        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11938                int userId) {
11939            if (!sUserManager.exists(userId)) {
11940                return null;
11941            }
11942            final String packageName = responseObj.resolveInfo.getPackageName();
11943            final Integer order = responseObj.getOrder();
11944            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11945                    mOrderResult.get(packageName);
11946            // ordering is enabled and this item's order isn't high enough
11947            if (lastOrderResult != null && lastOrderResult.first >= order) {
11948                return null;
11949            }
11950            final EphemeralResolveInfo res = responseObj.resolveInfo;
11951            if (order > 0) {
11952                // non-zero order, enable ordering
11953                mOrderResult.put(packageName, new Pair<>(order, res));
11954            }
11955            return responseObj;
11956        }
11957
11958        @Override
11959        protected void filterResults(List<EphemeralResponse> results) {
11960            // only do work if ordering is enabled [most of the time it won't be]
11961            if (mOrderResult.size() == 0) {
11962                return;
11963            }
11964            int resultSize = results.size();
11965            for (int i = 0; i < resultSize; i++) {
11966                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11967                final String packageName = info.getPackageName();
11968                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11969                if (savedInfo == null) {
11970                    // package doesn't having ordering
11971                    continue;
11972                }
11973                if (savedInfo.second == info) {
11974                    // circled back to the highest ordered item; remove from order list
11975                    mOrderResult.remove(savedInfo);
11976                    if (mOrderResult.size() == 0) {
11977                        // no more ordered items
11978                        break;
11979                    }
11980                    continue;
11981                }
11982                // item has a worse order, remove it from the result list
11983                results.remove(i);
11984                resultSize--;
11985                i--;
11986            }
11987        }
11988    }
11989
11990    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11991            new Comparator<ResolveInfo>() {
11992        public int compare(ResolveInfo r1, ResolveInfo r2) {
11993            int v1 = r1.priority;
11994            int v2 = r2.priority;
11995            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11996            if (v1 != v2) {
11997                return (v1 > v2) ? -1 : 1;
11998            }
11999            v1 = r1.preferredOrder;
12000            v2 = r2.preferredOrder;
12001            if (v1 != v2) {
12002                return (v1 > v2) ? -1 : 1;
12003            }
12004            if (r1.isDefault != r2.isDefault) {
12005                return r1.isDefault ? -1 : 1;
12006            }
12007            v1 = r1.match;
12008            v2 = r2.match;
12009            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12010            if (v1 != v2) {
12011                return (v1 > v2) ? -1 : 1;
12012            }
12013            if (r1.system != r2.system) {
12014                return r1.system ? -1 : 1;
12015            }
12016            if (r1.activityInfo != null) {
12017                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12018            }
12019            if (r1.serviceInfo != null) {
12020                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12021            }
12022            if (r1.providerInfo != null) {
12023                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12024            }
12025            return 0;
12026        }
12027    };
12028
12029    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12030            new Comparator<ProviderInfo>() {
12031        public int compare(ProviderInfo p1, ProviderInfo p2) {
12032            final int v1 = p1.initOrder;
12033            final int v2 = p2.initOrder;
12034            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12035        }
12036    };
12037
12038    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12039            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12040            final int[] userIds) {
12041        mHandler.post(new Runnable() {
12042            @Override
12043            public void run() {
12044                try {
12045                    final IActivityManager am = ActivityManager.getService();
12046                    if (am == null) return;
12047                    final int[] resolvedUserIds;
12048                    if (userIds == null) {
12049                        resolvedUserIds = am.getRunningUserIds();
12050                    } else {
12051                        resolvedUserIds = userIds;
12052                    }
12053                    for (int id : resolvedUserIds) {
12054                        final Intent intent = new Intent(action,
12055                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12056                        if (extras != null) {
12057                            intent.putExtras(extras);
12058                        }
12059                        if (targetPkg != null) {
12060                            intent.setPackage(targetPkg);
12061                        }
12062                        // Modify the UID when posting to other users
12063                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12064                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12065                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12066                            intent.putExtra(Intent.EXTRA_UID, uid);
12067                        }
12068                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12069                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12070                        if (DEBUG_BROADCASTS) {
12071                            RuntimeException here = new RuntimeException("here");
12072                            here.fillInStackTrace();
12073                            Slog.d(TAG, "Sending to user " + id + ": "
12074                                    + intent.toShortString(false, true, false, false)
12075                                    + " " + intent.getExtras(), here);
12076                        }
12077                        am.broadcastIntent(null, intent, null, finishedReceiver,
12078                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12079                                null, finishedReceiver != null, false, id);
12080                    }
12081                } catch (RemoteException ex) {
12082                }
12083            }
12084        });
12085    }
12086
12087    /**
12088     * Check if the external storage media is available. This is true if there
12089     * is a mounted external storage medium or if the external storage is
12090     * emulated.
12091     */
12092    private boolean isExternalMediaAvailable() {
12093        return mMediaMounted || Environment.isExternalStorageEmulated();
12094    }
12095
12096    @Override
12097    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12098        // writer
12099        synchronized (mPackages) {
12100            if (!isExternalMediaAvailable()) {
12101                // If the external storage is no longer mounted at this point,
12102                // the caller may not have been able to delete all of this
12103                // packages files and can not delete any more.  Bail.
12104                return null;
12105            }
12106            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12107            if (lastPackage != null) {
12108                pkgs.remove(lastPackage);
12109            }
12110            if (pkgs.size() > 0) {
12111                return pkgs.get(0);
12112            }
12113        }
12114        return null;
12115    }
12116
12117    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12118        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12119                userId, andCode ? 1 : 0, packageName);
12120        if (mSystemReady) {
12121            msg.sendToTarget();
12122        } else {
12123            if (mPostSystemReadyMessages == null) {
12124                mPostSystemReadyMessages = new ArrayList<>();
12125            }
12126            mPostSystemReadyMessages.add(msg);
12127        }
12128    }
12129
12130    void startCleaningPackages() {
12131        // reader
12132        if (!isExternalMediaAvailable()) {
12133            return;
12134        }
12135        synchronized (mPackages) {
12136            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12137                return;
12138            }
12139        }
12140        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12141        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12142        IActivityManager am = ActivityManager.getService();
12143        if (am != null) {
12144            try {
12145                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12146                        UserHandle.USER_SYSTEM);
12147            } catch (RemoteException e) {
12148            }
12149        }
12150    }
12151
12152    @Override
12153    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12154            int installFlags, String installerPackageName, int userId) {
12155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12156
12157        final int callingUid = Binder.getCallingUid();
12158        enforceCrossUserPermission(callingUid, userId,
12159                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12160
12161        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12162            try {
12163                if (observer != null) {
12164                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12165                }
12166            } catch (RemoteException re) {
12167            }
12168            return;
12169        }
12170
12171        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12172            installFlags |= PackageManager.INSTALL_FROM_ADB;
12173
12174        } else {
12175            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12176            // about installerPackageName.
12177
12178            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12179            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12180        }
12181
12182        UserHandle user;
12183        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12184            user = UserHandle.ALL;
12185        } else {
12186            user = new UserHandle(userId);
12187        }
12188
12189        // Only system components can circumvent runtime permissions when installing.
12190        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12191                && mContext.checkCallingOrSelfPermission(Manifest.permission
12192                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12193            throw new SecurityException("You need the "
12194                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12195                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12196        }
12197
12198        final File originFile = new File(originPath);
12199        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12200
12201        final Message msg = mHandler.obtainMessage(INIT_COPY);
12202        final VerificationInfo verificationInfo = new VerificationInfo(
12203                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12204        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12205                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12206                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12207                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12208        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12209        msg.obj = params;
12210
12211        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12212                System.identityHashCode(msg.obj));
12213        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12214                System.identityHashCode(msg.obj));
12215
12216        mHandler.sendMessage(msg);
12217    }
12218
12219    void installStage(String packageName, File stagedDir, String stagedCid,
12220            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12221            String installerPackageName, int installerUid, UserHandle user,
12222            Certificate[][] certificates) {
12223        if (DEBUG_EPHEMERAL) {
12224            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12225                Slog.d(TAG, "Ephemeral install of " + packageName);
12226            }
12227        }
12228        final VerificationInfo verificationInfo = new VerificationInfo(
12229                sessionParams.originatingUri, sessionParams.referrerUri,
12230                sessionParams.originatingUid, installerUid);
12231
12232        final OriginInfo origin;
12233        if (stagedDir != null) {
12234            origin = OriginInfo.fromStagedFile(stagedDir);
12235        } else {
12236            origin = OriginInfo.fromStagedContainer(stagedCid);
12237        }
12238
12239        final Message msg = mHandler.obtainMessage(INIT_COPY);
12240        final InstallParams params = new InstallParams(origin, null, observer,
12241                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12242                verificationInfo, user, sessionParams.abiOverride,
12243                sessionParams.grantedRuntimePermissions, certificates, sessionParams.installReason);
12244        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12245        msg.obj = params;
12246
12247        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12248                System.identityHashCode(msg.obj));
12249        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12250                System.identityHashCode(msg.obj));
12251
12252        mHandler.sendMessage(msg);
12253    }
12254
12255    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12256            int userId) {
12257        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12258        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12259    }
12260
12261    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12262            int appId, int... userIds) {
12263        if (ArrayUtils.isEmpty(userIds)) {
12264            return;
12265        }
12266        Bundle extras = new Bundle(1);
12267        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12268        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12269
12270        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12271                packageName, extras, 0, null, null, userIds);
12272        if (isSystem) {
12273            mHandler.post(() -> {
12274                        for (int userId : userIds) {
12275                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12276                        }
12277                    }
12278            );
12279        }
12280    }
12281
12282    /**
12283     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12284     * automatically without needing an explicit launch.
12285     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12286     */
12287    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12288        // If user is not running, the app didn't miss any broadcast
12289        if (!mUserManagerInternal.isUserRunning(userId)) {
12290            return;
12291        }
12292        final IActivityManager am = ActivityManager.getService();
12293        try {
12294            // Deliver LOCKED_BOOT_COMPLETED first
12295            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12296                    .setPackage(packageName);
12297            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12298            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12299                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12300
12301            // Deliver BOOT_COMPLETED only if user is unlocked
12302            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12303                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12304                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12305                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12306            }
12307        } catch (RemoteException e) {
12308            throw e.rethrowFromSystemServer();
12309        }
12310    }
12311
12312    @Override
12313    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12314            int userId) {
12315        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12316        PackageSetting pkgSetting;
12317        final int uid = Binder.getCallingUid();
12318        enforceCrossUserPermission(uid, userId,
12319                true /* requireFullPermission */, true /* checkShell */,
12320                "setApplicationHiddenSetting for user " + userId);
12321
12322        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12323            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12324            return false;
12325        }
12326
12327        long callingId = Binder.clearCallingIdentity();
12328        try {
12329            boolean sendAdded = false;
12330            boolean sendRemoved = false;
12331            // writer
12332            synchronized (mPackages) {
12333                pkgSetting = mSettings.mPackages.get(packageName);
12334                if (pkgSetting == null) {
12335                    return false;
12336                }
12337                // Do not allow "android" is being disabled
12338                if ("android".equals(packageName)) {
12339                    Slog.w(TAG, "Cannot hide package: android");
12340                    return false;
12341                }
12342                // Only allow protected packages to hide themselves.
12343                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12344                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12345                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12346                    return false;
12347                }
12348
12349                if (pkgSetting.getHidden(userId) != hidden) {
12350                    pkgSetting.setHidden(hidden, userId);
12351                    mSettings.writePackageRestrictionsLPr(userId);
12352                    if (hidden) {
12353                        sendRemoved = true;
12354                    } else {
12355                        sendAdded = true;
12356                    }
12357                }
12358            }
12359            if (sendAdded) {
12360                sendPackageAddedForUser(packageName, pkgSetting, userId);
12361                return true;
12362            }
12363            if (sendRemoved) {
12364                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12365                        "hiding pkg");
12366                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12367                return true;
12368            }
12369        } finally {
12370            Binder.restoreCallingIdentity(callingId);
12371        }
12372        return false;
12373    }
12374
12375    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12376            int userId) {
12377        final PackageRemovedInfo info = new PackageRemovedInfo();
12378        info.removedPackage = packageName;
12379        info.removedUsers = new int[] {userId};
12380        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12381        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12382    }
12383
12384    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12385        if (pkgList.length > 0) {
12386            Bundle extras = new Bundle(1);
12387            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12388
12389            sendPackageBroadcast(
12390                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12391                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12392                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12393                    new int[] {userId});
12394        }
12395    }
12396
12397    /**
12398     * Returns true if application is not found or there was an error. Otherwise it returns
12399     * the hidden state of the package for the given user.
12400     */
12401    @Override
12402    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12403        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12404        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12405                true /* requireFullPermission */, false /* checkShell */,
12406                "getApplicationHidden for user " + userId);
12407        PackageSetting pkgSetting;
12408        long callingId = Binder.clearCallingIdentity();
12409        try {
12410            // writer
12411            synchronized (mPackages) {
12412                pkgSetting = mSettings.mPackages.get(packageName);
12413                if (pkgSetting == null) {
12414                    return true;
12415                }
12416                return pkgSetting.getHidden(userId);
12417            }
12418        } finally {
12419            Binder.restoreCallingIdentity(callingId);
12420        }
12421    }
12422
12423    /**
12424     * @hide
12425     */
12426    @Override
12427    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
12428        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12429                null);
12430        PackageSetting pkgSetting;
12431        final int uid = Binder.getCallingUid();
12432        enforceCrossUserPermission(uid, userId,
12433                true /* requireFullPermission */, true /* checkShell */,
12434                "installExistingPackage for user " + userId);
12435        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12436            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12437        }
12438
12439        long callingId = Binder.clearCallingIdentity();
12440        try {
12441            boolean installed = false;
12442
12443            // writer
12444            synchronized (mPackages) {
12445                pkgSetting = mSettings.mPackages.get(packageName);
12446                if (pkgSetting == null) {
12447                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12448                }
12449                if (!pkgSetting.getInstalled(userId)) {
12450                    pkgSetting.setInstalled(true, userId);
12451                    pkgSetting.setHidden(false, userId);
12452                    pkgSetting.setInstallReason(installReason, userId);
12453                    mSettings.writePackageRestrictionsLPr(userId);
12454                    installed = true;
12455                }
12456            }
12457
12458            if (installed) {
12459                if (pkgSetting.pkg != null) {
12460                    synchronized (mInstallLock) {
12461                        // We don't need to freeze for a brand new install
12462                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12463                    }
12464                }
12465                sendPackageAddedForUser(packageName, pkgSetting, userId);
12466            }
12467        } finally {
12468            Binder.restoreCallingIdentity(callingId);
12469        }
12470
12471        return PackageManager.INSTALL_SUCCEEDED;
12472    }
12473
12474    boolean isUserRestricted(int userId, String restrictionKey) {
12475        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12476        if (restrictions.getBoolean(restrictionKey, false)) {
12477            Log.w(TAG, "User is restricted: " + restrictionKey);
12478            return true;
12479        }
12480        return false;
12481    }
12482
12483    @Override
12484    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12485            int userId) {
12486        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12487        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12488                true /* requireFullPermission */, true /* checkShell */,
12489                "setPackagesSuspended for user " + userId);
12490
12491        if (ArrayUtils.isEmpty(packageNames)) {
12492            return packageNames;
12493        }
12494
12495        // List of package names for whom the suspended state has changed.
12496        List<String> changedPackages = new ArrayList<>(packageNames.length);
12497        // List of package names for whom the suspended state is not set as requested in this
12498        // method.
12499        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12500        long callingId = Binder.clearCallingIdentity();
12501        try {
12502            for (int i = 0; i < packageNames.length; i++) {
12503                String packageName = packageNames[i];
12504                boolean changed = false;
12505                final int appId;
12506                synchronized (mPackages) {
12507                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12508                    if (pkgSetting == null) {
12509                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12510                                + "\". Skipping suspending/un-suspending.");
12511                        unactionedPackages.add(packageName);
12512                        continue;
12513                    }
12514                    appId = pkgSetting.appId;
12515                    if (pkgSetting.getSuspended(userId) != suspended) {
12516                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12517                            unactionedPackages.add(packageName);
12518                            continue;
12519                        }
12520                        pkgSetting.setSuspended(suspended, userId);
12521                        mSettings.writePackageRestrictionsLPr(userId);
12522                        changed = true;
12523                        changedPackages.add(packageName);
12524                    }
12525                }
12526
12527                if (changed && suspended) {
12528                    killApplication(packageName, UserHandle.getUid(userId, appId),
12529                            "suspending package");
12530                }
12531            }
12532        } finally {
12533            Binder.restoreCallingIdentity(callingId);
12534        }
12535
12536        if (!changedPackages.isEmpty()) {
12537            sendPackagesSuspendedForUser(changedPackages.toArray(
12538                    new String[changedPackages.size()]), userId, suspended);
12539        }
12540
12541        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12542    }
12543
12544    @Override
12545    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12546        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12547                true /* requireFullPermission */, false /* checkShell */,
12548                "isPackageSuspendedForUser for user " + userId);
12549        synchronized (mPackages) {
12550            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12551            if (pkgSetting == null) {
12552                throw new IllegalArgumentException("Unknown target package: " + packageName);
12553            }
12554            return pkgSetting.getSuspended(userId);
12555        }
12556    }
12557
12558    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12559        if (isPackageDeviceAdmin(packageName, userId)) {
12560            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12561                    + "\": has an active device admin");
12562            return false;
12563        }
12564
12565        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12566        if (packageName.equals(activeLauncherPackageName)) {
12567            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12568                    + "\": contains the active launcher");
12569            return false;
12570        }
12571
12572        if (packageName.equals(mRequiredInstallerPackage)) {
12573            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12574                    + "\": required for package installation");
12575            return false;
12576        }
12577
12578        if (packageName.equals(mRequiredUninstallerPackage)) {
12579            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12580                    + "\": required for package uninstallation");
12581            return false;
12582        }
12583
12584        if (packageName.equals(mRequiredVerifierPackage)) {
12585            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12586                    + "\": required for package verification");
12587            return false;
12588        }
12589
12590        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12591            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12592                    + "\": is the default dialer");
12593            return false;
12594        }
12595
12596        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12597            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12598                    + "\": protected package");
12599            return false;
12600        }
12601
12602        return true;
12603    }
12604
12605    private String getActiveLauncherPackageName(int userId) {
12606        Intent intent = new Intent(Intent.ACTION_MAIN);
12607        intent.addCategory(Intent.CATEGORY_HOME);
12608        ResolveInfo resolveInfo = resolveIntent(
12609                intent,
12610                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12611                PackageManager.MATCH_DEFAULT_ONLY,
12612                userId);
12613
12614        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12615    }
12616
12617    private String getDefaultDialerPackageName(int userId) {
12618        synchronized (mPackages) {
12619            return mSettings.getDefaultDialerPackageNameLPw(userId);
12620        }
12621    }
12622
12623    @Override
12624    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12625        mContext.enforceCallingOrSelfPermission(
12626                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12627                "Only package verification agents can verify applications");
12628
12629        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12630        final PackageVerificationResponse response = new PackageVerificationResponse(
12631                verificationCode, Binder.getCallingUid());
12632        msg.arg1 = id;
12633        msg.obj = response;
12634        mHandler.sendMessage(msg);
12635    }
12636
12637    @Override
12638    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12639            long millisecondsToDelay) {
12640        mContext.enforceCallingOrSelfPermission(
12641                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12642                "Only package verification agents can extend verification timeouts");
12643
12644        final PackageVerificationState state = mPendingVerification.get(id);
12645        final PackageVerificationResponse response = new PackageVerificationResponse(
12646                verificationCodeAtTimeout, Binder.getCallingUid());
12647
12648        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12649            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12650        }
12651        if (millisecondsToDelay < 0) {
12652            millisecondsToDelay = 0;
12653        }
12654        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12655                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12656            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12657        }
12658
12659        if ((state != null) && !state.timeoutExtended()) {
12660            state.extendTimeout();
12661
12662            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12663            msg.arg1 = id;
12664            msg.obj = response;
12665            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12666        }
12667    }
12668
12669    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12670            int verificationCode, UserHandle user) {
12671        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12672        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12673        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12674        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12675        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12676
12677        mContext.sendBroadcastAsUser(intent, user,
12678                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12679    }
12680
12681    private ComponentName matchComponentForVerifier(String packageName,
12682            List<ResolveInfo> receivers) {
12683        ActivityInfo targetReceiver = null;
12684
12685        final int NR = receivers.size();
12686        for (int i = 0; i < NR; i++) {
12687            final ResolveInfo info = receivers.get(i);
12688            if (info.activityInfo == null) {
12689                continue;
12690            }
12691
12692            if (packageName.equals(info.activityInfo.packageName)) {
12693                targetReceiver = info.activityInfo;
12694                break;
12695            }
12696        }
12697
12698        if (targetReceiver == null) {
12699            return null;
12700        }
12701
12702        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12703    }
12704
12705    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12706            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12707        if (pkgInfo.verifiers.length == 0) {
12708            return null;
12709        }
12710
12711        final int N = pkgInfo.verifiers.length;
12712        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12713        for (int i = 0; i < N; i++) {
12714            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12715
12716            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12717                    receivers);
12718            if (comp == null) {
12719                continue;
12720            }
12721
12722            final int verifierUid = getUidForVerifier(verifierInfo);
12723            if (verifierUid == -1) {
12724                continue;
12725            }
12726
12727            if (DEBUG_VERIFY) {
12728                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12729                        + " with the correct signature");
12730            }
12731            sufficientVerifiers.add(comp);
12732            verificationState.addSufficientVerifier(verifierUid);
12733        }
12734
12735        return sufficientVerifiers;
12736    }
12737
12738    private int getUidForVerifier(VerifierInfo verifierInfo) {
12739        synchronized (mPackages) {
12740            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12741            if (pkg == null) {
12742                return -1;
12743            } else if (pkg.mSignatures.length != 1) {
12744                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12745                        + " has more than one signature; ignoring");
12746                return -1;
12747            }
12748
12749            /*
12750             * If the public key of the package's signature does not match
12751             * our expected public key, then this is a different package and
12752             * we should skip.
12753             */
12754
12755            final byte[] expectedPublicKey;
12756            try {
12757                final Signature verifierSig = pkg.mSignatures[0];
12758                final PublicKey publicKey = verifierSig.getPublicKey();
12759                expectedPublicKey = publicKey.getEncoded();
12760            } catch (CertificateException e) {
12761                return -1;
12762            }
12763
12764            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12765
12766            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12767                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12768                        + " does not have the expected public key; ignoring");
12769                return -1;
12770            }
12771
12772            return pkg.applicationInfo.uid;
12773        }
12774    }
12775
12776    @Override
12777    public void finishPackageInstall(int token, boolean didLaunch) {
12778        enforceSystemOrRoot("Only the system is allowed to finish installs");
12779
12780        if (DEBUG_INSTALL) {
12781            Slog.v(TAG, "BM finishing package install for " + token);
12782        }
12783        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12784
12785        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12786        mHandler.sendMessage(msg);
12787    }
12788
12789    /**
12790     * Get the verification agent timeout.
12791     *
12792     * @return verification timeout in milliseconds
12793     */
12794    private long getVerificationTimeout() {
12795        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12796                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12797                DEFAULT_VERIFICATION_TIMEOUT);
12798    }
12799
12800    /**
12801     * Get the default verification agent response code.
12802     *
12803     * @return default verification response code
12804     */
12805    private int getDefaultVerificationResponse() {
12806        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12807                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12808                DEFAULT_VERIFICATION_RESPONSE);
12809    }
12810
12811    /**
12812     * Check whether or not package verification has been enabled.
12813     *
12814     * @return true if verification should be performed
12815     */
12816    private boolean isVerificationEnabled(int userId, int installFlags) {
12817        if (!DEFAULT_VERIFY_ENABLE) {
12818            return false;
12819        }
12820        // Ephemeral apps don't get the full verification treatment
12821        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12822            if (DEBUG_EPHEMERAL) {
12823                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12824            }
12825            return false;
12826        }
12827
12828        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12829
12830        // Check if installing from ADB
12831        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12832            // Do not run verification in a test harness environment
12833            if (ActivityManager.isRunningInTestHarness()) {
12834                return false;
12835            }
12836            if (ensureVerifyAppsEnabled) {
12837                return true;
12838            }
12839            // Check if the developer does not want package verification for ADB installs
12840            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12841                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12842                return false;
12843            }
12844        }
12845
12846        if (ensureVerifyAppsEnabled) {
12847            return true;
12848        }
12849
12850        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12851                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12852    }
12853
12854    @Override
12855    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12856            throws RemoteException {
12857        mContext.enforceCallingOrSelfPermission(
12858                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12859                "Only intentfilter verification agents can verify applications");
12860
12861        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12862        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12863                Binder.getCallingUid(), verificationCode, failedDomains);
12864        msg.arg1 = id;
12865        msg.obj = response;
12866        mHandler.sendMessage(msg);
12867    }
12868
12869    @Override
12870    public int getIntentVerificationStatus(String packageName, int userId) {
12871        synchronized (mPackages) {
12872            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12873        }
12874    }
12875
12876    @Override
12877    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12878        mContext.enforceCallingOrSelfPermission(
12879                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12880
12881        boolean result = false;
12882        synchronized (mPackages) {
12883            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12884        }
12885        if (result) {
12886            scheduleWritePackageRestrictionsLocked(userId);
12887        }
12888        return result;
12889    }
12890
12891    @Override
12892    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12893            String packageName) {
12894        synchronized (mPackages) {
12895            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12896        }
12897    }
12898
12899    @Override
12900    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12901        if (TextUtils.isEmpty(packageName)) {
12902            return ParceledListSlice.emptyList();
12903        }
12904        synchronized (mPackages) {
12905            PackageParser.Package pkg = mPackages.get(packageName);
12906            if (pkg == null || pkg.activities == null) {
12907                return ParceledListSlice.emptyList();
12908            }
12909            final int count = pkg.activities.size();
12910            ArrayList<IntentFilter> result = new ArrayList<>();
12911            for (int n=0; n<count; n++) {
12912                PackageParser.Activity activity = pkg.activities.get(n);
12913                if (activity.intents != null && activity.intents.size() > 0) {
12914                    result.addAll(activity.intents);
12915                }
12916            }
12917            return new ParceledListSlice<>(result);
12918        }
12919    }
12920
12921    @Override
12922    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12923        mContext.enforceCallingOrSelfPermission(
12924                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12925
12926        synchronized (mPackages) {
12927            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12928            if (packageName != null) {
12929                result |= updateIntentVerificationStatus(packageName,
12930                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12931                        userId);
12932                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12933                        packageName, userId);
12934            }
12935            return result;
12936        }
12937    }
12938
12939    @Override
12940    public String getDefaultBrowserPackageName(int userId) {
12941        synchronized (mPackages) {
12942            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12943        }
12944    }
12945
12946    /**
12947     * Get the "allow unknown sources" setting.
12948     *
12949     * @return the current "allow unknown sources" setting
12950     */
12951    private int getUnknownSourcesSettings() {
12952        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12953                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12954                -1);
12955    }
12956
12957    @Override
12958    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12959        final int uid = Binder.getCallingUid();
12960        // writer
12961        synchronized (mPackages) {
12962            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12963            if (targetPackageSetting == null) {
12964                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12965            }
12966
12967            PackageSetting installerPackageSetting;
12968            if (installerPackageName != null) {
12969                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12970                if (installerPackageSetting == null) {
12971                    throw new IllegalArgumentException("Unknown installer package: "
12972                            + installerPackageName);
12973                }
12974            } else {
12975                installerPackageSetting = null;
12976            }
12977
12978            Signature[] callerSignature;
12979            Object obj = mSettings.getUserIdLPr(uid);
12980            if (obj != null) {
12981                if (obj instanceof SharedUserSetting) {
12982                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12983                } else if (obj instanceof PackageSetting) {
12984                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12985                } else {
12986                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12987                }
12988            } else {
12989                throw new SecurityException("Unknown calling UID: " + uid);
12990            }
12991
12992            // Verify: can't set installerPackageName to a package that is
12993            // not signed with the same cert as the caller.
12994            if (installerPackageSetting != null) {
12995                if (compareSignatures(callerSignature,
12996                        installerPackageSetting.signatures.mSignatures)
12997                        != PackageManager.SIGNATURE_MATCH) {
12998                    throw new SecurityException(
12999                            "Caller does not have same cert as new installer package "
13000                            + installerPackageName);
13001                }
13002            }
13003
13004            // Verify: if target already has an installer package, it must
13005            // be signed with the same cert as the caller.
13006            if (targetPackageSetting.installerPackageName != null) {
13007                PackageSetting setting = mSettings.mPackages.get(
13008                        targetPackageSetting.installerPackageName);
13009                // If the currently set package isn't valid, then it's always
13010                // okay to change it.
13011                if (setting != null) {
13012                    if (compareSignatures(callerSignature,
13013                            setting.signatures.mSignatures)
13014                            != PackageManager.SIGNATURE_MATCH) {
13015                        throw new SecurityException(
13016                                "Caller does not have same cert as old installer package "
13017                                + targetPackageSetting.installerPackageName);
13018                    }
13019                }
13020            }
13021
13022            // Okay!
13023            targetPackageSetting.installerPackageName = installerPackageName;
13024            if (installerPackageName != null) {
13025                mSettings.mInstallerPackages.add(installerPackageName);
13026            }
13027            scheduleWriteSettingsLocked();
13028        }
13029    }
13030
13031    @Override
13032    public void setApplicationCategoryHint(String packageName, int categoryHint,
13033            String callerPackageName) {
13034        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13035                callerPackageName);
13036        synchronized (mPackages) {
13037            PackageSetting ps = mSettings.mPackages.get(packageName);
13038            if (ps == null) {
13039                throw new IllegalArgumentException("Unknown target package " + packageName);
13040            }
13041
13042            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13043                throw new IllegalArgumentException("Calling package " + callerPackageName
13044                        + " is not installer for " + packageName);
13045            }
13046
13047            if (ps.categoryHint != categoryHint) {
13048                ps.categoryHint = categoryHint;
13049                scheduleWriteSettingsLocked();
13050            }
13051        }
13052    }
13053
13054    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13055        // Queue up an async operation since the package installation may take a little while.
13056        mHandler.post(new Runnable() {
13057            public void run() {
13058                mHandler.removeCallbacks(this);
13059                 // Result object to be returned
13060                PackageInstalledInfo res = new PackageInstalledInfo();
13061                res.setReturnCode(currentStatus);
13062                res.uid = -1;
13063                res.pkg = null;
13064                res.removedInfo = null;
13065                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13066                    args.doPreInstall(res.returnCode);
13067                    synchronized (mInstallLock) {
13068                        installPackageTracedLI(args, res);
13069                    }
13070                    args.doPostInstall(res.returnCode, res.uid);
13071                }
13072
13073                // A restore should be performed at this point if (a) the install
13074                // succeeded, (b) the operation is not an update, and (c) the new
13075                // package has not opted out of backup participation.
13076                final boolean update = res.removedInfo != null
13077                        && res.removedInfo.removedPackage != null;
13078                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13079                boolean doRestore = !update
13080                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13081
13082                // Set up the post-install work request bookkeeping.  This will be used
13083                // and cleaned up by the post-install event handling regardless of whether
13084                // there's a restore pass performed.  Token values are >= 1.
13085                int token;
13086                if (mNextInstallToken < 0) mNextInstallToken = 1;
13087                token = mNextInstallToken++;
13088
13089                PostInstallData data = new PostInstallData(args, res);
13090                mRunningInstalls.put(token, data);
13091                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13092
13093                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13094                    // Pass responsibility to the Backup Manager.  It will perform a
13095                    // restore if appropriate, then pass responsibility back to the
13096                    // Package Manager to run the post-install observer callbacks
13097                    // and broadcasts.
13098                    IBackupManager bm = IBackupManager.Stub.asInterface(
13099                            ServiceManager.getService(Context.BACKUP_SERVICE));
13100                    if (bm != null) {
13101                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13102                                + " to BM for possible restore");
13103                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13104                        try {
13105                            // TODO: http://b/22388012
13106                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13107                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13108                            } else {
13109                                doRestore = false;
13110                            }
13111                        } catch (RemoteException e) {
13112                            // can't happen; the backup manager is local
13113                        } catch (Exception e) {
13114                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13115                            doRestore = false;
13116                        }
13117                    } else {
13118                        Slog.e(TAG, "Backup Manager not found!");
13119                        doRestore = false;
13120                    }
13121                }
13122
13123                if (!doRestore) {
13124                    // No restore possible, or the Backup Manager was mysteriously not
13125                    // available -- just fire the post-install work request directly.
13126                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13127
13128                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13129
13130                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13131                    mHandler.sendMessage(msg);
13132                }
13133            }
13134        });
13135    }
13136
13137    /**
13138     * Callback from PackageSettings whenever an app is first transitioned out of the
13139     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13140     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13141     * here whether the app is the target of an ongoing install, and only send the
13142     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13143     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13144     * handling.
13145     */
13146    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13147        // Serialize this with the rest of the install-process message chain.  In the
13148        // restore-at-install case, this Runnable will necessarily run before the
13149        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13150        // are coherent.  In the non-restore case, the app has already completed install
13151        // and been launched through some other means, so it is not in a problematic
13152        // state for observers to see the FIRST_LAUNCH signal.
13153        mHandler.post(new Runnable() {
13154            @Override
13155            public void run() {
13156                for (int i = 0; i < mRunningInstalls.size(); i++) {
13157                    final PostInstallData data = mRunningInstalls.valueAt(i);
13158                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13159                        continue;
13160                    }
13161                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13162                        // right package; but is it for the right user?
13163                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13164                            if (userId == data.res.newUsers[uIndex]) {
13165                                if (DEBUG_BACKUP) {
13166                                    Slog.i(TAG, "Package " + pkgName
13167                                            + " being restored so deferring FIRST_LAUNCH");
13168                                }
13169                                return;
13170                            }
13171                        }
13172                    }
13173                }
13174                // didn't find it, so not being restored
13175                if (DEBUG_BACKUP) {
13176                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13177                }
13178                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13179            }
13180        });
13181    }
13182
13183    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13184        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13185                installerPkg, null, userIds);
13186    }
13187
13188    private abstract class HandlerParams {
13189        private static final int MAX_RETRIES = 4;
13190
13191        /**
13192         * Number of times startCopy() has been attempted and had a non-fatal
13193         * error.
13194         */
13195        private int mRetries = 0;
13196
13197        /** User handle for the user requesting the information or installation. */
13198        private final UserHandle mUser;
13199        String traceMethod;
13200        int traceCookie;
13201
13202        HandlerParams(UserHandle user) {
13203            mUser = user;
13204        }
13205
13206        UserHandle getUser() {
13207            return mUser;
13208        }
13209
13210        HandlerParams setTraceMethod(String traceMethod) {
13211            this.traceMethod = traceMethod;
13212            return this;
13213        }
13214
13215        HandlerParams setTraceCookie(int traceCookie) {
13216            this.traceCookie = traceCookie;
13217            return this;
13218        }
13219
13220        final boolean startCopy() {
13221            boolean res;
13222            try {
13223                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13224
13225                if (++mRetries > MAX_RETRIES) {
13226                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13227                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13228                    handleServiceError();
13229                    return false;
13230                } else {
13231                    handleStartCopy();
13232                    res = true;
13233                }
13234            } catch (RemoteException e) {
13235                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13236                mHandler.sendEmptyMessage(MCS_RECONNECT);
13237                res = false;
13238            }
13239            handleReturnCode();
13240            return res;
13241        }
13242
13243        final void serviceError() {
13244            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13245            handleServiceError();
13246            handleReturnCode();
13247        }
13248
13249        abstract void handleStartCopy() throws RemoteException;
13250        abstract void handleServiceError();
13251        abstract void handleReturnCode();
13252    }
13253
13254    class MeasureParams extends HandlerParams {
13255        private final PackageStats mStats;
13256        private boolean mSuccess;
13257
13258        private final IPackageStatsObserver mObserver;
13259
13260        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13261            super(new UserHandle(stats.userHandle));
13262            mObserver = observer;
13263            mStats = stats;
13264        }
13265
13266        @Override
13267        public String toString() {
13268            return "MeasureParams{"
13269                + Integer.toHexString(System.identityHashCode(this))
13270                + " " + mStats.packageName + "}";
13271        }
13272
13273        @Override
13274        void handleStartCopy() throws RemoteException {
13275            synchronized (mInstallLock) {
13276                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13277            }
13278
13279            if (mSuccess) {
13280                boolean mounted = false;
13281                try {
13282                    final String status = Environment.getExternalStorageState();
13283                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13284                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13285                } catch (Exception e) {
13286                }
13287
13288                if (mounted) {
13289                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13290
13291                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13292                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13293
13294                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13295                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13296
13297                    // Always subtract cache size, since it's a subdirectory
13298                    mStats.externalDataSize -= mStats.externalCacheSize;
13299
13300                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13301                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13302
13303                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13304                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13305                }
13306            }
13307        }
13308
13309        @Override
13310        void handleReturnCode() {
13311            if (mObserver != null) {
13312                try {
13313                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13314                } catch (RemoteException e) {
13315                    Slog.i(TAG, "Observer no longer exists.");
13316                }
13317            }
13318        }
13319
13320        @Override
13321        void handleServiceError() {
13322            Slog.e(TAG, "Could not measure application " + mStats.packageName
13323                            + " external storage");
13324        }
13325    }
13326
13327    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13328            throws RemoteException {
13329        long result = 0;
13330        for (File path : paths) {
13331            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13332        }
13333        return result;
13334    }
13335
13336    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13337        for (File path : paths) {
13338            try {
13339                mcs.clearDirectory(path.getAbsolutePath());
13340            } catch (RemoteException e) {
13341            }
13342        }
13343    }
13344
13345    static class OriginInfo {
13346        /**
13347         * Location where install is coming from, before it has been
13348         * copied/renamed into place. This could be a single monolithic APK
13349         * file, or a cluster directory. This location may be untrusted.
13350         */
13351        final File file;
13352        final String cid;
13353
13354        /**
13355         * Flag indicating that {@link #file} or {@link #cid} has already been
13356         * staged, meaning downstream users don't need to defensively copy the
13357         * contents.
13358         */
13359        final boolean staged;
13360
13361        /**
13362         * Flag indicating that {@link #file} or {@link #cid} is an already
13363         * installed app that is being moved.
13364         */
13365        final boolean existing;
13366
13367        final String resolvedPath;
13368        final File resolvedFile;
13369
13370        static OriginInfo fromNothing() {
13371            return new OriginInfo(null, null, false, false);
13372        }
13373
13374        static OriginInfo fromUntrustedFile(File file) {
13375            return new OriginInfo(file, null, false, false);
13376        }
13377
13378        static OriginInfo fromExistingFile(File file) {
13379            return new OriginInfo(file, null, false, true);
13380        }
13381
13382        static OriginInfo fromStagedFile(File file) {
13383            return new OriginInfo(file, null, true, false);
13384        }
13385
13386        static OriginInfo fromStagedContainer(String cid) {
13387            return new OriginInfo(null, cid, true, false);
13388        }
13389
13390        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13391            this.file = file;
13392            this.cid = cid;
13393            this.staged = staged;
13394            this.existing = existing;
13395
13396            if (cid != null) {
13397                resolvedPath = PackageHelper.getSdDir(cid);
13398                resolvedFile = new File(resolvedPath);
13399            } else if (file != null) {
13400                resolvedPath = file.getAbsolutePath();
13401                resolvedFile = file;
13402            } else {
13403                resolvedPath = null;
13404                resolvedFile = null;
13405            }
13406        }
13407    }
13408
13409    static class MoveInfo {
13410        final int moveId;
13411        final String fromUuid;
13412        final String toUuid;
13413        final String packageName;
13414        final String dataAppName;
13415        final int appId;
13416        final String seinfo;
13417        final int targetSdkVersion;
13418
13419        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13420                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13421            this.moveId = moveId;
13422            this.fromUuid = fromUuid;
13423            this.toUuid = toUuid;
13424            this.packageName = packageName;
13425            this.dataAppName = dataAppName;
13426            this.appId = appId;
13427            this.seinfo = seinfo;
13428            this.targetSdkVersion = targetSdkVersion;
13429        }
13430    }
13431
13432    static class VerificationInfo {
13433        /** A constant used to indicate that a uid value is not present. */
13434        public static final int NO_UID = -1;
13435
13436        /** URI referencing where the package was downloaded from. */
13437        final Uri originatingUri;
13438
13439        /** HTTP referrer URI associated with the originatingURI. */
13440        final Uri referrer;
13441
13442        /** UID of the application that the install request originated from. */
13443        final int originatingUid;
13444
13445        /** UID of application requesting the install */
13446        final int installerUid;
13447
13448        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13449            this.originatingUri = originatingUri;
13450            this.referrer = referrer;
13451            this.originatingUid = originatingUid;
13452            this.installerUid = installerUid;
13453        }
13454    }
13455
13456    class InstallParams extends HandlerParams {
13457        final OriginInfo origin;
13458        final MoveInfo move;
13459        final IPackageInstallObserver2 observer;
13460        int installFlags;
13461        final String installerPackageName;
13462        final String volumeUuid;
13463        private InstallArgs mArgs;
13464        private int mRet;
13465        final String packageAbiOverride;
13466        final String[] grantedRuntimePermissions;
13467        final VerificationInfo verificationInfo;
13468        final Certificate[][] certificates;
13469        final int installReason;
13470
13471        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13472                int installFlags, String installerPackageName, String volumeUuid,
13473                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13474                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
13475            super(user);
13476            this.origin = origin;
13477            this.move = move;
13478            this.observer = observer;
13479            this.installFlags = installFlags;
13480            this.installerPackageName = installerPackageName;
13481            this.volumeUuid = volumeUuid;
13482            this.verificationInfo = verificationInfo;
13483            this.packageAbiOverride = packageAbiOverride;
13484            this.grantedRuntimePermissions = grantedPermissions;
13485            this.certificates = certificates;
13486            this.installReason = installReason;
13487        }
13488
13489        @Override
13490        public String toString() {
13491            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13492                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13493        }
13494
13495        private int installLocationPolicy(PackageInfoLite pkgLite) {
13496            String packageName = pkgLite.packageName;
13497            int installLocation = pkgLite.installLocation;
13498            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13499            // reader
13500            synchronized (mPackages) {
13501                // Currently installed package which the new package is attempting to replace or
13502                // null if no such package is installed.
13503                PackageParser.Package installedPkg = mPackages.get(packageName);
13504                // Package which currently owns the data which the new package will own if installed.
13505                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13506                // will be null whereas dataOwnerPkg will contain information about the package
13507                // which was uninstalled while keeping its data.
13508                PackageParser.Package dataOwnerPkg = installedPkg;
13509                if (dataOwnerPkg  == null) {
13510                    PackageSetting ps = mSettings.mPackages.get(packageName);
13511                    if (ps != null) {
13512                        dataOwnerPkg = ps.pkg;
13513                    }
13514                }
13515
13516                if (dataOwnerPkg != null) {
13517                    // If installed, the package will get access to data left on the device by its
13518                    // predecessor. As a security measure, this is permited only if this is not a
13519                    // version downgrade or if the predecessor package is marked as debuggable and
13520                    // a downgrade is explicitly requested.
13521                    //
13522                    // On debuggable platform builds, downgrades are permitted even for
13523                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13524                    // not offer security guarantees and thus it's OK to disable some security
13525                    // mechanisms to make debugging/testing easier on those builds. However, even on
13526                    // debuggable builds downgrades of packages are permitted only if requested via
13527                    // installFlags. This is because we aim to keep the behavior of debuggable
13528                    // platform builds as close as possible to the behavior of non-debuggable
13529                    // platform builds.
13530                    final boolean downgradeRequested =
13531                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13532                    final boolean packageDebuggable =
13533                                (dataOwnerPkg.applicationInfo.flags
13534                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13535                    final boolean downgradePermitted =
13536                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13537                    if (!downgradePermitted) {
13538                        try {
13539                            checkDowngrade(dataOwnerPkg, pkgLite);
13540                        } catch (PackageManagerException e) {
13541                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13542                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13543                        }
13544                    }
13545                }
13546
13547                if (installedPkg != null) {
13548                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13549                        // Check for updated system application.
13550                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13551                            if (onSd) {
13552                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13553                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13554                            }
13555                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13556                        } else {
13557                            if (onSd) {
13558                                // Install flag overrides everything.
13559                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13560                            }
13561                            // If current upgrade specifies particular preference
13562                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13563                                // Application explicitly specified internal.
13564                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13565                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13566                                // App explictly prefers external. Let policy decide
13567                            } else {
13568                                // Prefer previous location
13569                                if (isExternal(installedPkg)) {
13570                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13571                                }
13572                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13573                            }
13574                        }
13575                    } else {
13576                        // Invalid install. Return error code
13577                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13578                    }
13579                }
13580            }
13581            // All the special cases have been taken care of.
13582            // Return result based on recommended install location.
13583            if (onSd) {
13584                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13585            }
13586            return pkgLite.recommendedInstallLocation;
13587        }
13588
13589        /*
13590         * Invoke remote method to get package information and install
13591         * location values. Override install location based on default
13592         * policy if needed and then create install arguments based
13593         * on the install location.
13594         */
13595        public void handleStartCopy() throws RemoteException {
13596            int ret = PackageManager.INSTALL_SUCCEEDED;
13597
13598            // If we're already staged, we've firmly committed to an install location
13599            if (origin.staged) {
13600                if (origin.file != null) {
13601                    installFlags |= PackageManager.INSTALL_INTERNAL;
13602                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13603                } else if (origin.cid != null) {
13604                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13605                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13606                } else {
13607                    throw new IllegalStateException("Invalid stage location");
13608                }
13609            }
13610
13611            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13612            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13613            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13614            PackageInfoLite pkgLite = null;
13615
13616            if (onInt && onSd) {
13617                // Check if both bits are set.
13618                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13619                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13620            } else if (onSd && ephemeral) {
13621                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13622                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13623            } else {
13624                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13625                        packageAbiOverride);
13626
13627                if (DEBUG_EPHEMERAL && ephemeral) {
13628                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13629                }
13630
13631                /*
13632                 * If we have too little free space, try to free cache
13633                 * before giving up.
13634                 */
13635                if (!origin.staged && pkgLite.recommendedInstallLocation
13636                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13637                    // TODO: focus freeing disk space on the target device
13638                    final StorageManager storage = StorageManager.from(mContext);
13639                    final long lowThreshold = storage.getStorageLowBytes(
13640                            Environment.getDataDirectory());
13641
13642                    final long sizeBytes = mContainerService.calculateInstalledSize(
13643                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13644
13645                    try {
13646                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13647                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13648                                installFlags, packageAbiOverride);
13649                    } catch (InstallerException e) {
13650                        Slog.w(TAG, "Failed to free cache", e);
13651                    }
13652
13653                    /*
13654                     * The cache free must have deleted the file we
13655                     * downloaded to install.
13656                     *
13657                     * TODO: fix the "freeCache" call to not delete
13658                     *       the file we care about.
13659                     */
13660                    if (pkgLite.recommendedInstallLocation
13661                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13662                        pkgLite.recommendedInstallLocation
13663                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13664                    }
13665                }
13666            }
13667
13668            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13669                int loc = pkgLite.recommendedInstallLocation;
13670                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13671                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13672                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13673                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13674                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13675                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13676                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13677                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13678                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13679                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13680                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13681                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13682                } else {
13683                    // Override with defaults if needed.
13684                    loc = installLocationPolicy(pkgLite);
13685                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13686                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13687                    } else if (!onSd && !onInt) {
13688                        // Override install location with flags
13689                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13690                            // Set the flag to install on external media.
13691                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13692                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13693                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13694                            if (DEBUG_EPHEMERAL) {
13695                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13696                            }
13697                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13698                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13699                                    |PackageManager.INSTALL_INTERNAL);
13700                        } else {
13701                            // Make sure the flag for installing on external
13702                            // media is unset
13703                            installFlags |= PackageManager.INSTALL_INTERNAL;
13704                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13705                        }
13706                    }
13707                }
13708            }
13709
13710            final InstallArgs args = createInstallArgs(this);
13711            mArgs = args;
13712
13713            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13714                // TODO: http://b/22976637
13715                // Apps installed for "all" users use the device owner to verify the app
13716                UserHandle verifierUser = getUser();
13717                if (verifierUser == UserHandle.ALL) {
13718                    verifierUser = UserHandle.SYSTEM;
13719                }
13720
13721                /*
13722                 * Determine if we have any installed package verifiers. If we
13723                 * do, then we'll defer to them to verify the packages.
13724                 */
13725                final int requiredUid = mRequiredVerifierPackage == null ? -1
13726                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13727                                verifierUser.getIdentifier());
13728                if (!origin.existing && requiredUid != -1
13729                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13730                    final Intent verification = new Intent(
13731                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13732                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13733                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13734                            PACKAGE_MIME_TYPE);
13735                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13736
13737                    // Query all live verifiers based on current user state
13738                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13739                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13740
13741                    if (DEBUG_VERIFY) {
13742                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13743                                + verification.toString() + " with " + pkgLite.verifiers.length
13744                                + " optional verifiers");
13745                    }
13746
13747                    final int verificationId = mPendingVerificationToken++;
13748
13749                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13750
13751                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13752                            installerPackageName);
13753
13754                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13755                            installFlags);
13756
13757                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13758                            pkgLite.packageName);
13759
13760                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13761                            pkgLite.versionCode);
13762
13763                    if (verificationInfo != null) {
13764                        if (verificationInfo.originatingUri != null) {
13765                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13766                                    verificationInfo.originatingUri);
13767                        }
13768                        if (verificationInfo.referrer != null) {
13769                            verification.putExtra(Intent.EXTRA_REFERRER,
13770                                    verificationInfo.referrer);
13771                        }
13772                        if (verificationInfo.originatingUid >= 0) {
13773                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13774                                    verificationInfo.originatingUid);
13775                        }
13776                        if (verificationInfo.installerUid >= 0) {
13777                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13778                                    verificationInfo.installerUid);
13779                        }
13780                    }
13781
13782                    final PackageVerificationState verificationState = new PackageVerificationState(
13783                            requiredUid, args);
13784
13785                    mPendingVerification.append(verificationId, verificationState);
13786
13787                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13788                            receivers, verificationState);
13789
13790                    /*
13791                     * If any sufficient verifiers were listed in the package
13792                     * manifest, attempt to ask them.
13793                     */
13794                    if (sufficientVerifiers != null) {
13795                        final int N = sufficientVerifiers.size();
13796                        if (N == 0) {
13797                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13798                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13799                        } else {
13800                            for (int i = 0; i < N; i++) {
13801                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13802
13803                                final Intent sufficientIntent = new Intent(verification);
13804                                sufficientIntent.setComponent(verifierComponent);
13805                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13806                            }
13807                        }
13808                    }
13809
13810                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13811                            mRequiredVerifierPackage, receivers);
13812                    if (ret == PackageManager.INSTALL_SUCCEEDED
13813                            && mRequiredVerifierPackage != null) {
13814                        Trace.asyncTraceBegin(
13815                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13816                        /*
13817                         * Send the intent to the required verification agent,
13818                         * but only start the verification timeout after the
13819                         * target BroadcastReceivers have run.
13820                         */
13821                        verification.setComponent(requiredVerifierComponent);
13822                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13823                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13824                                new BroadcastReceiver() {
13825                                    @Override
13826                                    public void onReceive(Context context, Intent intent) {
13827                                        final Message msg = mHandler
13828                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13829                                        msg.arg1 = verificationId;
13830                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13831                                    }
13832                                }, null, 0, null, null);
13833
13834                        /*
13835                         * We don't want the copy to proceed until verification
13836                         * succeeds, so null out this field.
13837                         */
13838                        mArgs = null;
13839                    }
13840                } else {
13841                    /*
13842                     * No package verification is enabled, so immediately start
13843                     * the remote call to initiate copy using temporary file.
13844                     */
13845                    ret = args.copyApk(mContainerService, true);
13846                }
13847            }
13848
13849            mRet = ret;
13850        }
13851
13852        @Override
13853        void handleReturnCode() {
13854            // If mArgs is null, then MCS couldn't be reached. When it
13855            // reconnects, it will try again to install. At that point, this
13856            // will succeed.
13857            if (mArgs != null) {
13858                processPendingInstall(mArgs, mRet);
13859            }
13860        }
13861
13862        @Override
13863        void handleServiceError() {
13864            mArgs = createInstallArgs(this);
13865            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13866        }
13867
13868        public boolean isForwardLocked() {
13869            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13870        }
13871    }
13872
13873    /**
13874     * Used during creation of InstallArgs
13875     *
13876     * @param installFlags package installation flags
13877     * @return true if should be installed on external storage
13878     */
13879    private static boolean installOnExternalAsec(int installFlags) {
13880        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13881            return false;
13882        }
13883        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13884            return true;
13885        }
13886        return false;
13887    }
13888
13889    /**
13890     * Used during creation of InstallArgs
13891     *
13892     * @param installFlags package installation flags
13893     * @return true if should be installed as forward locked
13894     */
13895    private static boolean installForwardLocked(int installFlags) {
13896        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13897    }
13898
13899    private InstallArgs createInstallArgs(InstallParams params) {
13900        if (params.move != null) {
13901            return new MoveInstallArgs(params);
13902        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13903            return new AsecInstallArgs(params);
13904        } else {
13905            return new FileInstallArgs(params);
13906        }
13907    }
13908
13909    /**
13910     * Create args that describe an existing installed package. Typically used
13911     * when cleaning up old installs, or used as a move source.
13912     */
13913    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13914            String resourcePath, String[] instructionSets) {
13915        final boolean isInAsec;
13916        if (installOnExternalAsec(installFlags)) {
13917            /* Apps on SD card are always in ASEC containers. */
13918            isInAsec = true;
13919        } else if (installForwardLocked(installFlags)
13920                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13921            /*
13922             * Forward-locked apps are only in ASEC containers if they're the
13923             * new style
13924             */
13925            isInAsec = true;
13926        } else {
13927            isInAsec = false;
13928        }
13929
13930        if (isInAsec) {
13931            return new AsecInstallArgs(codePath, instructionSets,
13932                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13933        } else {
13934            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13935        }
13936    }
13937
13938    static abstract class InstallArgs {
13939        /** @see InstallParams#origin */
13940        final OriginInfo origin;
13941        /** @see InstallParams#move */
13942        final MoveInfo move;
13943
13944        final IPackageInstallObserver2 observer;
13945        // Always refers to PackageManager flags only
13946        final int installFlags;
13947        final String installerPackageName;
13948        final String volumeUuid;
13949        final UserHandle user;
13950        final String abiOverride;
13951        final String[] installGrantPermissions;
13952        /** If non-null, drop an async trace when the install completes */
13953        final String traceMethod;
13954        final int traceCookie;
13955        final Certificate[][] certificates;
13956        final int installReason;
13957
13958        // The list of instruction sets supported by this app. This is currently
13959        // only used during the rmdex() phase to clean up resources. We can get rid of this
13960        // if we move dex files under the common app path.
13961        /* nullable */ String[] instructionSets;
13962
13963        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13964                int installFlags, String installerPackageName, String volumeUuid,
13965                UserHandle user, String[] instructionSets,
13966                String abiOverride, String[] installGrantPermissions,
13967                String traceMethod, int traceCookie, Certificate[][] certificates,
13968                int installReason) {
13969            this.origin = origin;
13970            this.move = move;
13971            this.installFlags = installFlags;
13972            this.observer = observer;
13973            this.installerPackageName = installerPackageName;
13974            this.volumeUuid = volumeUuid;
13975            this.user = user;
13976            this.instructionSets = instructionSets;
13977            this.abiOverride = abiOverride;
13978            this.installGrantPermissions = installGrantPermissions;
13979            this.traceMethod = traceMethod;
13980            this.traceCookie = traceCookie;
13981            this.certificates = certificates;
13982            this.installReason = installReason;
13983        }
13984
13985        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13986        abstract int doPreInstall(int status);
13987
13988        /**
13989         * Rename package into final resting place. All paths on the given
13990         * scanned package should be updated to reflect the rename.
13991         */
13992        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13993        abstract int doPostInstall(int status, int uid);
13994
13995        /** @see PackageSettingBase#codePathString */
13996        abstract String getCodePath();
13997        /** @see PackageSettingBase#resourcePathString */
13998        abstract String getResourcePath();
13999
14000        // Need installer lock especially for dex file removal.
14001        abstract void cleanUpResourcesLI();
14002        abstract boolean doPostDeleteLI(boolean delete);
14003
14004        /**
14005         * Called before the source arguments are copied. This is used mostly
14006         * for MoveParams when it needs to read the source file to put it in the
14007         * destination.
14008         */
14009        int doPreCopy() {
14010            return PackageManager.INSTALL_SUCCEEDED;
14011        }
14012
14013        /**
14014         * Called after the source arguments are copied. This is used mostly for
14015         * MoveParams when it needs to read the source file to put it in the
14016         * destination.
14017         */
14018        int doPostCopy(int uid) {
14019            return PackageManager.INSTALL_SUCCEEDED;
14020        }
14021
14022        protected boolean isFwdLocked() {
14023            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14024        }
14025
14026        protected boolean isExternalAsec() {
14027            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14028        }
14029
14030        protected boolean isEphemeral() {
14031            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14032        }
14033
14034        UserHandle getUser() {
14035            return user;
14036        }
14037    }
14038
14039    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14040        if (!allCodePaths.isEmpty()) {
14041            if (instructionSets == null) {
14042                throw new IllegalStateException("instructionSet == null");
14043            }
14044            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14045            for (String codePath : allCodePaths) {
14046                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14047                    try {
14048                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14049                    } catch (InstallerException ignored) {
14050                    }
14051                }
14052            }
14053        }
14054    }
14055
14056    /**
14057     * Logic to handle installation of non-ASEC applications, including copying
14058     * and renaming logic.
14059     */
14060    class FileInstallArgs extends InstallArgs {
14061        private File codeFile;
14062        private File resourceFile;
14063
14064        // Example topology:
14065        // /data/app/com.example/base.apk
14066        // /data/app/com.example/split_foo.apk
14067        // /data/app/com.example/lib/arm/libfoo.so
14068        // /data/app/com.example/lib/arm64/libfoo.so
14069        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14070
14071        /** New install */
14072        FileInstallArgs(InstallParams params) {
14073            super(params.origin, params.move, params.observer, params.installFlags,
14074                    params.installerPackageName, params.volumeUuid,
14075                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14076                    params.grantedRuntimePermissions,
14077                    params.traceMethod, params.traceCookie, params.certificates,
14078                    params.installReason);
14079            if (isFwdLocked()) {
14080                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14081            }
14082        }
14083
14084        /** Existing install */
14085        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14086            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14087                    null, null, null, 0, null /*certificates*/,
14088                    PackageManager.INSTALL_REASON_UNKNOWN);
14089            this.codeFile = (codePath != null) ? new File(codePath) : null;
14090            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14091        }
14092
14093        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14094            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14095            try {
14096                return doCopyApk(imcs, temp);
14097            } finally {
14098                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14099            }
14100        }
14101
14102        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14103            if (origin.staged) {
14104                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14105                codeFile = origin.file;
14106                resourceFile = origin.file;
14107                return PackageManager.INSTALL_SUCCEEDED;
14108            }
14109
14110            try {
14111                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14112                final File tempDir =
14113                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14114                codeFile = tempDir;
14115                resourceFile = tempDir;
14116            } catch (IOException e) {
14117                Slog.w(TAG, "Failed to create copy file: " + e);
14118                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14119            }
14120
14121            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14122                @Override
14123                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14124                    if (!FileUtils.isValidExtFilename(name)) {
14125                        throw new IllegalArgumentException("Invalid filename: " + name);
14126                    }
14127                    try {
14128                        final File file = new File(codeFile, name);
14129                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14130                                O_RDWR | O_CREAT, 0644);
14131                        Os.chmod(file.getAbsolutePath(), 0644);
14132                        return new ParcelFileDescriptor(fd);
14133                    } catch (ErrnoException e) {
14134                        throw new RemoteException("Failed to open: " + e.getMessage());
14135                    }
14136                }
14137            };
14138
14139            int ret = PackageManager.INSTALL_SUCCEEDED;
14140            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14141            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14142                Slog.e(TAG, "Failed to copy package");
14143                return ret;
14144            }
14145
14146            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14147            NativeLibraryHelper.Handle handle = null;
14148            try {
14149                handle = NativeLibraryHelper.Handle.create(codeFile);
14150                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14151                        abiOverride);
14152            } catch (IOException e) {
14153                Slog.e(TAG, "Copying native libraries failed", e);
14154                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14155            } finally {
14156                IoUtils.closeQuietly(handle);
14157            }
14158
14159            return ret;
14160        }
14161
14162        int doPreInstall(int status) {
14163            if (status != PackageManager.INSTALL_SUCCEEDED) {
14164                cleanUp();
14165            }
14166            return status;
14167        }
14168
14169        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14170            if (status != PackageManager.INSTALL_SUCCEEDED) {
14171                cleanUp();
14172                return false;
14173            }
14174
14175            final File targetDir = codeFile.getParentFile();
14176            final File beforeCodeFile = codeFile;
14177            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14178
14179            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14180            try {
14181                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14182            } catch (ErrnoException e) {
14183                Slog.w(TAG, "Failed to rename", e);
14184                return false;
14185            }
14186
14187            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14188                Slog.w(TAG, "Failed to restorecon");
14189                return false;
14190            }
14191
14192            // Reflect the rename internally
14193            codeFile = afterCodeFile;
14194            resourceFile = afterCodeFile;
14195
14196            // Reflect the rename in scanned details
14197            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14198            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14199                    afterCodeFile, pkg.baseCodePath));
14200            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14201                    afterCodeFile, pkg.splitCodePaths));
14202
14203            // Reflect the rename in app info
14204            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14205            pkg.setApplicationInfoCodePath(pkg.codePath);
14206            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14207            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14208            pkg.setApplicationInfoResourcePath(pkg.codePath);
14209            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14210            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14211
14212            return true;
14213        }
14214
14215        int doPostInstall(int status, int uid) {
14216            if (status != PackageManager.INSTALL_SUCCEEDED) {
14217                cleanUp();
14218            }
14219            return status;
14220        }
14221
14222        @Override
14223        String getCodePath() {
14224            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14225        }
14226
14227        @Override
14228        String getResourcePath() {
14229            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14230        }
14231
14232        private boolean cleanUp() {
14233            if (codeFile == null || !codeFile.exists()) {
14234                return false;
14235            }
14236
14237            removeCodePathLI(codeFile);
14238
14239            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14240                resourceFile.delete();
14241            }
14242
14243            return true;
14244        }
14245
14246        void cleanUpResourcesLI() {
14247            // Try enumerating all code paths before deleting
14248            List<String> allCodePaths = Collections.EMPTY_LIST;
14249            if (codeFile != null && codeFile.exists()) {
14250                try {
14251                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14252                    allCodePaths = pkg.getAllCodePaths();
14253                } catch (PackageParserException e) {
14254                    // Ignored; we tried our best
14255                }
14256            }
14257
14258            cleanUp();
14259            removeDexFiles(allCodePaths, instructionSets);
14260        }
14261
14262        boolean doPostDeleteLI(boolean delete) {
14263            // XXX err, shouldn't we respect the delete flag?
14264            cleanUpResourcesLI();
14265            return true;
14266        }
14267    }
14268
14269    private boolean isAsecExternal(String cid) {
14270        final String asecPath = PackageHelper.getSdFilesystem(cid);
14271        return !asecPath.startsWith(mAsecInternalPath);
14272    }
14273
14274    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14275            PackageManagerException {
14276        if (copyRet < 0) {
14277            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14278                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14279                throw new PackageManagerException(copyRet, message);
14280            }
14281        }
14282    }
14283
14284    /**
14285     * Extract the StorageManagerService "container ID" from the full code path of an
14286     * .apk.
14287     */
14288    static String cidFromCodePath(String fullCodePath) {
14289        int eidx = fullCodePath.lastIndexOf("/");
14290        String subStr1 = fullCodePath.substring(0, eidx);
14291        int sidx = subStr1.lastIndexOf("/");
14292        return subStr1.substring(sidx+1, eidx);
14293    }
14294
14295    /**
14296     * Logic to handle installation of ASEC applications, including copying and
14297     * renaming logic.
14298     */
14299    class AsecInstallArgs extends InstallArgs {
14300        static final String RES_FILE_NAME = "pkg.apk";
14301        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14302
14303        String cid;
14304        String packagePath;
14305        String resourcePath;
14306
14307        /** New install */
14308        AsecInstallArgs(InstallParams params) {
14309            super(params.origin, params.move, params.observer, params.installFlags,
14310                    params.installerPackageName, params.volumeUuid,
14311                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14312                    params.grantedRuntimePermissions,
14313                    params.traceMethod, params.traceCookie, params.certificates,
14314                    params.installReason);
14315        }
14316
14317        /** Existing install */
14318        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14319                        boolean isExternal, boolean isForwardLocked) {
14320            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14321                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14322                    instructionSets, null, null, null, 0, null /*certificates*/,
14323                    PackageManager.INSTALL_REASON_UNKNOWN);
14324            // Hackily pretend we're still looking at a full code path
14325            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14326                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14327            }
14328
14329            // Extract cid from fullCodePath
14330            int eidx = fullCodePath.lastIndexOf("/");
14331            String subStr1 = fullCodePath.substring(0, eidx);
14332            int sidx = subStr1.lastIndexOf("/");
14333            cid = subStr1.substring(sidx+1, eidx);
14334            setMountPath(subStr1);
14335        }
14336
14337        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14338            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14339                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14340                    instructionSets, null, null, null, 0, null /*certificates*/,
14341                    PackageManager.INSTALL_REASON_UNKNOWN);
14342            this.cid = cid;
14343            setMountPath(PackageHelper.getSdDir(cid));
14344        }
14345
14346        void createCopyFile() {
14347            cid = mInstallerService.allocateExternalStageCidLegacy();
14348        }
14349
14350        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14351            if (origin.staged && origin.cid != null) {
14352                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14353                cid = origin.cid;
14354                setMountPath(PackageHelper.getSdDir(cid));
14355                return PackageManager.INSTALL_SUCCEEDED;
14356            }
14357
14358            if (temp) {
14359                createCopyFile();
14360            } else {
14361                /*
14362                 * Pre-emptively destroy the container since it's destroyed if
14363                 * copying fails due to it existing anyway.
14364                 */
14365                PackageHelper.destroySdDir(cid);
14366            }
14367
14368            final String newMountPath = imcs.copyPackageToContainer(
14369                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14370                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14371
14372            if (newMountPath != null) {
14373                setMountPath(newMountPath);
14374                return PackageManager.INSTALL_SUCCEEDED;
14375            } else {
14376                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14377            }
14378        }
14379
14380        @Override
14381        String getCodePath() {
14382            return packagePath;
14383        }
14384
14385        @Override
14386        String getResourcePath() {
14387            return resourcePath;
14388        }
14389
14390        int doPreInstall(int status) {
14391            if (status != PackageManager.INSTALL_SUCCEEDED) {
14392                // Destroy container
14393                PackageHelper.destroySdDir(cid);
14394            } else {
14395                boolean mounted = PackageHelper.isContainerMounted(cid);
14396                if (!mounted) {
14397                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14398                            Process.SYSTEM_UID);
14399                    if (newMountPath != null) {
14400                        setMountPath(newMountPath);
14401                    } else {
14402                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14403                    }
14404                }
14405            }
14406            return status;
14407        }
14408
14409        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14410            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14411            String newMountPath = null;
14412            if (PackageHelper.isContainerMounted(cid)) {
14413                // Unmount the container
14414                if (!PackageHelper.unMountSdDir(cid)) {
14415                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14416                    return false;
14417                }
14418            }
14419            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14420                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14421                        " which might be stale. Will try to clean up.");
14422                // Clean up the stale container and proceed to recreate.
14423                if (!PackageHelper.destroySdDir(newCacheId)) {
14424                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14425                    return false;
14426                }
14427                // Successfully cleaned up stale container. Try to rename again.
14428                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14429                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14430                            + " inspite of cleaning it up.");
14431                    return false;
14432                }
14433            }
14434            if (!PackageHelper.isContainerMounted(newCacheId)) {
14435                Slog.w(TAG, "Mounting container " + newCacheId);
14436                newMountPath = PackageHelper.mountSdDir(newCacheId,
14437                        getEncryptKey(), Process.SYSTEM_UID);
14438            } else {
14439                newMountPath = PackageHelper.getSdDir(newCacheId);
14440            }
14441            if (newMountPath == null) {
14442                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14443                return false;
14444            }
14445            Log.i(TAG, "Succesfully renamed " + cid +
14446                    " to " + newCacheId +
14447                    " at new path: " + newMountPath);
14448            cid = newCacheId;
14449
14450            final File beforeCodeFile = new File(packagePath);
14451            setMountPath(newMountPath);
14452            final File afterCodeFile = new File(packagePath);
14453
14454            // Reflect the rename in scanned details
14455            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14456            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14457                    afterCodeFile, pkg.baseCodePath));
14458            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14459                    afterCodeFile, pkg.splitCodePaths));
14460
14461            // Reflect the rename in app info
14462            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14463            pkg.setApplicationInfoCodePath(pkg.codePath);
14464            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14465            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14466            pkg.setApplicationInfoResourcePath(pkg.codePath);
14467            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14468            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14469
14470            return true;
14471        }
14472
14473        private void setMountPath(String mountPath) {
14474            final File mountFile = new File(mountPath);
14475
14476            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14477            if (monolithicFile.exists()) {
14478                packagePath = monolithicFile.getAbsolutePath();
14479                if (isFwdLocked()) {
14480                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14481                } else {
14482                    resourcePath = packagePath;
14483                }
14484            } else {
14485                packagePath = mountFile.getAbsolutePath();
14486                resourcePath = packagePath;
14487            }
14488        }
14489
14490        int doPostInstall(int status, int uid) {
14491            if (status != PackageManager.INSTALL_SUCCEEDED) {
14492                cleanUp();
14493            } else {
14494                final int groupOwner;
14495                final String protectedFile;
14496                if (isFwdLocked()) {
14497                    groupOwner = UserHandle.getSharedAppGid(uid);
14498                    protectedFile = RES_FILE_NAME;
14499                } else {
14500                    groupOwner = -1;
14501                    protectedFile = null;
14502                }
14503
14504                if (uid < Process.FIRST_APPLICATION_UID
14505                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14506                    Slog.e(TAG, "Failed to finalize " + cid);
14507                    PackageHelper.destroySdDir(cid);
14508                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14509                }
14510
14511                boolean mounted = PackageHelper.isContainerMounted(cid);
14512                if (!mounted) {
14513                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14514                }
14515            }
14516            return status;
14517        }
14518
14519        private void cleanUp() {
14520            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14521
14522            // Destroy secure container
14523            PackageHelper.destroySdDir(cid);
14524        }
14525
14526        private List<String> getAllCodePaths() {
14527            final File codeFile = new File(getCodePath());
14528            if (codeFile != null && codeFile.exists()) {
14529                try {
14530                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14531                    return pkg.getAllCodePaths();
14532                } catch (PackageParserException e) {
14533                    // Ignored; we tried our best
14534                }
14535            }
14536            return Collections.EMPTY_LIST;
14537        }
14538
14539        void cleanUpResourcesLI() {
14540            // Enumerate all code paths before deleting
14541            cleanUpResourcesLI(getAllCodePaths());
14542        }
14543
14544        private void cleanUpResourcesLI(List<String> allCodePaths) {
14545            cleanUp();
14546            removeDexFiles(allCodePaths, instructionSets);
14547        }
14548
14549        String getPackageName() {
14550            return getAsecPackageName(cid);
14551        }
14552
14553        boolean doPostDeleteLI(boolean delete) {
14554            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14555            final List<String> allCodePaths = getAllCodePaths();
14556            boolean mounted = PackageHelper.isContainerMounted(cid);
14557            if (mounted) {
14558                // Unmount first
14559                if (PackageHelper.unMountSdDir(cid)) {
14560                    mounted = false;
14561                }
14562            }
14563            if (!mounted && delete) {
14564                cleanUpResourcesLI(allCodePaths);
14565            }
14566            return !mounted;
14567        }
14568
14569        @Override
14570        int doPreCopy() {
14571            if (isFwdLocked()) {
14572                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14573                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14574                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14575                }
14576            }
14577
14578            return PackageManager.INSTALL_SUCCEEDED;
14579        }
14580
14581        @Override
14582        int doPostCopy(int uid) {
14583            if (isFwdLocked()) {
14584                if (uid < Process.FIRST_APPLICATION_UID
14585                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14586                                RES_FILE_NAME)) {
14587                    Slog.e(TAG, "Failed to finalize " + cid);
14588                    PackageHelper.destroySdDir(cid);
14589                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14590                }
14591            }
14592
14593            return PackageManager.INSTALL_SUCCEEDED;
14594        }
14595    }
14596
14597    /**
14598     * Logic to handle movement of existing installed applications.
14599     */
14600    class MoveInstallArgs extends InstallArgs {
14601        private File codeFile;
14602        private File resourceFile;
14603
14604        /** New install */
14605        MoveInstallArgs(InstallParams params) {
14606            super(params.origin, params.move, params.observer, params.installFlags,
14607                    params.installerPackageName, params.volumeUuid,
14608                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14609                    params.grantedRuntimePermissions,
14610                    params.traceMethod, params.traceCookie, params.certificates,
14611                    params.installReason);
14612        }
14613
14614        int copyApk(IMediaContainerService imcs, boolean temp) {
14615            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14616                    + move.fromUuid + " to " + move.toUuid);
14617            synchronized (mInstaller) {
14618                try {
14619                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14620                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14621                } catch (InstallerException e) {
14622                    Slog.w(TAG, "Failed to move app", e);
14623                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14624                }
14625            }
14626
14627            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14628            resourceFile = codeFile;
14629            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14630
14631            return PackageManager.INSTALL_SUCCEEDED;
14632        }
14633
14634        int doPreInstall(int status) {
14635            if (status != PackageManager.INSTALL_SUCCEEDED) {
14636                cleanUp(move.toUuid);
14637            }
14638            return status;
14639        }
14640
14641        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14642            if (status != PackageManager.INSTALL_SUCCEEDED) {
14643                cleanUp(move.toUuid);
14644                return false;
14645            }
14646
14647            // Reflect the move in app info
14648            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14649            pkg.setApplicationInfoCodePath(pkg.codePath);
14650            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14651            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14652            pkg.setApplicationInfoResourcePath(pkg.codePath);
14653            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14654            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14655
14656            return true;
14657        }
14658
14659        int doPostInstall(int status, int uid) {
14660            if (status == PackageManager.INSTALL_SUCCEEDED) {
14661                cleanUp(move.fromUuid);
14662            } else {
14663                cleanUp(move.toUuid);
14664            }
14665            return status;
14666        }
14667
14668        @Override
14669        String getCodePath() {
14670            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14671        }
14672
14673        @Override
14674        String getResourcePath() {
14675            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14676        }
14677
14678        private boolean cleanUp(String volumeUuid) {
14679            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14680                    move.dataAppName);
14681            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14682            final int[] userIds = sUserManager.getUserIds();
14683            synchronized (mInstallLock) {
14684                // Clean up both app data and code
14685                // All package moves are frozen until finished
14686                for (int userId : userIds) {
14687                    try {
14688                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14689                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14690                    } catch (InstallerException e) {
14691                        Slog.w(TAG, String.valueOf(e));
14692                    }
14693                }
14694                removeCodePathLI(codeFile);
14695            }
14696            return true;
14697        }
14698
14699        void cleanUpResourcesLI() {
14700            throw new UnsupportedOperationException();
14701        }
14702
14703        boolean doPostDeleteLI(boolean delete) {
14704            throw new UnsupportedOperationException();
14705        }
14706    }
14707
14708    static String getAsecPackageName(String packageCid) {
14709        int idx = packageCid.lastIndexOf("-");
14710        if (idx == -1) {
14711            return packageCid;
14712        }
14713        return packageCid.substring(0, idx);
14714    }
14715
14716    // Utility method used to create code paths based on package name and available index.
14717    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14718        String idxStr = "";
14719        int idx = 1;
14720        // Fall back to default value of idx=1 if prefix is not
14721        // part of oldCodePath
14722        if (oldCodePath != null) {
14723            String subStr = oldCodePath;
14724            // Drop the suffix right away
14725            if (suffix != null && subStr.endsWith(suffix)) {
14726                subStr = subStr.substring(0, subStr.length() - suffix.length());
14727            }
14728            // If oldCodePath already contains prefix find out the
14729            // ending index to either increment or decrement.
14730            int sidx = subStr.lastIndexOf(prefix);
14731            if (sidx != -1) {
14732                subStr = subStr.substring(sidx + prefix.length());
14733                if (subStr != null) {
14734                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14735                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14736                    }
14737                    try {
14738                        idx = Integer.parseInt(subStr);
14739                        if (idx <= 1) {
14740                            idx++;
14741                        } else {
14742                            idx--;
14743                        }
14744                    } catch(NumberFormatException e) {
14745                    }
14746                }
14747            }
14748        }
14749        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14750        return prefix + idxStr;
14751    }
14752
14753    private File getNextCodePath(File targetDir, String packageName) {
14754        File result;
14755        SecureRandom random = new SecureRandom();
14756        byte[] bytes = new byte[16];
14757        do {
14758            random.nextBytes(bytes);
14759            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14760            result = new File(targetDir, packageName + "-" + suffix);
14761        } while (result.exists());
14762        return result;
14763    }
14764
14765    // Utility method that returns the relative package path with respect
14766    // to the installation directory. Like say for /data/data/com.test-1.apk
14767    // string com.test-1 is returned.
14768    static String deriveCodePathName(String codePath) {
14769        if (codePath == null) {
14770            return null;
14771        }
14772        final File codeFile = new File(codePath);
14773        final String name = codeFile.getName();
14774        if (codeFile.isDirectory()) {
14775            return name;
14776        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14777            final int lastDot = name.lastIndexOf('.');
14778            return name.substring(0, lastDot);
14779        } else {
14780            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14781            return null;
14782        }
14783    }
14784
14785    static class PackageInstalledInfo {
14786        String name;
14787        int uid;
14788        // The set of users that originally had this package installed.
14789        int[] origUsers;
14790        // The set of users that now have this package installed.
14791        int[] newUsers;
14792        PackageParser.Package pkg;
14793        int returnCode;
14794        String returnMsg;
14795        PackageRemovedInfo removedInfo;
14796        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14797
14798        public void setError(int code, String msg) {
14799            setReturnCode(code);
14800            setReturnMessage(msg);
14801            Slog.w(TAG, msg);
14802        }
14803
14804        public void setError(String msg, PackageParserException e) {
14805            setReturnCode(e.error);
14806            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14807            Slog.w(TAG, msg, e);
14808        }
14809
14810        public void setError(String msg, PackageManagerException e) {
14811            returnCode = e.error;
14812            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14813            Slog.w(TAG, msg, e);
14814        }
14815
14816        public void setReturnCode(int returnCode) {
14817            this.returnCode = returnCode;
14818            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14819            for (int i = 0; i < childCount; i++) {
14820                addedChildPackages.valueAt(i).returnCode = returnCode;
14821            }
14822        }
14823
14824        private void setReturnMessage(String returnMsg) {
14825            this.returnMsg = returnMsg;
14826            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14827            for (int i = 0; i < childCount; i++) {
14828                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14829            }
14830        }
14831
14832        // In some error cases we want to convey more info back to the observer
14833        String origPackage;
14834        String origPermission;
14835    }
14836
14837    /*
14838     * Install a non-existing package.
14839     */
14840    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14841            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14842            PackageInstalledInfo res, int installReason) {
14843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14844
14845        // Remember this for later, in case we need to rollback this install
14846        String pkgName = pkg.packageName;
14847
14848        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14849
14850        synchronized(mPackages) {
14851            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14852            if (renamedPackage != null) {
14853                // A package with the same name is already installed, though
14854                // it has been renamed to an older name.  The package we
14855                // are trying to install should be installed as an update to
14856                // the existing one, but that has not been requested, so bail.
14857                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14858                        + " without first uninstalling package running as "
14859                        + renamedPackage);
14860                return;
14861            }
14862            if (mPackages.containsKey(pkgName)) {
14863                // Don't allow installation over an existing package with the same name.
14864                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14865                        + " without first uninstalling.");
14866                return;
14867            }
14868        }
14869
14870        try {
14871            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14872                    System.currentTimeMillis(), user);
14873
14874            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
14875
14876            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14877                prepareAppDataAfterInstallLIF(newPackage);
14878
14879            } else {
14880                // Remove package from internal structures, but keep around any
14881                // data that might have already existed
14882                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14883                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14884            }
14885        } catch (PackageManagerException e) {
14886            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14887        }
14888
14889        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14890    }
14891
14892    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14893        // Can't rotate keys during boot or if sharedUser.
14894        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14895                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14896            return false;
14897        }
14898        // app is using upgradeKeySets; make sure all are valid
14899        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14900        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14901        for (int i = 0; i < upgradeKeySets.length; i++) {
14902            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14903                Slog.wtf(TAG, "Package "
14904                         + (oldPs.name != null ? oldPs.name : "<null>")
14905                         + " contains upgrade-key-set reference to unknown key-set: "
14906                         + upgradeKeySets[i]
14907                         + " reverting to signatures check.");
14908                return false;
14909            }
14910        }
14911        return true;
14912    }
14913
14914    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14915        // Upgrade keysets are being used.  Determine if new package has a superset of the
14916        // required keys.
14917        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14918        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14919        for (int i = 0; i < upgradeKeySets.length; i++) {
14920            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14921            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14922                return true;
14923            }
14924        }
14925        return false;
14926    }
14927
14928    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14929        try (DigestInputStream digestStream =
14930                new DigestInputStream(new FileInputStream(file), digest)) {
14931            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14932        }
14933    }
14934
14935    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14936            UserHandle user, String installerPackageName, PackageInstalledInfo res,
14937            int installReason) {
14938        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14939
14940        final PackageParser.Package oldPackage;
14941        final String pkgName = pkg.packageName;
14942        final int[] allUsers;
14943        final int[] installedUsers;
14944
14945        synchronized(mPackages) {
14946            oldPackage = mPackages.get(pkgName);
14947            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14948
14949            // don't allow upgrade to target a release SDK from a pre-release SDK
14950            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14951                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14952            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14953                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14954            if (oldTargetsPreRelease
14955                    && !newTargetsPreRelease
14956                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14957                Slog.w(TAG, "Can't install package targeting released sdk");
14958                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14959                return;
14960            }
14961
14962            // don't allow an upgrade from full to ephemeral
14963            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14964            if (isEphemeral && !oldIsEphemeral) {
14965                // can't downgrade from full to ephemeral
14966                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14967                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14968                return;
14969            }
14970
14971            // verify signatures are valid
14972            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14973            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14974                if (!checkUpgradeKeySetLP(ps, pkg)) {
14975                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14976                            "New package not signed by keys specified by upgrade-keysets: "
14977                                    + pkgName);
14978                    return;
14979                }
14980            } else {
14981                // default to original signature matching
14982                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14983                        != PackageManager.SIGNATURE_MATCH) {
14984                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14985                            "New package has a different signature: " + pkgName);
14986                    return;
14987                }
14988            }
14989
14990            // don't allow a system upgrade unless the upgrade hash matches
14991            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14992                byte[] digestBytes = null;
14993                try {
14994                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14995                    updateDigest(digest, new File(pkg.baseCodePath));
14996                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14997                        for (String path : pkg.splitCodePaths) {
14998                            updateDigest(digest, new File(path));
14999                        }
15000                    }
15001                    digestBytes = digest.digest();
15002                } catch (NoSuchAlgorithmException | IOException e) {
15003                    res.setError(INSTALL_FAILED_INVALID_APK,
15004                            "Could not compute hash: " + pkgName);
15005                    return;
15006                }
15007                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15008                    res.setError(INSTALL_FAILED_INVALID_APK,
15009                            "New package fails restrict-update check: " + pkgName);
15010                    return;
15011                }
15012                // retain upgrade restriction
15013                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15014            }
15015
15016            // Check for shared user id changes
15017            String invalidPackageName =
15018                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15019            if (invalidPackageName != null) {
15020                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15021                        "Package " + invalidPackageName + " tried to change user "
15022                                + oldPackage.mSharedUserId);
15023                return;
15024            }
15025
15026            // In case of rollback, remember per-user/profile install state
15027            allUsers = sUserManager.getUserIds();
15028            installedUsers = ps.queryInstalledUsers(allUsers, true);
15029        }
15030
15031        // Update what is removed
15032        res.removedInfo = new PackageRemovedInfo();
15033        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15034        res.removedInfo.removedPackage = oldPackage.packageName;
15035        res.removedInfo.isUpdate = true;
15036        res.removedInfo.origUsers = installedUsers;
15037        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15038        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15039        for (int i = 0; i < installedUsers.length; i++) {
15040            final int userId = installedUsers[i];
15041            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15042        }
15043
15044        final int childCount = (oldPackage.childPackages != null)
15045                ? oldPackage.childPackages.size() : 0;
15046        for (int i = 0; i < childCount; i++) {
15047            boolean childPackageUpdated = false;
15048            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15049            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15050            if (res.addedChildPackages != null) {
15051                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15052                if (childRes != null) {
15053                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15054                    childRes.removedInfo.removedPackage = childPkg.packageName;
15055                    childRes.removedInfo.isUpdate = true;
15056                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15057                    childPackageUpdated = true;
15058                }
15059            }
15060            if (!childPackageUpdated) {
15061                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15062                childRemovedRes.removedPackage = childPkg.packageName;
15063                childRemovedRes.isUpdate = false;
15064                childRemovedRes.dataRemoved = true;
15065                synchronized (mPackages) {
15066                    if (childPs != null) {
15067                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15068                    }
15069                }
15070                if (res.removedInfo.removedChildPackages == null) {
15071                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15072                }
15073                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15074            }
15075        }
15076
15077        boolean sysPkg = (isSystemApp(oldPackage));
15078        if (sysPkg) {
15079            // Set the system/privileged flags as needed
15080            final boolean privileged =
15081                    (oldPackage.applicationInfo.privateFlags
15082                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15083            final int systemPolicyFlags = policyFlags
15084                    | PackageParser.PARSE_IS_SYSTEM
15085                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15086
15087            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15088                    user, allUsers, installerPackageName, res, installReason);
15089        } else {
15090            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15091                    user, allUsers, installerPackageName, res, installReason);
15092        }
15093    }
15094
15095    public List<String> getPreviousCodePaths(String packageName) {
15096        final PackageSetting ps = mSettings.mPackages.get(packageName);
15097        final List<String> result = new ArrayList<String>();
15098        if (ps != null && ps.oldCodePaths != null) {
15099            result.addAll(ps.oldCodePaths);
15100        }
15101        return result;
15102    }
15103
15104    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15105            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15106            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15107            int installReason) {
15108        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15109                + deletedPackage);
15110
15111        String pkgName = deletedPackage.packageName;
15112        boolean deletedPkg = true;
15113        boolean addedPkg = false;
15114        boolean updatedSettings = false;
15115        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15116        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15117                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15118
15119        final long origUpdateTime = (pkg.mExtras != null)
15120                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15121
15122        // First delete the existing package while retaining the data directory
15123        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15124                res.removedInfo, true, pkg)) {
15125            // If the existing package wasn't successfully deleted
15126            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15127            deletedPkg = false;
15128        } else {
15129            // Successfully deleted the old package; proceed with replace.
15130
15131            // If deleted package lived in a container, give users a chance to
15132            // relinquish resources before killing.
15133            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15134                if (DEBUG_INSTALL) {
15135                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15136                }
15137                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15138                final ArrayList<String> pkgList = new ArrayList<String>(1);
15139                pkgList.add(deletedPackage.applicationInfo.packageName);
15140                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15141            }
15142
15143            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15144                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15145            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15146
15147            try {
15148                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15149                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15150                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15151                        installReason);
15152
15153                // Update the in-memory copy of the previous code paths.
15154                PackageSetting ps = mSettings.mPackages.get(pkgName);
15155                if (!killApp) {
15156                    if (ps.oldCodePaths == null) {
15157                        ps.oldCodePaths = new ArraySet<>();
15158                    }
15159                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15160                    if (deletedPackage.splitCodePaths != null) {
15161                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15162                    }
15163                } else {
15164                    ps.oldCodePaths = null;
15165                }
15166                if (ps.childPackageNames != null) {
15167                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15168                        final String childPkgName = ps.childPackageNames.get(i);
15169                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15170                        childPs.oldCodePaths = ps.oldCodePaths;
15171                    }
15172                }
15173                prepareAppDataAfterInstallLIF(newPackage);
15174                addedPkg = true;
15175            } catch (PackageManagerException e) {
15176                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15177            }
15178        }
15179
15180        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15181            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15182
15183            // Revert all internal state mutations and added folders for the failed install
15184            if (addedPkg) {
15185                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15186                        res.removedInfo, true, null);
15187            }
15188
15189            // Restore the old package
15190            if (deletedPkg) {
15191                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15192                File restoreFile = new File(deletedPackage.codePath);
15193                // Parse old package
15194                boolean oldExternal = isExternal(deletedPackage);
15195                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15196                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15197                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15198                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15199                try {
15200                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15201                            null);
15202                } catch (PackageManagerException e) {
15203                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15204                            + e.getMessage());
15205                    return;
15206                }
15207
15208                synchronized (mPackages) {
15209                    // Ensure the installer package name up to date
15210                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15211
15212                    // Update permissions for restored package
15213                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15214
15215                    mSettings.writeLPr();
15216                }
15217
15218                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15219            }
15220        } else {
15221            synchronized (mPackages) {
15222                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15223                if (ps != null) {
15224                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15225                    if (res.removedInfo.removedChildPackages != null) {
15226                        final int childCount = res.removedInfo.removedChildPackages.size();
15227                        // Iterate in reverse as we may modify the collection
15228                        for (int i = childCount - 1; i >= 0; i--) {
15229                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15230                            if (res.addedChildPackages.containsKey(childPackageName)) {
15231                                res.removedInfo.removedChildPackages.removeAt(i);
15232                            } else {
15233                                PackageRemovedInfo childInfo = res.removedInfo
15234                                        .removedChildPackages.valueAt(i);
15235                                childInfo.removedForAllUsers = mPackages.get(
15236                                        childInfo.removedPackage) == null;
15237                            }
15238                        }
15239                    }
15240                }
15241            }
15242        }
15243    }
15244
15245    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15246            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15247            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15248            int installReason) {
15249        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15250                + ", old=" + deletedPackage);
15251
15252        final boolean disabledSystem;
15253
15254        // Remove existing system package
15255        removePackageLI(deletedPackage, true);
15256
15257        synchronized (mPackages) {
15258            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15259        }
15260        if (!disabledSystem) {
15261            // We didn't need to disable the .apk as a current system package,
15262            // which means we are replacing another update that is already
15263            // installed.  We need to make sure to delete the older one's .apk.
15264            res.removedInfo.args = createInstallArgsForExisting(0,
15265                    deletedPackage.applicationInfo.getCodePath(),
15266                    deletedPackage.applicationInfo.getResourcePath(),
15267                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15268        } else {
15269            res.removedInfo.args = null;
15270        }
15271
15272        // Successfully disabled the old package. Now proceed with re-installation
15273        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15274                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15275        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15276
15277        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15278        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15279                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15280
15281        PackageParser.Package newPackage = null;
15282        try {
15283            // Add the package to the internal data structures
15284            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15285
15286            // Set the update and install times
15287            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15288            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15289                    System.currentTimeMillis());
15290
15291            // Update the package dynamic state if succeeded
15292            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15293                // Now that the install succeeded make sure we remove data
15294                // directories for any child package the update removed.
15295                final int deletedChildCount = (deletedPackage.childPackages != null)
15296                        ? deletedPackage.childPackages.size() : 0;
15297                final int newChildCount = (newPackage.childPackages != null)
15298                        ? newPackage.childPackages.size() : 0;
15299                for (int i = 0; i < deletedChildCount; i++) {
15300                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15301                    boolean childPackageDeleted = true;
15302                    for (int j = 0; j < newChildCount; j++) {
15303                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15304                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15305                            childPackageDeleted = false;
15306                            break;
15307                        }
15308                    }
15309                    if (childPackageDeleted) {
15310                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15311                                deletedChildPkg.packageName);
15312                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15313                            PackageRemovedInfo removedChildRes = res.removedInfo
15314                                    .removedChildPackages.get(deletedChildPkg.packageName);
15315                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15316                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15317                        }
15318                    }
15319                }
15320
15321                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15322                        installReason);
15323                prepareAppDataAfterInstallLIF(newPackage);
15324            }
15325        } catch (PackageManagerException e) {
15326            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15327            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15328        }
15329
15330        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15331            // Re installation failed. Restore old information
15332            // Remove new pkg information
15333            if (newPackage != null) {
15334                removeInstalledPackageLI(newPackage, true);
15335            }
15336            // Add back the old system package
15337            try {
15338                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15339            } catch (PackageManagerException e) {
15340                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15341            }
15342
15343            synchronized (mPackages) {
15344                if (disabledSystem) {
15345                    enableSystemPackageLPw(deletedPackage);
15346                }
15347
15348                // Ensure the installer package name up to date
15349                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15350
15351                // Update permissions for restored package
15352                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15353
15354                mSettings.writeLPr();
15355            }
15356
15357            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15358                    + " after failed upgrade");
15359        }
15360    }
15361
15362    /**
15363     * Checks whether the parent or any of the child packages have a change shared
15364     * user. For a package to be a valid update the shred users of the parent and
15365     * the children should match. We may later support changing child shared users.
15366     * @param oldPkg The updated package.
15367     * @param newPkg The update package.
15368     * @return The shared user that change between the versions.
15369     */
15370    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15371            PackageParser.Package newPkg) {
15372        // Check parent shared user
15373        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15374            return newPkg.packageName;
15375        }
15376        // Check child shared users
15377        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15378        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15379        for (int i = 0; i < newChildCount; i++) {
15380            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15381            // If this child was present, did it have the same shared user?
15382            for (int j = 0; j < oldChildCount; j++) {
15383                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15384                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15385                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15386                    return newChildPkg.packageName;
15387                }
15388            }
15389        }
15390        return null;
15391    }
15392
15393    private void removeNativeBinariesLI(PackageSetting ps) {
15394        // Remove the lib path for the parent package
15395        if (ps != null) {
15396            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15397            // Remove the lib path for the child packages
15398            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15399            for (int i = 0; i < childCount; i++) {
15400                PackageSetting childPs = null;
15401                synchronized (mPackages) {
15402                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15403                }
15404                if (childPs != null) {
15405                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15406                            .legacyNativeLibraryPathString);
15407                }
15408            }
15409        }
15410    }
15411
15412    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15413        // Enable the parent package
15414        mSettings.enableSystemPackageLPw(pkg.packageName);
15415        // Enable the child packages
15416        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15417        for (int i = 0; i < childCount; i++) {
15418            PackageParser.Package childPkg = pkg.childPackages.get(i);
15419            mSettings.enableSystemPackageLPw(childPkg.packageName);
15420        }
15421    }
15422
15423    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15424            PackageParser.Package newPkg) {
15425        // Disable the parent package (parent always replaced)
15426        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15427        // Disable the child packages
15428        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15429        for (int i = 0; i < childCount; i++) {
15430            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15431            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15432            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15433        }
15434        return disabled;
15435    }
15436
15437    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15438            String installerPackageName) {
15439        // Enable the parent package
15440        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15441        // Enable the child packages
15442        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15443        for (int i = 0; i < childCount; i++) {
15444            PackageParser.Package childPkg = pkg.childPackages.get(i);
15445            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15446        }
15447    }
15448
15449    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15450        // Collect all used permissions in the UID
15451        ArraySet<String> usedPermissions = new ArraySet<>();
15452        final int packageCount = su.packages.size();
15453        for (int i = 0; i < packageCount; i++) {
15454            PackageSetting ps = su.packages.valueAt(i);
15455            if (ps.pkg == null) {
15456                continue;
15457            }
15458            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15459            for (int j = 0; j < requestedPermCount; j++) {
15460                String permission = ps.pkg.requestedPermissions.get(j);
15461                BasePermission bp = mSettings.mPermissions.get(permission);
15462                if (bp != null) {
15463                    usedPermissions.add(permission);
15464                }
15465            }
15466        }
15467
15468        PermissionsState permissionsState = su.getPermissionsState();
15469        // Prune install permissions
15470        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15471        final int installPermCount = installPermStates.size();
15472        for (int i = installPermCount - 1; i >= 0;  i--) {
15473            PermissionState permissionState = installPermStates.get(i);
15474            if (!usedPermissions.contains(permissionState.getName())) {
15475                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15476                if (bp != null) {
15477                    permissionsState.revokeInstallPermission(bp);
15478                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15479                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15480                }
15481            }
15482        }
15483
15484        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15485
15486        // Prune runtime permissions
15487        for (int userId : allUserIds) {
15488            List<PermissionState> runtimePermStates = permissionsState
15489                    .getRuntimePermissionStates(userId);
15490            final int runtimePermCount = runtimePermStates.size();
15491            for (int i = runtimePermCount - 1; i >= 0; i--) {
15492                PermissionState permissionState = runtimePermStates.get(i);
15493                if (!usedPermissions.contains(permissionState.getName())) {
15494                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15495                    if (bp != null) {
15496                        permissionsState.revokeRuntimePermission(bp, userId);
15497                        permissionsState.updatePermissionFlags(bp, userId,
15498                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15499                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15500                                runtimePermissionChangedUserIds, userId);
15501                    }
15502                }
15503            }
15504        }
15505
15506        return runtimePermissionChangedUserIds;
15507    }
15508
15509    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15510            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15511        // Update the parent package setting
15512        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15513                res, user, installReason);
15514        // Update the child packages setting
15515        final int childCount = (newPackage.childPackages != null)
15516                ? newPackage.childPackages.size() : 0;
15517        for (int i = 0; i < childCount; i++) {
15518            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15519            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15520            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15521                    childRes.origUsers, childRes, user, installReason);
15522        }
15523    }
15524
15525    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15526            String installerPackageName, int[] allUsers, int[] installedForUsers,
15527            PackageInstalledInfo res, UserHandle user, int installReason) {
15528        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15529
15530        String pkgName = newPackage.packageName;
15531        synchronized (mPackages) {
15532            //write settings. the installStatus will be incomplete at this stage.
15533            //note that the new package setting would have already been
15534            //added to mPackages. It hasn't been persisted yet.
15535            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15536            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15537            mSettings.writeLPr();
15538            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15539        }
15540
15541        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15542        synchronized (mPackages) {
15543            updatePermissionsLPw(newPackage.packageName, newPackage,
15544                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15545                            ? UPDATE_PERMISSIONS_ALL : 0));
15546            // For system-bundled packages, we assume that installing an upgraded version
15547            // of the package implies that the user actually wants to run that new code,
15548            // so we enable the package.
15549            PackageSetting ps = mSettings.mPackages.get(pkgName);
15550            final int userId = user.getIdentifier();
15551            if (ps != null) {
15552                if (isSystemApp(newPackage)) {
15553                    if (DEBUG_INSTALL) {
15554                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15555                    }
15556                    // Enable system package for requested users
15557                    if (res.origUsers != null) {
15558                        for (int origUserId : res.origUsers) {
15559                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15560                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15561                                        origUserId, installerPackageName);
15562                            }
15563                        }
15564                    }
15565                    // Also convey the prior install/uninstall state
15566                    if (allUsers != null && installedForUsers != null) {
15567                        for (int currentUserId : allUsers) {
15568                            final boolean installed = ArrayUtils.contains(
15569                                    installedForUsers, currentUserId);
15570                            if (DEBUG_INSTALL) {
15571                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15572                            }
15573                            ps.setInstalled(installed, currentUserId);
15574                        }
15575                        // these install state changes will be persisted in the
15576                        // upcoming call to mSettings.writeLPr().
15577                    }
15578                }
15579                // It's implied that when a user requests installation, they want the app to be
15580                // installed and enabled.
15581                if (userId != UserHandle.USER_ALL) {
15582                    ps.setInstalled(true, userId);
15583                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15584                }
15585
15586                // When replacing an existing package, preserve the original install reason for all
15587                // users that had the package installed before.
15588                final Set<Integer> previousUserIds = new ArraySet<>();
15589                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15590                    final int installReasonCount = res.removedInfo.installReasons.size();
15591                    for (int i = 0; i < installReasonCount; i++) {
15592                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15593                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15594                        ps.setInstallReason(previousInstallReason, previousUserId);
15595                        previousUserIds.add(previousUserId);
15596                    }
15597                }
15598
15599                // Set install reason for users that are having the package newly installed.
15600                if (userId == UserHandle.USER_ALL) {
15601                    for (int currentUserId : sUserManager.getUserIds()) {
15602                        if (!previousUserIds.contains(currentUserId)) {
15603                            ps.setInstallReason(installReason, currentUserId);
15604                        }
15605                    }
15606                } else if (!previousUserIds.contains(userId)) {
15607                    ps.setInstallReason(installReason, userId);
15608                }
15609            }
15610            res.name = pkgName;
15611            res.uid = newPackage.applicationInfo.uid;
15612            res.pkg = newPackage;
15613            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15614            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15615            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15616            //to update install status
15617            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15618            mSettings.writeLPr();
15619            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15620        }
15621
15622        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15623    }
15624
15625    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15626        try {
15627            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15628            installPackageLI(args, res);
15629        } finally {
15630            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15631        }
15632    }
15633
15634    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15635        final int installFlags = args.installFlags;
15636        final String installerPackageName = args.installerPackageName;
15637        final String volumeUuid = args.volumeUuid;
15638        final File tmpPackageFile = new File(args.getCodePath());
15639        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15640        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15641                || (args.volumeUuid != null));
15642        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15643        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15644        boolean replace = false;
15645        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15646        if (args.move != null) {
15647            // moving a complete application; perform an initial scan on the new install location
15648            scanFlags |= SCAN_INITIAL;
15649        }
15650        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15651            scanFlags |= SCAN_DONT_KILL_APP;
15652        }
15653
15654        // Result object to be returned
15655        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15656
15657        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15658
15659        // Sanity check
15660        if (ephemeral && (forwardLocked || onExternal)) {
15661            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15662                    + " external=" + onExternal);
15663            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15664            return;
15665        }
15666
15667        // Retrieve PackageSettings and parse package
15668        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15669                | PackageParser.PARSE_ENFORCE_CODE
15670                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15671                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15672                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15673                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15674        PackageParser pp = new PackageParser();
15675        pp.setSeparateProcesses(mSeparateProcesses);
15676        pp.setDisplayMetrics(mMetrics);
15677
15678        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15679        final PackageParser.Package pkg;
15680        try {
15681            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15682        } catch (PackageParserException e) {
15683            res.setError("Failed parse during installPackageLI", e);
15684            return;
15685        } finally {
15686            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15687        }
15688
15689        // Ephemeral apps must have target SDK >= O.
15690        // TODO: Update conditional and error message when O gets locked down
15691        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15692            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15693                    "Ephemeral apps must have target SDK version of at least O");
15694            return;
15695        }
15696
15697        // If we are installing a clustered package add results for the children
15698        if (pkg.childPackages != null) {
15699            synchronized (mPackages) {
15700                final int childCount = pkg.childPackages.size();
15701                for (int i = 0; i < childCount; i++) {
15702                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15703                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15704                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15705                    childRes.pkg = childPkg;
15706                    childRes.name = childPkg.packageName;
15707                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15708                    if (childPs != null) {
15709                        childRes.origUsers = childPs.queryInstalledUsers(
15710                                sUserManager.getUserIds(), true);
15711                    }
15712                    if ((mPackages.containsKey(childPkg.packageName))) {
15713                        childRes.removedInfo = new PackageRemovedInfo();
15714                        childRes.removedInfo.removedPackage = childPkg.packageName;
15715                    }
15716                    if (res.addedChildPackages == null) {
15717                        res.addedChildPackages = new ArrayMap<>();
15718                    }
15719                    res.addedChildPackages.put(childPkg.packageName, childRes);
15720                }
15721            }
15722        }
15723
15724        // If package doesn't declare API override, mark that we have an install
15725        // time CPU ABI override.
15726        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15727            pkg.cpuAbiOverride = args.abiOverride;
15728        }
15729
15730        String pkgName = res.name = pkg.packageName;
15731        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15732            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15733                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15734                return;
15735            }
15736        }
15737
15738        try {
15739            // either use what we've been given or parse directly from the APK
15740            if (args.certificates != null) {
15741                try {
15742                    PackageParser.populateCertificates(pkg, args.certificates);
15743                } catch (PackageParserException e) {
15744                    // there was something wrong with the certificates we were given;
15745                    // try to pull them from the APK
15746                    PackageParser.collectCertificates(pkg, parseFlags);
15747                }
15748            } else {
15749                PackageParser.collectCertificates(pkg, parseFlags);
15750            }
15751        } catch (PackageParserException e) {
15752            res.setError("Failed collect during installPackageLI", e);
15753            return;
15754        }
15755
15756        // Get rid of all references to package scan path via parser.
15757        pp = null;
15758        String oldCodePath = null;
15759        boolean systemApp = false;
15760        synchronized (mPackages) {
15761            // Check if installing already existing package
15762            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15763                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15764                if (pkg.mOriginalPackages != null
15765                        && pkg.mOriginalPackages.contains(oldName)
15766                        && mPackages.containsKey(oldName)) {
15767                    // This package is derived from an original package,
15768                    // and this device has been updating from that original
15769                    // name.  We must continue using the original name, so
15770                    // rename the new package here.
15771                    pkg.setPackageName(oldName);
15772                    pkgName = pkg.packageName;
15773                    replace = true;
15774                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15775                            + oldName + " pkgName=" + pkgName);
15776                } else if (mPackages.containsKey(pkgName)) {
15777                    // This package, under its official name, already exists
15778                    // on the device; we should replace it.
15779                    replace = true;
15780                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15781                }
15782
15783                // Child packages are installed through the parent package
15784                if (pkg.parentPackage != null) {
15785                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15786                            "Package " + pkg.packageName + " is child of package "
15787                                    + pkg.parentPackage.parentPackage + ". Child packages "
15788                                    + "can be updated only through the parent package.");
15789                    return;
15790                }
15791
15792                if (replace) {
15793                    // Prevent apps opting out from runtime permissions
15794                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15795                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15796                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15797                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15798                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15799                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15800                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15801                                        + " doesn't support runtime permissions but the old"
15802                                        + " target SDK " + oldTargetSdk + " does.");
15803                        return;
15804                    }
15805
15806                    // Prevent installing of child packages
15807                    if (oldPackage.parentPackage != null) {
15808                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15809                                "Package " + pkg.packageName + " is child of package "
15810                                        + oldPackage.parentPackage + ". Child packages "
15811                                        + "can be updated only through the parent package.");
15812                        return;
15813                    }
15814                }
15815            }
15816
15817            PackageSetting ps = mSettings.mPackages.get(pkgName);
15818            if (ps != null) {
15819                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15820
15821                // Quick sanity check that we're signed correctly if updating;
15822                // we'll check this again later when scanning, but we want to
15823                // bail early here before tripping over redefined permissions.
15824                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15825                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15826                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15827                                + pkg.packageName + " upgrade keys do not match the "
15828                                + "previously installed version");
15829                        return;
15830                    }
15831                } else {
15832                    try {
15833                        verifySignaturesLP(ps, pkg);
15834                    } catch (PackageManagerException e) {
15835                        res.setError(e.error, e.getMessage());
15836                        return;
15837                    }
15838                }
15839
15840                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15841                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15842                    systemApp = (ps.pkg.applicationInfo.flags &
15843                            ApplicationInfo.FLAG_SYSTEM) != 0;
15844                }
15845                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15846            }
15847
15848            // Check whether the newly-scanned package wants to define an already-defined perm
15849            int N = pkg.permissions.size();
15850            for (int i = N-1; i >= 0; i--) {
15851                PackageParser.Permission perm = pkg.permissions.get(i);
15852                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15853                if (bp != null) {
15854                    // If the defining package is signed with our cert, it's okay.  This
15855                    // also includes the "updating the same package" case, of course.
15856                    // "updating same package" could also involve key-rotation.
15857                    final boolean sigsOk;
15858                    if (bp.sourcePackage.equals(pkg.packageName)
15859                            && (bp.packageSetting instanceof PackageSetting)
15860                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15861                                    scanFlags))) {
15862                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15863                    } else {
15864                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15865                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15866                    }
15867                    if (!sigsOk) {
15868                        // If the owning package is the system itself, we log but allow
15869                        // install to proceed; we fail the install on all other permission
15870                        // redefinitions.
15871                        if (!bp.sourcePackage.equals("android")) {
15872                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15873                                    + pkg.packageName + " attempting to redeclare permission "
15874                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15875                            res.origPermission = perm.info.name;
15876                            res.origPackage = bp.sourcePackage;
15877                            return;
15878                        } else {
15879                            Slog.w(TAG, "Package " + pkg.packageName
15880                                    + " attempting to redeclare system permission "
15881                                    + perm.info.name + "; ignoring new declaration");
15882                            pkg.permissions.remove(i);
15883                        }
15884                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15885                        // Prevent apps to change protection level to dangerous from any other
15886                        // type as this would allow a privilege escalation where an app adds a
15887                        // normal/signature permission in other app's group and later redefines
15888                        // it as dangerous leading to the group auto-grant.
15889                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15890                                == PermissionInfo.PROTECTION_DANGEROUS) {
15891                            if (bp != null && !bp.isRuntime()) {
15892                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15893                                        + "non-runtime permission " + perm.info.name
15894                                        + " to runtime; keeping old protection level");
15895                                perm.info.protectionLevel = bp.protectionLevel;
15896                            }
15897                        }
15898                    }
15899                }
15900            }
15901        }
15902
15903        if (systemApp) {
15904            if (onExternal) {
15905                // Abort update; system app can't be replaced with app on sdcard
15906                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15907                        "Cannot install updates to system apps on sdcard");
15908                return;
15909            } else if (ephemeral) {
15910                // Abort update; system app can't be replaced with an ephemeral app
15911                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15912                        "Cannot update a system app with an ephemeral app");
15913                return;
15914            }
15915        }
15916
15917        if (args.move != null) {
15918            // We did an in-place move, so dex is ready to roll
15919            scanFlags |= SCAN_NO_DEX;
15920            scanFlags |= SCAN_MOVE;
15921
15922            synchronized (mPackages) {
15923                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15924                if (ps == null) {
15925                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15926                            "Missing settings for moved package " + pkgName);
15927                }
15928
15929                // We moved the entire application as-is, so bring over the
15930                // previously derived ABI information.
15931                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15932                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15933            }
15934
15935        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15936            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15937            scanFlags |= SCAN_NO_DEX;
15938
15939            try {
15940                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15941                    args.abiOverride : pkg.cpuAbiOverride);
15942                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15943                        true /*extractLibs*/, mAppLib32InstallDir);
15944            } catch (PackageManagerException pme) {
15945                Slog.e(TAG, "Error deriving application ABI", pme);
15946                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15947                return;
15948            }
15949
15950            // Shared libraries for the package need to be updated.
15951            synchronized (mPackages) {
15952                try {
15953                    updateSharedLibrariesLPr(pkg, null);
15954                } catch (PackageManagerException e) {
15955                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15956                }
15957            }
15958            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15959            // Do not run PackageDexOptimizer through the local performDexOpt
15960            // method because `pkg` may not be in `mPackages` yet.
15961            //
15962            // Also, don't fail application installs if the dexopt step fails.
15963            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15964                    null /* instructionSets */, false /* checkProfiles */,
15965                    getCompilerFilterForReason(REASON_INSTALL),
15966                    getOrCreateCompilerPackageStats(pkg));
15967            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15968
15969            // Notify BackgroundDexOptService that the package has been changed.
15970            // If this is an update of a package which used to fail to compile,
15971            // BDOS will remove it from its blacklist.
15972            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15973        }
15974
15975        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15976            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15977            return;
15978        }
15979
15980        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15981
15982        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15983                "installPackageLI")) {
15984            if (replace) {
15985                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15986                        installerPackageName, res, args.installReason);
15987            } else {
15988                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15989                        args.user, installerPackageName, volumeUuid, res, args.installReason);
15990            }
15991        }
15992        synchronized (mPackages) {
15993            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15994            if (ps != null) {
15995                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15996            }
15997
15998            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15999            for (int i = 0; i < childCount; i++) {
16000                PackageParser.Package childPkg = pkg.childPackages.get(i);
16001                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16002                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16003                if (childPs != null) {
16004                    childRes.newUsers = childPs.queryInstalledUsers(
16005                            sUserManager.getUserIds(), true);
16006                }
16007            }
16008        }
16009    }
16010
16011    private void startIntentFilterVerifications(int userId, boolean replacing,
16012            PackageParser.Package pkg) {
16013        if (mIntentFilterVerifierComponent == null) {
16014            Slog.w(TAG, "No IntentFilter verification will not be done as "
16015                    + "there is no IntentFilterVerifier available!");
16016            return;
16017        }
16018
16019        final int verifierUid = getPackageUid(
16020                mIntentFilterVerifierComponent.getPackageName(),
16021                MATCH_DEBUG_TRIAGED_MISSING,
16022                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16023
16024        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16025        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16026        mHandler.sendMessage(msg);
16027
16028        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16029        for (int i = 0; i < childCount; i++) {
16030            PackageParser.Package childPkg = pkg.childPackages.get(i);
16031            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16032            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16033            mHandler.sendMessage(msg);
16034        }
16035    }
16036
16037    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16038            PackageParser.Package pkg) {
16039        int size = pkg.activities.size();
16040        if (size == 0) {
16041            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16042                    "No activity, so no need to verify any IntentFilter!");
16043            return;
16044        }
16045
16046        final boolean hasDomainURLs = hasDomainURLs(pkg);
16047        if (!hasDomainURLs) {
16048            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16049                    "No domain URLs, so no need to verify any IntentFilter!");
16050            return;
16051        }
16052
16053        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16054                + " if any IntentFilter from the " + size
16055                + " Activities needs verification ...");
16056
16057        int count = 0;
16058        final String packageName = pkg.packageName;
16059
16060        synchronized (mPackages) {
16061            // If this is a new install and we see that we've already run verification for this
16062            // package, we have nothing to do: it means the state was restored from backup.
16063            if (!replacing) {
16064                IntentFilterVerificationInfo ivi =
16065                        mSettings.getIntentFilterVerificationLPr(packageName);
16066                if (ivi != null) {
16067                    if (DEBUG_DOMAIN_VERIFICATION) {
16068                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16069                                + ivi.getStatusString());
16070                    }
16071                    return;
16072                }
16073            }
16074
16075            // If any filters need to be verified, then all need to be.
16076            boolean needToVerify = false;
16077            for (PackageParser.Activity a : pkg.activities) {
16078                for (ActivityIntentInfo filter : a.intents) {
16079                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16080                        if (DEBUG_DOMAIN_VERIFICATION) {
16081                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16082                        }
16083                        needToVerify = true;
16084                        break;
16085                    }
16086                }
16087            }
16088
16089            if (needToVerify) {
16090                final int verificationId = mIntentFilterVerificationToken++;
16091                for (PackageParser.Activity a : pkg.activities) {
16092                    for (ActivityIntentInfo filter : a.intents) {
16093                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16094                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16095                                    "Verification needed for IntentFilter:" + filter.toString());
16096                            mIntentFilterVerifier.addOneIntentFilterVerification(
16097                                    verifierUid, userId, verificationId, filter, packageName);
16098                            count++;
16099                        }
16100                    }
16101                }
16102            }
16103        }
16104
16105        if (count > 0) {
16106            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16107                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16108                    +  " for userId:" + userId);
16109            mIntentFilterVerifier.startVerifications(userId);
16110        } else {
16111            if (DEBUG_DOMAIN_VERIFICATION) {
16112                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16113            }
16114        }
16115    }
16116
16117    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16118        final ComponentName cn  = filter.activity.getComponentName();
16119        final String packageName = cn.getPackageName();
16120
16121        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16122                packageName);
16123        if (ivi == null) {
16124            return true;
16125        }
16126        int status = ivi.getStatus();
16127        switch (status) {
16128            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16129            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16130                return true;
16131
16132            default:
16133                // Nothing to do
16134                return false;
16135        }
16136    }
16137
16138    private static boolean isMultiArch(ApplicationInfo info) {
16139        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16140    }
16141
16142    private static boolean isExternal(PackageParser.Package pkg) {
16143        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16144    }
16145
16146    private static boolean isExternal(PackageSetting ps) {
16147        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16148    }
16149
16150    private static boolean isEphemeral(PackageParser.Package pkg) {
16151        return pkg.applicationInfo.isEphemeralApp();
16152    }
16153
16154    private static boolean isEphemeral(PackageSetting ps) {
16155        return ps.pkg != null && isEphemeral(ps.pkg);
16156    }
16157
16158    private static boolean isSystemApp(PackageParser.Package pkg) {
16159        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16160    }
16161
16162    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16163        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16164    }
16165
16166    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16167        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16168    }
16169
16170    private static boolean isSystemApp(PackageSetting ps) {
16171        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16172    }
16173
16174    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16175        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16176    }
16177
16178    private int packageFlagsToInstallFlags(PackageSetting ps) {
16179        int installFlags = 0;
16180        if (isEphemeral(ps)) {
16181            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16182        }
16183        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16184            // This existing package was an external ASEC install when we have
16185            // the external flag without a UUID
16186            installFlags |= PackageManager.INSTALL_EXTERNAL;
16187        }
16188        if (ps.isForwardLocked()) {
16189            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16190        }
16191        return installFlags;
16192    }
16193
16194    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16195        if (isExternal(pkg)) {
16196            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16197                return StorageManager.UUID_PRIMARY_PHYSICAL;
16198            } else {
16199                return pkg.volumeUuid;
16200            }
16201        } else {
16202            return StorageManager.UUID_PRIVATE_INTERNAL;
16203        }
16204    }
16205
16206    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16207        if (isExternal(pkg)) {
16208            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16209                return mSettings.getExternalVersion();
16210            } else {
16211                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16212            }
16213        } else {
16214            return mSettings.getInternalVersion();
16215        }
16216    }
16217
16218    private void deleteTempPackageFiles() {
16219        final FilenameFilter filter = new FilenameFilter() {
16220            public boolean accept(File dir, String name) {
16221                return name.startsWith("vmdl") && name.endsWith(".tmp");
16222            }
16223        };
16224        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16225            file.delete();
16226        }
16227    }
16228
16229    @Override
16230    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16231            int flags) {
16232        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16233                flags);
16234    }
16235
16236    @Override
16237    public void deletePackage(final String packageName,
16238            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16239        mContext.enforceCallingOrSelfPermission(
16240                android.Manifest.permission.DELETE_PACKAGES, null);
16241        Preconditions.checkNotNull(packageName);
16242        Preconditions.checkNotNull(observer);
16243        final int uid = Binder.getCallingUid();
16244        if (!isOrphaned(packageName)
16245                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16246            try {
16247                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16248                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16249                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16250                observer.onUserActionRequired(intent);
16251            } catch (RemoteException re) {
16252            }
16253            return;
16254        }
16255        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16256        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16257        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16258            mContext.enforceCallingOrSelfPermission(
16259                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16260                    "deletePackage for user " + userId);
16261        }
16262
16263        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16264            try {
16265                observer.onPackageDeleted(packageName,
16266                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16267            } catch (RemoteException re) {
16268            }
16269            return;
16270        }
16271
16272        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16273            try {
16274                observer.onPackageDeleted(packageName,
16275                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16276            } catch (RemoteException re) {
16277            }
16278            return;
16279        }
16280
16281        if (DEBUG_REMOVE) {
16282            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16283                    + " deleteAllUsers: " + deleteAllUsers );
16284        }
16285        // Queue up an async operation since the package deletion may take a little while.
16286        mHandler.post(new Runnable() {
16287            public void run() {
16288                mHandler.removeCallbacks(this);
16289                int returnCode;
16290                if (!deleteAllUsers) {
16291                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16292                } else {
16293                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16294                    // If nobody is blocking uninstall, proceed with delete for all users
16295                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16296                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16297                    } else {
16298                        // Otherwise uninstall individually for users with blockUninstalls=false
16299                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16300                        for (int userId : users) {
16301                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16302                                returnCode = deletePackageX(packageName, userId, userFlags);
16303                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16304                                    Slog.w(TAG, "Package delete failed for user " + userId
16305                                            + ", returnCode " + returnCode);
16306                                }
16307                            }
16308                        }
16309                        // The app has only been marked uninstalled for certain users.
16310                        // We still need to report that delete was blocked
16311                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16312                    }
16313                }
16314                try {
16315                    observer.onPackageDeleted(packageName, returnCode, null);
16316                } catch (RemoteException e) {
16317                    Log.i(TAG, "Observer no longer exists.");
16318                } //end catch
16319            } //end run
16320        });
16321    }
16322
16323    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16324        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16325              || callingUid == Process.SYSTEM_UID) {
16326            return true;
16327        }
16328        final int callingUserId = UserHandle.getUserId(callingUid);
16329        // If the caller installed the pkgName, then allow it to silently uninstall.
16330        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16331            return true;
16332        }
16333
16334        // Allow package verifier to silently uninstall.
16335        if (mRequiredVerifierPackage != null &&
16336                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16337            return true;
16338        }
16339
16340        // Allow package uninstaller to silently uninstall.
16341        if (mRequiredUninstallerPackage != null &&
16342                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16343            return true;
16344        }
16345
16346        // Allow storage manager to silently uninstall.
16347        if (mStorageManagerPackage != null &&
16348                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16349            return true;
16350        }
16351        return false;
16352    }
16353
16354    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16355        int[] result = EMPTY_INT_ARRAY;
16356        for (int userId : userIds) {
16357            if (getBlockUninstallForUser(packageName, userId)) {
16358                result = ArrayUtils.appendInt(result, userId);
16359            }
16360        }
16361        return result;
16362    }
16363
16364    @Override
16365    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16366        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16367    }
16368
16369    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16370        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16371                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16372        try {
16373            if (dpm != null) {
16374                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16375                        /* callingUserOnly =*/ false);
16376                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16377                        : deviceOwnerComponentName.getPackageName();
16378                // Does the package contains the device owner?
16379                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16380                // this check is probably not needed, since DO should be registered as a device
16381                // admin on some user too. (Original bug for this: b/17657954)
16382                if (packageName.equals(deviceOwnerPackageName)) {
16383                    return true;
16384                }
16385                // Does it contain a device admin for any user?
16386                int[] users;
16387                if (userId == UserHandle.USER_ALL) {
16388                    users = sUserManager.getUserIds();
16389                } else {
16390                    users = new int[]{userId};
16391                }
16392                for (int i = 0; i < users.length; ++i) {
16393                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16394                        return true;
16395                    }
16396                }
16397            }
16398        } catch (RemoteException e) {
16399        }
16400        return false;
16401    }
16402
16403    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16404        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16405    }
16406
16407    /**
16408     *  This method is an internal method that could be get invoked either
16409     *  to delete an installed package or to clean up a failed installation.
16410     *  After deleting an installed package, a broadcast is sent to notify any
16411     *  listeners that the package has been removed. For cleaning up a failed
16412     *  installation, the broadcast is not necessary since the package's
16413     *  installation wouldn't have sent the initial broadcast either
16414     *  The key steps in deleting a package are
16415     *  deleting the package information in internal structures like mPackages,
16416     *  deleting the packages base directories through installd
16417     *  updating mSettings to reflect current status
16418     *  persisting settings for later use
16419     *  sending a broadcast if necessary
16420     */
16421    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16422        final PackageRemovedInfo info = new PackageRemovedInfo();
16423        final boolean res;
16424
16425        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16426                ? UserHandle.USER_ALL : userId;
16427
16428        if (isPackageDeviceAdmin(packageName, removeUser)) {
16429            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16430            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16431        }
16432
16433        PackageSetting uninstalledPs = null;
16434
16435        // for the uninstall-updates case and restricted profiles, remember the per-
16436        // user handle installed state
16437        int[] allUsers;
16438        synchronized (mPackages) {
16439            uninstalledPs = mSettings.mPackages.get(packageName);
16440            if (uninstalledPs == null) {
16441                Slog.w(TAG, "Not removing non-existent package " + packageName);
16442                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16443            }
16444            allUsers = sUserManager.getUserIds();
16445            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16446        }
16447
16448        final int freezeUser;
16449        if (isUpdatedSystemApp(uninstalledPs)
16450                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16451            // We're downgrading a system app, which will apply to all users, so
16452            // freeze them all during the downgrade
16453            freezeUser = UserHandle.USER_ALL;
16454        } else {
16455            freezeUser = removeUser;
16456        }
16457
16458        synchronized (mInstallLock) {
16459            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16460            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16461                    deleteFlags, "deletePackageX")) {
16462                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16463                        deleteFlags | REMOVE_CHATTY, info, true, null);
16464            }
16465            synchronized (mPackages) {
16466                if (res) {
16467                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16468                }
16469            }
16470        }
16471
16472        if (res) {
16473            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16474            info.sendPackageRemovedBroadcasts(killApp);
16475            info.sendSystemPackageUpdatedBroadcasts();
16476            info.sendSystemPackageAppearedBroadcasts();
16477        }
16478        // Force a gc here.
16479        Runtime.getRuntime().gc();
16480        // Delete the resources here after sending the broadcast to let
16481        // other processes clean up before deleting resources.
16482        if (info.args != null) {
16483            synchronized (mInstallLock) {
16484                info.args.doPostDeleteLI(true);
16485            }
16486        }
16487
16488        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16489    }
16490
16491    class PackageRemovedInfo {
16492        String removedPackage;
16493        int uid = -1;
16494        int removedAppId = -1;
16495        int[] origUsers;
16496        int[] removedUsers = null;
16497        SparseArray<Integer> installReasons;
16498        boolean isRemovedPackageSystemUpdate = false;
16499        boolean isUpdate;
16500        boolean dataRemoved;
16501        boolean removedForAllUsers;
16502        // Clean up resources deleted packages.
16503        InstallArgs args = null;
16504        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16505        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16506
16507        void sendPackageRemovedBroadcasts(boolean killApp) {
16508            sendPackageRemovedBroadcastInternal(killApp);
16509            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16510            for (int i = 0; i < childCount; i++) {
16511                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16512                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16513            }
16514        }
16515
16516        void sendSystemPackageUpdatedBroadcasts() {
16517            if (isRemovedPackageSystemUpdate) {
16518                sendSystemPackageUpdatedBroadcastsInternal();
16519                final int childCount = (removedChildPackages != null)
16520                        ? removedChildPackages.size() : 0;
16521                for (int i = 0; i < childCount; i++) {
16522                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16523                    if (childInfo.isRemovedPackageSystemUpdate) {
16524                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16525                    }
16526                }
16527            }
16528        }
16529
16530        void sendSystemPackageAppearedBroadcasts() {
16531            final int packageCount = (appearedChildPackages != null)
16532                    ? appearedChildPackages.size() : 0;
16533            for (int i = 0; i < packageCount; i++) {
16534                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16535                sendPackageAddedForNewUsers(installedInfo.name, true,
16536                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16537            }
16538        }
16539
16540        private void sendSystemPackageUpdatedBroadcastsInternal() {
16541            Bundle extras = new Bundle(2);
16542            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16543            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16544            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16545                    extras, 0, null, null, null);
16546            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16547                    extras, 0, null, null, null);
16548            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16549                    null, 0, removedPackage, null, null);
16550        }
16551
16552        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16553            Bundle extras = new Bundle(2);
16554            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16555            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16556            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16557            if (isUpdate || isRemovedPackageSystemUpdate) {
16558                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16559            }
16560            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16561            if (removedPackage != null) {
16562                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16563                        extras, 0, null, null, removedUsers);
16564                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16565                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16566                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
16567                            null, null, removedUsers);
16568                }
16569            }
16570            if (removedAppId >= 0) {
16571                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16572                        removedUsers);
16573            }
16574        }
16575    }
16576
16577    /*
16578     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16579     * flag is not set, the data directory is removed as well.
16580     * make sure this flag is set for partially installed apps. If not its meaningless to
16581     * delete a partially installed application.
16582     */
16583    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16584            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16585        String packageName = ps.name;
16586        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16587        // Retrieve object to delete permissions for shared user later on
16588        final PackageParser.Package deletedPkg;
16589        final PackageSetting deletedPs;
16590        // reader
16591        synchronized (mPackages) {
16592            deletedPkg = mPackages.get(packageName);
16593            deletedPs = mSettings.mPackages.get(packageName);
16594            if (outInfo != null) {
16595                outInfo.removedPackage = packageName;
16596                outInfo.removedUsers = deletedPs != null
16597                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16598                        : null;
16599            }
16600        }
16601
16602        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16603
16604        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16605            final PackageParser.Package resolvedPkg;
16606            if (deletedPkg != null) {
16607                resolvedPkg = deletedPkg;
16608            } else {
16609                // We don't have a parsed package when it lives on an ejected
16610                // adopted storage device, so fake something together
16611                resolvedPkg = new PackageParser.Package(ps.name);
16612                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16613            }
16614            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16615                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16616            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16617            if (outInfo != null) {
16618                outInfo.dataRemoved = true;
16619            }
16620            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16621        }
16622
16623        // writer
16624        synchronized (mPackages) {
16625            if (deletedPs != null) {
16626                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16627                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16628                    clearDefaultBrowserIfNeeded(packageName);
16629                    if (outInfo != null) {
16630                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16631                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16632                    }
16633                    updatePermissionsLPw(deletedPs.name, null, 0);
16634                    if (deletedPs.sharedUser != null) {
16635                        // Remove permissions associated with package. Since runtime
16636                        // permissions are per user we have to kill the removed package
16637                        // or packages running under the shared user of the removed
16638                        // package if revoking the permissions requested only by the removed
16639                        // package is successful and this causes a change in gids.
16640                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16641                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16642                                    userId);
16643                            if (userIdToKill == UserHandle.USER_ALL
16644                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16645                                // If gids changed for this user, kill all affected packages.
16646                                mHandler.post(new Runnable() {
16647                                    @Override
16648                                    public void run() {
16649                                        // This has to happen with no lock held.
16650                                        killApplication(deletedPs.name, deletedPs.appId,
16651                                                KILL_APP_REASON_GIDS_CHANGED);
16652                                    }
16653                                });
16654                                break;
16655                            }
16656                        }
16657                    }
16658                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16659                }
16660                // make sure to preserve per-user disabled state if this removal was just
16661                // a downgrade of a system app to the factory package
16662                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16663                    if (DEBUG_REMOVE) {
16664                        Slog.d(TAG, "Propagating install state across downgrade");
16665                    }
16666                    for (int userId : allUserHandles) {
16667                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16668                        if (DEBUG_REMOVE) {
16669                            Slog.d(TAG, "    user " + userId + " => " + installed);
16670                        }
16671                        ps.setInstalled(installed, userId);
16672                    }
16673                }
16674            }
16675            // can downgrade to reader
16676            if (writeSettings) {
16677                // Save settings now
16678                mSettings.writeLPr();
16679            }
16680        }
16681        if (outInfo != null) {
16682            // A user ID was deleted here. Go through all users and remove it
16683            // from KeyStore.
16684            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16685        }
16686    }
16687
16688    static boolean locationIsPrivileged(File path) {
16689        try {
16690            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16691                    .getCanonicalPath();
16692            return path.getCanonicalPath().startsWith(privilegedAppDir);
16693        } catch (IOException e) {
16694            Slog.e(TAG, "Unable to access code path " + path);
16695        }
16696        return false;
16697    }
16698
16699    /*
16700     * Tries to delete system package.
16701     */
16702    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16703            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16704            boolean writeSettings) {
16705        if (deletedPs.parentPackageName != null) {
16706            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16707            return false;
16708        }
16709
16710        final boolean applyUserRestrictions
16711                = (allUserHandles != null) && (outInfo.origUsers != null);
16712        final PackageSetting disabledPs;
16713        // Confirm if the system package has been updated
16714        // An updated system app can be deleted. This will also have to restore
16715        // the system pkg from system partition
16716        // reader
16717        synchronized (mPackages) {
16718            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16719        }
16720
16721        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16722                + " disabledPs=" + disabledPs);
16723
16724        if (disabledPs == null) {
16725            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16726            return false;
16727        } else if (DEBUG_REMOVE) {
16728            Slog.d(TAG, "Deleting system pkg from data partition");
16729        }
16730
16731        if (DEBUG_REMOVE) {
16732            if (applyUserRestrictions) {
16733                Slog.d(TAG, "Remembering install states:");
16734                for (int userId : allUserHandles) {
16735                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16736                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16737                }
16738            }
16739        }
16740
16741        // Delete the updated package
16742        outInfo.isRemovedPackageSystemUpdate = true;
16743        if (outInfo.removedChildPackages != null) {
16744            final int childCount = (deletedPs.childPackageNames != null)
16745                    ? deletedPs.childPackageNames.size() : 0;
16746            for (int i = 0; i < childCount; i++) {
16747                String childPackageName = deletedPs.childPackageNames.get(i);
16748                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16749                        .contains(childPackageName)) {
16750                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16751                            childPackageName);
16752                    if (childInfo != null) {
16753                        childInfo.isRemovedPackageSystemUpdate = true;
16754                    }
16755                }
16756            }
16757        }
16758
16759        if (disabledPs.versionCode < deletedPs.versionCode) {
16760            // Delete data for downgrades
16761            flags &= ~PackageManager.DELETE_KEEP_DATA;
16762        } else {
16763            // Preserve data by setting flag
16764            flags |= PackageManager.DELETE_KEEP_DATA;
16765        }
16766
16767        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16768                outInfo, writeSettings, disabledPs.pkg);
16769        if (!ret) {
16770            return false;
16771        }
16772
16773        // writer
16774        synchronized (mPackages) {
16775            // Reinstate the old system package
16776            enableSystemPackageLPw(disabledPs.pkg);
16777            // Remove any native libraries from the upgraded package.
16778            removeNativeBinariesLI(deletedPs);
16779        }
16780
16781        // Install the system package
16782        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16783        int parseFlags = mDefParseFlags
16784                | PackageParser.PARSE_MUST_BE_APK
16785                | PackageParser.PARSE_IS_SYSTEM
16786                | PackageParser.PARSE_IS_SYSTEM_DIR;
16787        if (locationIsPrivileged(disabledPs.codePath)) {
16788            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16789        }
16790
16791        final PackageParser.Package newPkg;
16792        try {
16793            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16794                0 /* currentTime */, null);
16795        } catch (PackageManagerException e) {
16796            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16797                    + e.getMessage());
16798            return false;
16799        }
16800        try {
16801            // update shared libraries for the newly re-installed system package
16802            updateSharedLibrariesLPr(newPkg, null);
16803        } catch (PackageManagerException e) {
16804            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16805        }
16806
16807        prepareAppDataAfterInstallLIF(newPkg);
16808
16809        // writer
16810        synchronized (mPackages) {
16811            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16812
16813            // Propagate the permissions state as we do not want to drop on the floor
16814            // runtime permissions. The update permissions method below will take
16815            // care of removing obsolete permissions and grant install permissions.
16816            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16817            updatePermissionsLPw(newPkg.packageName, newPkg,
16818                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16819
16820            if (applyUserRestrictions) {
16821                if (DEBUG_REMOVE) {
16822                    Slog.d(TAG, "Propagating install state across reinstall");
16823                }
16824                for (int userId : allUserHandles) {
16825                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16826                    if (DEBUG_REMOVE) {
16827                        Slog.d(TAG, "    user " + userId + " => " + installed);
16828                    }
16829                    ps.setInstalled(installed, userId);
16830
16831                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16832                }
16833                // Regardless of writeSettings we need to ensure that this restriction
16834                // state propagation is persisted
16835                mSettings.writeAllUsersPackageRestrictionsLPr();
16836            }
16837            // can downgrade to reader here
16838            if (writeSettings) {
16839                mSettings.writeLPr();
16840            }
16841        }
16842        return true;
16843    }
16844
16845    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16846            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16847            PackageRemovedInfo outInfo, boolean writeSettings,
16848            PackageParser.Package replacingPackage) {
16849        synchronized (mPackages) {
16850            if (outInfo != null) {
16851                outInfo.uid = ps.appId;
16852            }
16853
16854            if (outInfo != null && outInfo.removedChildPackages != null) {
16855                final int childCount = (ps.childPackageNames != null)
16856                        ? ps.childPackageNames.size() : 0;
16857                for (int i = 0; i < childCount; i++) {
16858                    String childPackageName = ps.childPackageNames.get(i);
16859                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16860                    if (childPs == null) {
16861                        return false;
16862                    }
16863                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16864                            childPackageName);
16865                    if (childInfo != null) {
16866                        childInfo.uid = childPs.appId;
16867                    }
16868                }
16869            }
16870        }
16871
16872        // Delete package data from internal structures and also remove data if flag is set
16873        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16874
16875        // Delete the child packages data
16876        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16877        for (int i = 0; i < childCount; i++) {
16878            PackageSetting childPs;
16879            synchronized (mPackages) {
16880                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16881            }
16882            if (childPs != null) {
16883                PackageRemovedInfo childOutInfo = (outInfo != null
16884                        && outInfo.removedChildPackages != null)
16885                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16886                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16887                        && (replacingPackage != null
16888                        && !replacingPackage.hasChildPackage(childPs.name))
16889                        ? flags & ~DELETE_KEEP_DATA : flags;
16890                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16891                        deleteFlags, writeSettings);
16892            }
16893        }
16894
16895        // Delete application code and resources only for parent packages
16896        if (ps.parentPackageName == null) {
16897            if (deleteCodeAndResources && (outInfo != null)) {
16898                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16899                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16900                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16901            }
16902        }
16903
16904        return true;
16905    }
16906
16907    @Override
16908    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16909            int userId) {
16910        mContext.enforceCallingOrSelfPermission(
16911                android.Manifest.permission.DELETE_PACKAGES, null);
16912        synchronized (mPackages) {
16913            PackageSetting ps = mSettings.mPackages.get(packageName);
16914            if (ps == null) {
16915                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16916                return false;
16917            }
16918            if (!ps.getInstalled(userId)) {
16919                // Can't block uninstall for an app that is not installed or enabled.
16920                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16921                return false;
16922            }
16923            ps.setBlockUninstall(blockUninstall, userId);
16924            mSettings.writePackageRestrictionsLPr(userId);
16925        }
16926        return true;
16927    }
16928
16929    @Override
16930    public boolean getBlockUninstallForUser(String packageName, int userId) {
16931        synchronized (mPackages) {
16932            PackageSetting ps = mSettings.mPackages.get(packageName);
16933            if (ps == null) {
16934                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16935                return false;
16936            }
16937            return ps.getBlockUninstall(userId);
16938        }
16939    }
16940
16941    @Override
16942    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16943        int callingUid = Binder.getCallingUid();
16944        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16945            throw new SecurityException(
16946                    "setRequiredForSystemUser can only be run by the system or root");
16947        }
16948        synchronized (mPackages) {
16949            PackageSetting ps = mSettings.mPackages.get(packageName);
16950            if (ps == null) {
16951                Log.w(TAG, "Package doesn't exist: " + packageName);
16952                return false;
16953            }
16954            if (systemUserApp) {
16955                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16956            } else {
16957                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16958            }
16959            mSettings.writeLPr();
16960        }
16961        return true;
16962    }
16963
16964    /*
16965     * This method handles package deletion in general
16966     */
16967    private boolean deletePackageLIF(String packageName, UserHandle user,
16968            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16969            PackageRemovedInfo outInfo, boolean writeSettings,
16970            PackageParser.Package replacingPackage) {
16971        if (packageName == null) {
16972            Slog.w(TAG, "Attempt to delete null packageName.");
16973            return false;
16974        }
16975
16976        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16977
16978        PackageSetting ps;
16979
16980        synchronized (mPackages) {
16981            ps = mSettings.mPackages.get(packageName);
16982            if (ps == null) {
16983                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16984                return false;
16985            }
16986
16987            if (ps.parentPackageName != null && (!isSystemApp(ps)
16988                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16989                if (DEBUG_REMOVE) {
16990                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16991                            + ((user == null) ? UserHandle.USER_ALL : user));
16992                }
16993                final int removedUserId = (user != null) ? user.getIdentifier()
16994                        : UserHandle.USER_ALL;
16995                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16996                    return false;
16997                }
16998                markPackageUninstalledForUserLPw(ps, user);
16999                scheduleWritePackageRestrictionsLocked(user);
17000                return true;
17001            }
17002        }
17003
17004        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17005                && user.getIdentifier() != UserHandle.USER_ALL)) {
17006            // The caller is asking that the package only be deleted for a single
17007            // user.  To do this, we just mark its uninstalled state and delete
17008            // its data. If this is a system app, we only allow this to happen if
17009            // they have set the special DELETE_SYSTEM_APP which requests different
17010            // semantics than normal for uninstalling system apps.
17011            markPackageUninstalledForUserLPw(ps, user);
17012
17013            if (!isSystemApp(ps)) {
17014                // Do not uninstall the APK if an app should be cached
17015                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17016                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17017                    // Other user still have this package installed, so all
17018                    // we need to do is clear this user's data and save that
17019                    // it is uninstalled.
17020                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17021                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17022                        return false;
17023                    }
17024                    scheduleWritePackageRestrictionsLocked(user);
17025                    return true;
17026                } else {
17027                    // We need to set it back to 'installed' so the uninstall
17028                    // broadcasts will be sent correctly.
17029                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17030                    ps.setInstalled(true, user.getIdentifier());
17031                }
17032            } else {
17033                // This is a system app, so we assume that the
17034                // other users still have this package installed, so all
17035                // we need to do is clear this user's data and save that
17036                // it is uninstalled.
17037                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17038                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17039                    return false;
17040                }
17041                scheduleWritePackageRestrictionsLocked(user);
17042                return true;
17043            }
17044        }
17045
17046        // If we are deleting a composite package for all users, keep track
17047        // of result for each child.
17048        if (ps.childPackageNames != null && outInfo != null) {
17049            synchronized (mPackages) {
17050                final int childCount = ps.childPackageNames.size();
17051                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17052                for (int i = 0; i < childCount; i++) {
17053                    String childPackageName = ps.childPackageNames.get(i);
17054                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17055                    childInfo.removedPackage = childPackageName;
17056                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17057                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17058                    if (childPs != null) {
17059                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17060                    }
17061                }
17062            }
17063        }
17064
17065        boolean ret = false;
17066        if (isSystemApp(ps)) {
17067            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17068            // When an updated system application is deleted we delete the existing resources
17069            // as well and fall back to existing code in system partition
17070            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17071        } else {
17072            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17073            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17074                    outInfo, writeSettings, replacingPackage);
17075        }
17076
17077        // Take a note whether we deleted the package for all users
17078        if (outInfo != null) {
17079            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17080            if (outInfo.removedChildPackages != null) {
17081                synchronized (mPackages) {
17082                    final int childCount = outInfo.removedChildPackages.size();
17083                    for (int i = 0; i < childCount; i++) {
17084                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17085                        if (childInfo != null) {
17086                            childInfo.removedForAllUsers = mPackages.get(
17087                                    childInfo.removedPackage) == null;
17088                        }
17089                    }
17090                }
17091            }
17092            // If we uninstalled an update to a system app there may be some
17093            // child packages that appeared as they are declared in the system
17094            // app but were not declared in the update.
17095            if (isSystemApp(ps)) {
17096                synchronized (mPackages) {
17097                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17098                    final int childCount = (updatedPs.childPackageNames != null)
17099                            ? updatedPs.childPackageNames.size() : 0;
17100                    for (int i = 0; i < childCount; i++) {
17101                        String childPackageName = updatedPs.childPackageNames.get(i);
17102                        if (outInfo.removedChildPackages == null
17103                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17104                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17105                            if (childPs == null) {
17106                                continue;
17107                            }
17108                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17109                            installRes.name = childPackageName;
17110                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17111                            installRes.pkg = mPackages.get(childPackageName);
17112                            installRes.uid = childPs.pkg.applicationInfo.uid;
17113                            if (outInfo.appearedChildPackages == null) {
17114                                outInfo.appearedChildPackages = new ArrayMap<>();
17115                            }
17116                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17117                        }
17118                    }
17119                }
17120            }
17121        }
17122
17123        return ret;
17124    }
17125
17126    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17127        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17128                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17129        for (int nextUserId : userIds) {
17130            if (DEBUG_REMOVE) {
17131                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17132            }
17133            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17134                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
17135                    false /*hidden*/, false /*suspended*/, null, null, null,
17136                    false /*blockUninstall*/,
17137                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
17138                    PackageManager.INSTALL_REASON_UNKNOWN);
17139        }
17140    }
17141
17142    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17143            PackageRemovedInfo outInfo) {
17144        final PackageParser.Package pkg;
17145        synchronized (mPackages) {
17146            pkg = mPackages.get(ps.name);
17147        }
17148
17149        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17150                : new int[] {userId};
17151        for (int nextUserId : userIds) {
17152            if (DEBUG_REMOVE) {
17153                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17154                        + nextUserId);
17155            }
17156
17157            destroyAppDataLIF(pkg, userId,
17158                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17159            destroyAppProfilesLIF(pkg, userId);
17160            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17161            schedulePackageCleaning(ps.name, nextUserId, false);
17162            synchronized (mPackages) {
17163                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17164                    scheduleWritePackageRestrictionsLocked(nextUserId);
17165                }
17166                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17167            }
17168        }
17169
17170        if (outInfo != null) {
17171            outInfo.removedPackage = ps.name;
17172            outInfo.removedAppId = ps.appId;
17173            outInfo.removedUsers = userIds;
17174        }
17175
17176        return true;
17177    }
17178
17179    private final class ClearStorageConnection implements ServiceConnection {
17180        IMediaContainerService mContainerService;
17181
17182        @Override
17183        public void onServiceConnected(ComponentName name, IBinder service) {
17184            synchronized (this) {
17185                mContainerService = IMediaContainerService.Stub
17186                        .asInterface(Binder.allowBlocking(service));
17187                notifyAll();
17188            }
17189        }
17190
17191        @Override
17192        public void onServiceDisconnected(ComponentName name) {
17193        }
17194    }
17195
17196    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17197        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17198
17199        final boolean mounted;
17200        if (Environment.isExternalStorageEmulated()) {
17201            mounted = true;
17202        } else {
17203            final String status = Environment.getExternalStorageState();
17204
17205            mounted = status.equals(Environment.MEDIA_MOUNTED)
17206                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17207        }
17208
17209        if (!mounted) {
17210            return;
17211        }
17212
17213        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17214        int[] users;
17215        if (userId == UserHandle.USER_ALL) {
17216            users = sUserManager.getUserIds();
17217        } else {
17218            users = new int[] { userId };
17219        }
17220        final ClearStorageConnection conn = new ClearStorageConnection();
17221        if (mContext.bindServiceAsUser(
17222                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17223            try {
17224                for (int curUser : users) {
17225                    long timeout = SystemClock.uptimeMillis() + 5000;
17226                    synchronized (conn) {
17227                        long now;
17228                        while (conn.mContainerService == null &&
17229                                (now = SystemClock.uptimeMillis()) < timeout) {
17230                            try {
17231                                conn.wait(timeout - now);
17232                            } catch (InterruptedException e) {
17233                            }
17234                        }
17235                    }
17236                    if (conn.mContainerService == null) {
17237                        return;
17238                    }
17239
17240                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17241                    clearDirectory(conn.mContainerService,
17242                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17243                    if (allData) {
17244                        clearDirectory(conn.mContainerService,
17245                                userEnv.buildExternalStorageAppDataDirs(packageName));
17246                        clearDirectory(conn.mContainerService,
17247                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17248                    }
17249                }
17250            } finally {
17251                mContext.unbindService(conn);
17252            }
17253        }
17254    }
17255
17256    @Override
17257    public void clearApplicationProfileData(String packageName) {
17258        enforceSystemOrRoot("Only the system can clear all profile data");
17259
17260        final PackageParser.Package pkg;
17261        synchronized (mPackages) {
17262            pkg = mPackages.get(packageName);
17263        }
17264
17265        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17266            synchronized (mInstallLock) {
17267                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17268                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17269                        true /* removeBaseMarker */);
17270            }
17271        }
17272    }
17273
17274    @Override
17275    public void clearApplicationUserData(final String packageName,
17276            final IPackageDataObserver observer, final int userId) {
17277        mContext.enforceCallingOrSelfPermission(
17278                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17279
17280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17281                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17282
17283        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17284            throw new SecurityException("Cannot clear data for a protected package: "
17285                    + packageName);
17286        }
17287        // Queue up an async operation since the package deletion may take a little while.
17288        mHandler.post(new Runnable() {
17289            public void run() {
17290                mHandler.removeCallbacks(this);
17291                final boolean succeeded;
17292                try (PackageFreezer freezer = freezePackage(packageName,
17293                        "clearApplicationUserData")) {
17294                    synchronized (mInstallLock) {
17295                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17296                    }
17297                    clearExternalStorageDataSync(packageName, userId, true);
17298                }
17299                if (succeeded) {
17300                    // invoke DeviceStorageMonitor's update method to clear any notifications
17301                    DeviceStorageMonitorInternal dsm = LocalServices
17302                            .getService(DeviceStorageMonitorInternal.class);
17303                    if (dsm != null) {
17304                        dsm.checkMemory();
17305                    }
17306                }
17307                if(observer != null) {
17308                    try {
17309                        observer.onRemoveCompleted(packageName, succeeded);
17310                    } catch (RemoteException e) {
17311                        Log.i(TAG, "Observer no longer exists.");
17312                    }
17313                } //end if observer
17314            } //end run
17315        });
17316    }
17317
17318    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17319        if (packageName == null) {
17320            Slog.w(TAG, "Attempt to delete null packageName.");
17321            return false;
17322        }
17323
17324        // Try finding details about the requested package
17325        PackageParser.Package pkg;
17326        synchronized (mPackages) {
17327            pkg = mPackages.get(packageName);
17328            if (pkg == null) {
17329                final PackageSetting ps = mSettings.mPackages.get(packageName);
17330                if (ps != null) {
17331                    pkg = ps.pkg;
17332                }
17333            }
17334
17335            if (pkg == null) {
17336                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17337                return false;
17338            }
17339
17340            PackageSetting ps = (PackageSetting) pkg.mExtras;
17341            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17342        }
17343
17344        clearAppDataLIF(pkg, userId,
17345                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17346
17347        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17348        removeKeystoreDataIfNeeded(userId, appId);
17349
17350        UserManagerInternal umInternal = getUserManagerInternal();
17351        final int flags;
17352        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17353            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17354        } else if (umInternal.isUserRunning(userId)) {
17355            flags = StorageManager.FLAG_STORAGE_DE;
17356        } else {
17357            flags = 0;
17358        }
17359        prepareAppDataContentsLIF(pkg, userId, flags);
17360
17361        return true;
17362    }
17363
17364    /**
17365     * Reverts user permission state changes (permissions and flags) in
17366     * all packages for a given user.
17367     *
17368     * @param userId The device user for which to do a reset.
17369     */
17370    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17371        final int packageCount = mPackages.size();
17372        for (int i = 0; i < packageCount; i++) {
17373            PackageParser.Package pkg = mPackages.valueAt(i);
17374            PackageSetting ps = (PackageSetting) pkg.mExtras;
17375            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17376        }
17377    }
17378
17379    private void resetNetworkPolicies(int userId) {
17380        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17381    }
17382
17383    /**
17384     * Reverts user permission state changes (permissions and flags).
17385     *
17386     * @param ps The package for which to reset.
17387     * @param userId The device user for which to do a reset.
17388     */
17389    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17390            final PackageSetting ps, final int userId) {
17391        if (ps.pkg == null) {
17392            return;
17393        }
17394
17395        // These are flags that can change base on user actions.
17396        final int userSettableMask = FLAG_PERMISSION_USER_SET
17397                | FLAG_PERMISSION_USER_FIXED
17398                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17399                | FLAG_PERMISSION_REVIEW_REQUIRED;
17400
17401        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17402                | FLAG_PERMISSION_POLICY_FIXED;
17403
17404        boolean writeInstallPermissions = false;
17405        boolean writeRuntimePermissions = false;
17406
17407        final int permissionCount = ps.pkg.requestedPermissions.size();
17408        for (int i = 0; i < permissionCount; i++) {
17409            String permission = ps.pkg.requestedPermissions.get(i);
17410
17411            BasePermission bp = mSettings.mPermissions.get(permission);
17412            if (bp == null) {
17413                continue;
17414            }
17415
17416            // If shared user we just reset the state to which only this app contributed.
17417            if (ps.sharedUser != null) {
17418                boolean used = false;
17419                final int packageCount = ps.sharedUser.packages.size();
17420                for (int j = 0; j < packageCount; j++) {
17421                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17422                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17423                            && pkg.pkg.requestedPermissions.contains(permission)) {
17424                        used = true;
17425                        break;
17426                    }
17427                }
17428                if (used) {
17429                    continue;
17430                }
17431            }
17432
17433            PermissionsState permissionsState = ps.getPermissionsState();
17434
17435            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17436
17437            // Always clear the user settable flags.
17438            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17439                    bp.name) != null;
17440            // If permission review is enabled and this is a legacy app, mark the
17441            // permission as requiring a review as this is the initial state.
17442            int flags = 0;
17443            if (mPermissionReviewRequired
17444                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17445                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17446            }
17447            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17448                if (hasInstallState) {
17449                    writeInstallPermissions = true;
17450                } else {
17451                    writeRuntimePermissions = true;
17452                }
17453            }
17454
17455            // Below is only runtime permission handling.
17456            if (!bp.isRuntime()) {
17457                continue;
17458            }
17459
17460            // Never clobber system or policy.
17461            if ((oldFlags & policyOrSystemFlags) != 0) {
17462                continue;
17463            }
17464
17465            // If this permission was granted by default, make sure it is.
17466            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17467                if (permissionsState.grantRuntimePermission(bp, userId)
17468                        != PERMISSION_OPERATION_FAILURE) {
17469                    writeRuntimePermissions = true;
17470                }
17471            // If permission review is enabled the permissions for a legacy apps
17472            // are represented as constantly granted runtime ones, so don't revoke.
17473            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17474                // Otherwise, reset the permission.
17475                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17476                switch (revokeResult) {
17477                    case PERMISSION_OPERATION_SUCCESS:
17478                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17479                        writeRuntimePermissions = true;
17480                        final int appId = ps.appId;
17481                        mHandler.post(new Runnable() {
17482                            @Override
17483                            public void run() {
17484                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17485                            }
17486                        });
17487                    } break;
17488                }
17489            }
17490        }
17491
17492        // Synchronously write as we are taking permissions away.
17493        if (writeRuntimePermissions) {
17494            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17495        }
17496
17497        // Synchronously write as we are taking permissions away.
17498        if (writeInstallPermissions) {
17499            mSettings.writeLPr();
17500        }
17501    }
17502
17503    /**
17504     * Remove entries from the keystore daemon. Will only remove it if the
17505     * {@code appId} is valid.
17506     */
17507    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17508        if (appId < 0) {
17509            return;
17510        }
17511
17512        final KeyStore keyStore = KeyStore.getInstance();
17513        if (keyStore != null) {
17514            if (userId == UserHandle.USER_ALL) {
17515                for (final int individual : sUserManager.getUserIds()) {
17516                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17517                }
17518            } else {
17519                keyStore.clearUid(UserHandle.getUid(userId, appId));
17520            }
17521        } else {
17522            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17523        }
17524    }
17525
17526    @Override
17527    public void deleteApplicationCacheFiles(final String packageName,
17528            final IPackageDataObserver observer) {
17529        final int userId = UserHandle.getCallingUserId();
17530        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17531    }
17532
17533    @Override
17534    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17535            final IPackageDataObserver observer) {
17536        mContext.enforceCallingOrSelfPermission(
17537                android.Manifest.permission.DELETE_CACHE_FILES, null);
17538        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17539                /* requireFullPermission= */ true, /* checkShell= */ false,
17540                "delete application cache files");
17541
17542        final PackageParser.Package pkg;
17543        synchronized (mPackages) {
17544            pkg = mPackages.get(packageName);
17545        }
17546
17547        // Queue up an async operation since the package deletion may take a little while.
17548        mHandler.post(new Runnable() {
17549            public void run() {
17550                synchronized (mInstallLock) {
17551                    final int flags = StorageManager.FLAG_STORAGE_DE
17552                            | StorageManager.FLAG_STORAGE_CE;
17553                    // We're only clearing cache files, so we don't care if the
17554                    // app is unfrozen and still able to run
17555                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17556                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17557                }
17558                clearExternalStorageDataSync(packageName, userId, false);
17559                if (observer != null) {
17560                    try {
17561                        observer.onRemoveCompleted(packageName, true);
17562                    } catch (RemoteException e) {
17563                        Log.i(TAG, "Observer no longer exists.");
17564                    }
17565                }
17566            }
17567        });
17568    }
17569
17570    @Override
17571    public void getPackageSizeInfo(final String packageName, int userHandle,
17572            final IPackageStatsObserver observer) {
17573        mContext.enforceCallingOrSelfPermission(
17574                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17575        if (packageName == null) {
17576            throw new IllegalArgumentException("Attempt to get size of null packageName");
17577        }
17578
17579        PackageStats stats = new PackageStats(packageName, userHandle);
17580
17581        /*
17582         * Queue up an async operation since the package measurement may take a
17583         * little while.
17584         */
17585        Message msg = mHandler.obtainMessage(INIT_COPY);
17586        msg.obj = new MeasureParams(stats, observer);
17587        mHandler.sendMessage(msg);
17588    }
17589
17590    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17591        final PackageSetting ps;
17592        synchronized (mPackages) {
17593            ps = mSettings.mPackages.get(packageName);
17594            if (ps == null) {
17595                Slog.w(TAG, "Failed to find settings for " + packageName);
17596                return false;
17597            }
17598        }
17599
17600        final String[] packageNames = { packageName };
17601        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
17602        final String[] codePaths = { ps.codePathString };
17603
17604        try {
17605            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
17606                    ps.appId, ceDataInodes, codePaths, stats);
17607
17608            // For now, ignore code size of packages on system partition
17609            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17610                stats.codeSize = 0;
17611            }
17612
17613            // External clients expect these to be tracked separately
17614            stats.dataSize -= stats.cacheSize;
17615
17616        } catch (InstallerException e) {
17617            Slog.w(TAG, String.valueOf(e));
17618            return false;
17619        }
17620
17621        return true;
17622    }
17623
17624    private int getUidTargetSdkVersionLockedLPr(int uid) {
17625        Object obj = mSettings.getUserIdLPr(uid);
17626        if (obj instanceof SharedUserSetting) {
17627            final SharedUserSetting sus = (SharedUserSetting) obj;
17628            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17629            final Iterator<PackageSetting> it = sus.packages.iterator();
17630            while (it.hasNext()) {
17631                final PackageSetting ps = it.next();
17632                if (ps.pkg != null) {
17633                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17634                    if (v < vers) vers = v;
17635                }
17636            }
17637            return vers;
17638        } else if (obj instanceof PackageSetting) {
17639            final PackageSetting ps = (PackageSetting) obj;
17640            if (ps.pkg != null) {
17641                return ps.pkg.applicationInfo.targetSdkVersion;
17642            }
17643        }
17644        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17645    }
17646
17647    @Override
17648    public void addPreferredActivity(IntentFilter filter, int match,
17649            ComponentName[] set, ComponentName activity, int userId) {
17650        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17651                "Adding preferred");
17652    }
17653
17654    private void addPreferredActivityInternal(IntentFilter filter, int match,
17655            ComponentName[] set, ComponentName activity, boolean always, int userId,
17656            String opname) {
17657        // writer
17658        int callingUid = Binder.getCallingUid();
17659        enforceCrossUserPermission(callingUid, userId,
17660                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17661        if (filter.countActions() == 0) {
17662            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17663            return;
17664        }
17665        synchronized (mPackages) {
17666            if (mContext.checkCallingOrSelfPermission(
17667                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17668                    != PackageManager.PERMISSION_GRANTED) {
17669                if (getUidTargetSdkVersionLockedLPr(callingUid)
17670                        < Build.VERSION_CODES.FROYO) {
17671                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17672                            + callingUid);
17673                    return;
17674                }
17675                mContext.enforceCallingOrSelfPermission(
17676                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17677            }
17678
17679            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17680            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17681                    + userId + ":");
17682            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17683            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17684            scheduleWritePackageRestrictionsLocked(userId);
17685            postPreferredActivityChangedBroadcast(userId);
17686        }
17687    }
17688
17689    private void postPreferredActivityChangedBroadcast(int userId) {
17690        mHandler.post(() -> {
17691            final IActivityManager am = ActivityManager.getService();
17692            if (am == null) {
17693                return;
17694            }
17695
17696            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17697            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17698            try {
17699                am.broadcastIntent(null, intent, null, null,
17700                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17701                        null, false, false, userId);
17702            } catch (RemoteException e) {
17703            }
17704        });
17705    }
17706
17707    @Override
17708    public void replacePreferredActivity(IntentFilter filter, int match,
17709            ComponentName[] set, ComponentName activity, int userId) {
17710        if (filter.countActions() != 1) {
17711            throw new IllegalArgumentException(
17712                    "replacePreferredActivity expects filter to have only 1 action.");
17713        }
17714        if (filter.countDataAuthorities() != 0
17715                || filter.countDataPaths() != 0
17716                || filter.countDataSchemes() > 1
17717                || filter.countDataTypes() != 0) {
17718            throw new IllegalArgumentException(
17719                    "replacePreferredActivity expects filter to have no data authorities, " +
17720                    "paths, or types; and at most one scheme.");
17721        }
17722
17723        final int callingUid = Binder.getCallingUid();
17724        enforceCrossUserPermission(callingUid, userId,
17725                true /* requireFullPermission */, false /* checkShell */,
17726                "replace preferred activity");
17727        synchronized (mPackages) {
17728            if (mContext.checkCallingOrSelfPermission(
17729                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17730                    != PackageManager.PERMISSION_GRANTED) {
17731                if (getUidTargetSdkVersionLockedLPr(callingUid)
17732                        < Build.VERSION_CODES.FROYO) {
17733                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17734                            + Binder.getCallingUid());
17735                    return;
17736                }
17737                mContext.enforceCallingOrSelfPermission(
17738                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17739            }
17740
17741            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17742            if (pir != null) {
17743                // Get all of the existing entries that exactly match this filter.
17744                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17745                if (existing != null && existing.size() == 1) {
17746                    PreferredActivity cur = existing.get(0);
17747                    if (DEBUG_PREFERRED) {
17748                        Slog.i(TAG, "Checking replace of preferred:");
17749                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17750                        if (!cur.mPref.mAlways) {
17751                            Slog.i(TAG, "  -- CUR; not mAlways!");
17752                        } else {
17753                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17754                            Slog.i(TAG, "  -- CUR: mSet="
17755                                    + Arrays.toString(cur.mPref.mSetComponents));
17756                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17757                            Slog.i(TAG, "  -- NEW: mMatch="
17758                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17759                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17760                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17761                        }
17762                    }
17763                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17764                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17765                            && cur.mPref.sameSet(set)) {
17766                        // Setting the preferred activity to what it happens to be already
17767                        if (DEBUG_PREFERRED) {
17768                            Slog.i(TAG, "Replacing with same preferred activity "
17769                                    + cur.mPref.mShortComponent + " for user "
17770                                    + userId + ":");
17771                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17772                        }
17773                        return;
17774                    }
17775                }
17776
17777                if (existing != null) {
17778                    if (DEBUG_PREFERRED) {
17779                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17780                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17781                    }
17782                    for (int i = 0; i < existing.size(); i++) {
17783                        PreferredActivity pa = existing.get(i);
17784                        if (DEBUG_PREFERRED) {
17785                            Slog.i(TAG, "Removing existing preferred activity "
17786                                    + pa.mPref.mComponent + ":");
17787                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17788                        }
17789                        pir.removeFilter(pa);
17790                    }
17791                }
17792            }
17793            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17794                    "Replacing preferred");
17795        }
17796    }
17797
17798    @Override
17799    public void clearPackagePreferredActivities(String packageName) {
17800        final int uid = Binder.getCallingUid();
17801        // writer
17802        synchronized (mPackages) {
17803            PackageParser.Package pkg = mPackages.get(packageName);
17804            if (pkg == null || pkg.applicationInfo.uid != uid) {
17805                if (mContext.checkCallingOrSelfPermission(
17806                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17807                        != PackageManager.PERMISSION_GRANTED) {
17808                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17809                            < Build.VERSION_CODES.FROYO) {
17810                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17811                                + Binder.getCallingUid());
17812                        return;
17813                    }
17814                    mContext.enforceCallingOrSelfPermission(
17815                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17816                }
17817            }
17818
17819            int user = UserHandle.getCallingUserId();
17820            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17821                scheduleWritePackageRestrictionsLocked(user);
17822            }
17823        }
17824    }
17825
17826    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17827    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17828        ArrayList<PreferredActivity> removed = null;
17829        boolean changed = false;
17830        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17831            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17832            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17833            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17834                continue;
17835            }
17836            Iterator<PreferredActivity> it = pir.filterIterator();
17837            while (it.hasNext()) {
17838                PreferredActivity pa = it.next();
17839                // Mark entry for removal only if it matches the package name
17840                // and the entry is of type "always".
17841                if (packageName == null ||
17842                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17843                                && pa.mPref.mAlways)) {
17844                    if (removed == null) {
17845                        removed = new ArrayList<PreferredActivity>();
17846                    }
17847                    removed.add(pa);
17848                }
17849            }
17850            if (removed != null) {
17851                for (int j=0; j<removed.size(); j++) {
17852                    PreferredActivity pa = removed.get(j);
17853                    pir.removeFilter(pa);
17854                }
17855                changed = true;
17856            }
17857        }
17858        if (changed) {
17859            postPreferredActivityChangedBroadcast(userId);
17860        }
17861        return changed;
17862    }
17863
17864    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17865    private void clearIntentFilterVerificationsLPw(int userId) {
17866        final int packageCount = mPackages.size();
17867        for (int i = 0; i < packageCount; i++) {
17868            PackageParser.Package pkg = mPackages.valueAt(i);
17869            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17870        }
17871    }
17872
17873    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17874    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17875        if (userId == UserHandle.USER_ALL) {
17876            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17877                    sUserManager.getUserIds())) {
17878                for (int oneUserId : sUserManager.getUserIds()) {
17879                    scheduleWritePackageRestrictionsLocked(oneUserId);
17880                }
17881            }
17882        } else {
17883            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17884                scheduleWritePackageRestrictionsLocked(userId);
17885            }
17886        }
17887    }
17888
17889    void clearDefaultBrowserIfNeeded(String packageName) {
17890        for (int oneUserId : sUserManager.getUserIds()) {
17891            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17892            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17893            if (packageName.equals(defaultBrowserPackageName)) {
17894                setDefaultBrowserPackageName(null, oneUserId);
17895            }
17896        }
17897    }
17898
17899    @Override
17900    public void resetApplicationPreferences(int userId) {
17901        mContext.enforceCallingOrSelfPermission(
17902                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17903        final long identity = Binder.clearCallingIdentity();
17904        // writer
17905        try {
17906            synchronized (mPackages) {
17907                clearPackagePreferredActivitiesLPw(null, userId);
17908                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17909                // TODO: We have to reset the default SMS and Phone. This requires
17910                // significant refactoring to keep all default apps in the package
17911                // manager (cleaner but more work) or have the services provide
17912                // callbacks to the package manager to request a default app reset.
17913                applyFactoryDefaultBrowserLPw(userId);
17914                clearIntentFilterVerificationsLPw(userId);
17915                primeDomainVerificationsLPw(userId);
17916                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17917                scheduleWritePackageRestrictionsLocked(userId);
17918            }
17919            resetNetworkPolicies(userId);
17920        } finally {
17921            Binder.restoreCallingIdentity(identity);
17922        }
17923    }
17924
17925    @Override
17926    public int getPreferredActivities(List<IntentFilter> outFilters,
17927            List<ComponentName> outActivities, String packageName) {
17928
17929        int num = 0;
17930        final int userId = UserHandle.getCallingUserId();
17931        // reader
17932        synchronized (mPackages) {
17933            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17934            if (pir != null) {
17935                final Iterator<PreferredActivity> it = pir.filterIterator();
17936                while (it.hasNext()) {
17937                    final PreferredActivity pa = it.next();
17938                    if (packageName == null
17939                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17940                                    && pa.mPref.mAlways)) {
17941                        if (outFilters != null) {
17942                            outFilters.add(new IntentFilter(pa));
17943                        }
17944                        if (outActivities != null) {
17945                            outActivities.add(pa.mPref.mComponent);
17946                        }
17947                    }
17948                }
17949            }
17950        }
17951
17952        return num;
17953    }
17954
17955    @Override
17956    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17957            int userId) {
17958        int callingUid = Binder.getCallingUid();
17959        if (callingUid != Process.SYSTEM_UID) {
17960            throw new SecurityException(
17961                    "addPersistentPreferredActivity can only be run by the system");
17962        }
17963        if (filter.countActions() == 0) {
17964            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17965            return;
17966        }
17967        synchronized (mPackages) {
17968            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17969                    ":");
17970            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17971            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17972                    new PersistentPreferredActivity(filter, activity));
17973            scheduleWritePackageRestrictionsLocked(userId);
17974            postPreferredActivityChangedBroadcast(userId);
17975        }
17976    }
17977
17978    @Override
17979    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17980        int callingUid = Binder.getCallingUid();
17981        if (callingUid != Process.SYSTEM_UID) {
17982            throw new SecurityException(
17983                    "clearPackagePersistentPreferredActivities can only be run by the system");
17984        }
17985        ArrayList<PersistentPreferredActivity> removed = null;
17986        boolean changed = false;
17987        synchronized (mPackages) {
17988            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17989                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17990                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17991                        .valueAt(i);
17992                if (userId != thisUserId) {
17993                    continue;
17994                }
17995                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17996                while (it.hasNext()) {
17997                    PersistentPreferredActivity ppa = it.next();
17998                    // Mark entry for removal only if it matches the package name.
17999                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18000                        if (removed == null) {
18001                            removed = new ArrayList<PersistentPreferredActivity>();
18002                        }
18003                        removed.add(ppa);
18004                    }
18005                }
18006                if (removed != null) {
18007                    for (int j=0; j<removed.size(); j++) {
18008                        PersistentPreferredActivity ppa = removed.get(j);
18009                        ppir.removeFilter(ppa);
18010                    }
18011                    changed = true;
18012                }
18013            }
18014
18015            if (changed) {
18016                scheduleWritePackageRestrictionsLocked(userId);
18017                postPreferredActivityChangedBroadcast(userId);
18018            }
18019        }
18020    }
18021
18022    /**
18023     * Common machinery for picking apart a restored XML blob and passing
18024     * it to a caller-supplied functor to be applied to the running system.
18025     */
18026    private void restoreFromXml(XmlPullParser parser, int userId,
18027            String expectedStartTag, BlobXmlRestorer functor)
18028            throws IOException, XmlPullParserException {
18029        int type;
18030        while ((type = parser.next()) != XmlPullParser.START_TAG
18031                && type != XmlPullParser.END_DOCUMENT) {
18032        }
18033        if (type != XmlPullParser.START_TAG) {
18034            // oops didn't find a start tag?!
18035            if (DEBUG_BACKUP) {
18036                Slog.e(TAG, "Didn't find start tag during restore");
18037            }
18038            return;
18039        }
18040Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18041        // this is supposed to be TAG_PREFERRED_BACKUP
18042        if (!expectedStartTag.equals(parser.getName())) {
18043            if (DEBUG_BACKUP) {
18044                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18045            }
18046            return;
18047        }
18048
18049        // skip interfering stuff, then we're aligned with the backing implementation
18050        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18051Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18052        functor.apply(parser, userId);
18053    }
18054
18055    private interface BlobXmlRestorer {
18056        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18057    }
18058
18059    /**
18060     * Non-Binder method, support for the backup/restore mechanism: write the
18061     * full set of preferred activities in its canonical XML format.  Returns the
18062     * XML output as a byte array, or null if there is none.
18063     */
18064    @Override
18065    public byte[] getPreferredActivityBackup(int userId) {
18066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18067            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18068        }
18069
18070        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18071        try {
18072            final XmlSerializer serializer = new FastXmlSerializer();
18073            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18074            serializer.startDocument(null, true);
18075            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18076
18077            synchronized (mPackages) {
18078                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18079            }
18080
18081            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18082            serializer.endDocument();
18083            serializer.flush();
18084        } catch (Exception e) {
18085            if (DEBUG_BACKUP) {
18086                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18087            }
18088            return null;
18089        }
18090
18091        return dataStream.toByteArray();
18092    }
18093
18094    @Override
18095    public void restorePreferredActivities(byte[] backup, int userId) {
18096        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18097            throw new SecurityException("Only the system may call restorePreferredActivities()");
18098        }
18099
18100        try {
18101            final XmlPullParser parser = Xml.newPullParser();
18102            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18103            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18104                    new BlobXmlRestorer() {
18105                        @Override
18106                        public void apply(XmlPullParser parser, int userId)
18107                                throws XmlPullParserException, IOException {
18108                            synchronized (mPackages) {
18109                                mSettings.readPreferredActivitiesLPw(parser, userId);
18110                            }
18111                        }
18112                    } );
18113        } catch (Exception e) {
18114            if (DEBUG_BACKUP) {
18115                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18116            }
18117        }
18118    }
18119
18120    /**
18121     * Non-Binder method, support for the backup/restore mechanism: write the
18122     * default browser (etc) settings in its canonical XML format.  Returns the default
18123     * browser XML representation as a byte array, or null if there is none.
18124     */
18125    @Override
18126    public byte[] getDefaultAppsBackup(int userId) {
18127        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18128            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18129        }
18130
18131        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18132        try {
18133            final XmlSerializer serializer = new FastXmlSerializer();
18134            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18135            serializer.startDocument(null, true);
18136            serializer.startTag(null, TAG_DEFAULT_APPS);
18137
18138            synchronized (mPackages) {
18139                mSettings.writeDefaultAppsLPr(serializer, userId);
18140            }
18141
18142            serializer.endTag(null, TAG_DEFAULT_APPS);
18143            serializer.endDocument();
18144            serializer.flush();
18145        } catch (Exception e) {
18146            if (DEBUG_BACKUP) {
18147                Slog.e(TAG, "Unable to write default apps for backup", e);
18148            }
18149            return null;
18150        }
18151
18152        return dataStream.toByteArray();
18153    }
18154
18155    @Override
18156    public void restoreDefaultApps(byte[] backup, int userId) {
18157        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18158            throw new SecurityException("Only the system may call restoreDefaultApps()");
18159        }
18160
18161        try {
18162            final XmlPullParser parser = Xml.newPullParser();
18163            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18164            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18165                    new BlobXmlRestorer() {
18166                        @Override
18167                        public void apply(XmlPullParser parser, int userId)
18168                                throws XmlPullParserException, IOException {
18169                            synchronized (mPackages) {
18170                                mSettings.readDefaultAppsLPw(parser, userId);
18171                            }
18172                        }
18173                    } );
18174        } catch (Exception e) {
18175            if (DEBUG_BACKUP) {
18176                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18177            }
18178        }
18179    }
18180
18181    @Override
18182    public byte[] getIntentFilterVerificationBackup(int userId) {
18183        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18184            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18185        }
18186
18187        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18188        try {
18189            final XmlSerializer serializer = new FastXmlSerializer();
18190            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18191            serializer.startDocument(null, true);
18192            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18193
18194            synchronized (mPackages) {
18195                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18196            }
18197
18198            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18199            serializer.endDocument();
18200            serializer.flush();
18201        } catch (Exception e) {
18202            if (DEBUG_BACKUP) {
18203                Slog.e(TAG, "Unable to write default apps for backup", e);
18204            }
18205            return null;
18206        }
18207
18208        return dataStream.toByteArray();
18209    }
18210
18211    @Override
18212    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18213        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18214            throw new SecurityException("Only the system may call restorePreferredActivities()");
18215        }
18216
18217        try {
18218            final XmlPullParser parser = Xml.newPullParser();
18219            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18220            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18221                    new BlobXmlRestorer() {
18222                        @Override
18223                        public void apply(XmlPullParser parser, int userId)
18224                                throws XmlPullParserException, IOException {
18225                            synchronized (mPackages) {
18226                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18227                                mSettings.writeLPr();
18228                            }
18229                        }
18230                    } );
18231        } catch (Exception e) {
18232            if (DEBUG_BACKUP) {
18233                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18234            }
18235        }
18236    }
18237
18238    @Override
18239    public byte[] getPermissionGrantBackup(int userId) {
18240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18241            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18242        }
18243
18244        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18245        try {
18246            final XmlSerializer serializer = new FastXmlSerializer();
18247            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18248            serializer.startDocument(null, true);
18249            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18250
18251            synchronized (mPackages) {
18252                serializeRuntimePermissionGrantsLPr(serializer, userId);
18253            }
18254
18255            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18256            serializer.endDocument();
18257            serializer.flush();
18258        } catch (Exception e) {
18259            if (DEBUG_BACKUP) {
18260                Slog.e(TAG, "Unable to write default apps for backup", e);
18261            }
18262            return null;
18263        }
18264
18265        return dataStream.toByteArray();
18266    }
18267
18268    @Override
18269    public void restorePermissionGrants(byte[] backup, int userId) {
18270        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18271            throw new SecurityException("Only the system may call restorePermissionGrants()");
18272        }
18273
18274        try {
18275            final XmlPullParser parser = Xml.newPullParser();
18276            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18277            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18278                    new BlobXmlRestorer() {
18279                        @Override
18280                        public void apply(XmlPullParser parser, int userId)
18281                                throws XmlPullParserException, IOException {
18282                            synchronized (mPackages) {
18283                                processRestoredPermissionGrantsLPr(parser, userId);
18284                            }
18285                        }
18286                    } );
18287        } catch (Exception e) {
18288            if (DEBUG_BACKUP) {
18289                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18290            }
18291        }
18292    }
18293
18294    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18295            throws IOException {
18296        serializer.startTag(null, TAG_ALL_GRANTS);
18297
18298        final int N = mSettings.mPackages.size();
18299        for (int i = 0; i < N; i++) {
18300            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18301            boolean pkgGrantsKnown = false;
18302
18303            PermissionsState packagePerms = ps.getPermissionsState();
18304
18305            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18306                final int grantFlags = state.getFlags();
18307                // only look at grants that are not system/policy fixed
18308                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18309                    final boolean isGranted = state.isGranted();
18310                    // And only back up the user-twiddled state bits
18311                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18312                        final String packageName = mSettings.mPackages.keyAt(i);
18313                        if (!pkgGrantsKnown) {
18314                            serializer.startTag(null, TAG_GRANT);
18315                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18316                            pkgGrantsKnown = true;
18317                        }
18318
18319                        final boolean userSet =
18320                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18321                        final boolean userFixed =
18322                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18323                        final boolean revoke =
18324                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18325
18326                        serializer.startTag(null, TAG_PERMISSION);
18327                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18328                        if (isGranted) {
18329                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18330                        }
18331                        if (userSet) {
18332                            serializer.attribute(null, ATTR_USER_SET, "true");
18333                        }
18334                        if (userFixed) {
18335                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18336                        }
18337                        if (revoke) {
18338                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18339                        }
18340                        serializer.endTag(null, TAG_PERMISSION);
18341                    }
18342                }
18343            }
18344
18345            if (pkgGrantsKnown) {
18346                serializer.endTag(null, TAG_GRANT);
18347            }
18348        }
18349
18350        serializer.endTag(null, TAG_ALL_GRANTS);
18351    }
18352
18353    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18354            throws XmlPullParserException, IOException {
18355        String pkgName = null;
18356        int outerDepth = parser.getDepth();
18357        int type;
18358        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18359                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18360            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18361                continue;
18362            }
18363
18364            final String tagName = parser.getName();
18365            if (tagName.equals(TAG_GRANT)) {
18366                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18367                if (DEBUG_BACKUP) {
18368                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18369                }
18370            } else if (tagName.equals(TAG_PERMISSION)) {
18371
18372                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18373                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18374
18375                int newFlagSet = 0;
18376                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18377                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18378                }
18379                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18380                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18381                }
18382                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18383                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18384                }
18385                if (DEBUG_BACKUP) {
18386                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18387                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18388                }
18389                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18390                if (ps != null) {
18391                    // Already installed so we apply the grant immediately
18392                    if (DEBUG_BACKUP) {
18393                        Slog.v(TAG, "        + already installed; applying");
18394                    }
18395                    PermissionsState perms = ps.getPermissionsState();
18396                    BasePermission bp = mSettings.mPermissions.get(permName);
18397                    if (bp != null) {
18398                        if (isGranted) {
18399                            perms.grantRuntimePermission(bp, userId);
18400                        }
18401                        if (newFlagSet != 0) {
18402                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18403                        }
18404                    }
18405                } else {
18406                    // Need to wait for post-restore install to apply the grant
18407                    if (DEBUG_BACKUP) {
18408                        Slog.v(TAG, "        - not yet installed; saving for later");
18409                    }
18410                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18411                            isGranted, newFlagSet, userId);
18412                }
18413            } else {
18414                PackageManagerService.reportSettingsProblem(Log.WARN,
18415                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18416                XmlUtils.skipCurrentTag(parser);
18417            }
18418        }
18419
18420        scheduleWriteSettingsLocked();
18421        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18422    }
18423
18424    @Override
18425    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18426            int sourceUserId, int targetUserId, int flags) {
18427        mContext.enforceCallingOrSelfPermission(
18428                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18429        int callingUid = Binder.getCallingUid();
18430        enforceOwnerRights(ownerPackage, callingUid);
18431        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18432        if (intentFilter.countActions() == 0) {
18433            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18434            return;
18435        }
18436        synchronized (mPackages) {
18437            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18438                    ownerPackage, targetUserId, flags);
18439            CrossProfileIntentResolver resolver =
18440                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18441            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18442            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18443            if (existing != null) {
18444                int size = existing.size();
18445                for (int i = 0; i < size; i++) {
18446                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18447                        return;
18448                    }
18449                }
18450            }
18451            resolver.addFilter(newFilter);
18452            scheduleWritePackageRestrictionsLocked(sourceUserId);
18453        }
18454    }
18455
18456    @Override
18457    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18458        mContext.enforceCallingOrSelfPermission(
18459                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18460        int callingUid = Binder.getCallingUid();
18461        enforceOwnerRights(ownerPackage, callingUid);
18462        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18463        synchronized (mPackages) {
18464            CrossProfileIntentResolver resolver =
18465                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18466            ArraySet<CrossProfileIntentFilter> set =
18467                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18468            for (CrossProfileIntentFilter filter : set) {
18469                if (filter.getOwnerPackage().equals(ownerPackage)) {
18470                    resolver.removeFilter(filter);
18471                }
18472            }
18473            scheduleWritePackageRestrictionsLocked(sourceUserId);
18474        }
18475    }
18476
18477    // Enforcing that callingUid is owning pkg on userId
18478    private void enforceOwnerRights(String pkg, int callingUid) {
18479        // The system owns everything.
18480        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18481            return;
18482        }
18483        int callingUserId = UserHandle.getUserId(callingUid);
18484        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18485        if (pi == null) {
18486            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18487                    + callingUserId);
18488        }
18489        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18490            throw new SecurityException("Calling uid " + callingUid
18491                    + " does not own package " + pkg);
18492        }
18493    }
18494
18495    @Override
18496    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18497        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18498    }
18499
18500    private Intent getHomeIntent() {
18501        Intent intent = new Intent(Intent.ACTION_MAIN);
18502        intent.addCategory(Intent.CATEGORY_HOME);
18503        intent.addCategory(Intent.CATEGORY_DEFAULT);
18504        return intent;
18505    }
18506
18507    private IntentFilter getHomeFilter() {
18508        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18509        filter.addCategory(Intent.CATEGORY_HOME);
18510        filter.addCategory(Intent.CATEGORY_DEFAULT);
18511        return filter;
18512    }
18513
18514    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18515            int userId) {
18516        Intent intent  = getHomeIntent();
18517        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18518                PackageManager.GET_META_DATA, userId);
18519        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18520                true, false, false, userId);
18521
18522        allHomeCandidates.clear();
18523        if (list != null) {
18524            for (ResolveInfo ri : list) {
18525                allHomeCandidates.add(ri);
18526            }
18527        }
18528        return (preferred == null || preferred.activityInfo == null)
18529                ? null
18530                : new ComponentName(preferred.activityInfo.packageName,
18531                        preferred.activityInfo.name);
18532    }
18533
18534    @Override
18535    public void setHomeActivity(ComponentName comp, int userId) {
18536        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18537        getHomeActivitiesAsUser(homeActivities, userId);
18538
18539        boolean found = false;
18540
18541        final int size = homeActivities.size();
18542        final ComponentName[] set = new ComponentName[size];
18543        for (int i = 0; i < size; i++) {
18544            final ResolveInfo candidate = homeActivities.get(i);
18545            final ActivityInfo info = candidate.activityInfo;
18546            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18547            set[i] = activityName;
18548            if (!found && activityName.equals(comp)) {
18549                found = true;
18550            }
18551        }
18552        if (!found) {
18553            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18554                    + userId);
18555        }
18556        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18557                set, comp, userId);
18558    }
18559
18560    private @Nullable String getSetupWizardPackageName() {
18561        final Intent intent = new Intent(Intent.ACTION_MAIN);
18562        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18563
18564        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18565                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18566                        | MATCH_DISABLED_COMPONENTS,
18567                UserHandle.myUserId());
18568        if (matches.size() == 1) {
18569            return matches.get(0).getComponentInfo().packageName;
18570        } else {
18571            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18572                    + ": matches=" + matches);
18573            return null;
18574        }
18575    }
18576
18577    private @Nullable String getStorageManagerPackageName() {
18578        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18579
18580        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18581                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18582                        | MATCH_DISABLED_COMPONENTS,
18583                UserHandle.myUserId());
18584        if (matches.size() == 1) {
18585            return matches.get(0).getComponentInfo().packageName;
18586        } else {
18587            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18588                    + matches.size() + ": matches=" + matches);
18589            return null;
18590        }
18591    }
18592
18593    @Override
18594    public void setApplicationEnabledSetting(String appPackageName,
18595            int newState, int flags, int userId, String callingPackage) {
18596        if (!sUserManager.exists(userId)) return;
18597        if (callingPackage == null) {
18598            callingPackage = Integer.toString(Binder.getCallingUid());
18599        }
18600        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18601    }
18602
18603    @Override
18604    public void setComponentEnabledSetting(ComponentName componentName,
18605            int newState, int flags, int userId) {
18606        if (!sUserManager.exists(userId)) return;
18607        setEnabledSetting(componentName.getPackageName(),
18608                componentName.getClassName(), newState, flags, userId, null);
18609    }
18610
18611    private void setEnabledSetting(final String packageName, String className, int newState,
18612            final int flags, int userId, String callingPackage) {
18613        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18614              || newState == COMPONENT_ENABLED_STATE_ENABLED
18615              || newState == COMPONENT_ENABLED_STATE_DISABLED
18616              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18617              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18618            throw new IllegalArgumentException("Invalid new component state: "
18619                    + newState);
18620        }
18621        PackageSetting pkgSetting;
18622        final int uid = Binder.getCallingUid();
18623        final int permission;
18624        if (uid == Process.SYSTEM_UID) {
18625            permission = PackageManager.PERMISSION_GRANTED;
18626        } else {
18627            permission = mContext.checkCallingOrSelfPermission(
18628                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18629        }
18630        enforceCrossUserPermission(uid, userId,
18631                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18632        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18633        boolean sendNow = false;
18634        boolean isApp = (className == null);
18635        String componentName = isApp ? packageName : className;
18636        int packageUid = -1;
18637        ArrayList<String> components;
18638
18639        // writer
18640        synchronized (mPackages) {
18641            pkgSetting = mSettings.mPackages.get(packageName);
18642            if (pkgSetting == null) {
18643                if (className == null) {
18644                    throw new IllegalArgumentException("Unknown package: " + packageName);
18645                }
18646                throw new IllegalArgumentException(
18647                        "Unknown component: " + packageName + "/" + className);
18648            }
18649        }
18650
18651        // Limit who can change which apps
18652        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18653            // Don't allow apps that don't have permission to modify other apps
18654            if (!allowedByPermission) {
18655                throw new SecurityException(
18656                        "Permission Denial: attempt to change component state from pid="
18657                        + Binder.getCallingPid()
18658                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18659            }
18660            // Don't allow changing protected packages.
18661            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18662                throw new SecurityException("Cannot disable a protected package: " + packageName);
18663            }
18664        }
18665
18666        synchronized (mPackages) {
18667            if (uid == Process.SHELL_UID
18668                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18669                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18670                // unless it is a test package.
18671                int oldState = pkgSetting.getEnabled(userId);
18672                if (className == null
18673                    &&
18674                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18675                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18676                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18677                    &&
18678                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18679                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18680                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18681                    // ok
18682                } else {
18683                    throw new SecurityException(
18684                            "Shell cannot change component state for " + packageName + "/"
18685                            + className + " to " + newState);
18686                }
18687            }
18688            if (className == null) {
18689                // We're dealing with an application/package level state change
18690                if (pkgSetting.getEnabled(userId) == newState) {
18691                    // Nothing to do
18692                    return;
18693                }
18694                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18695                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18696                    // Don't care about who enables an app.
18697                    callingPackage = null;
18698                }
18699                pkgSetting.setEnabled(newState, userId, callingPackage);
18700                // pkgSetting.pkg.mSetEnabled = newState;
18701            } else {
18702                // We're dealing with a component level state change
18703                // First, verify that this is a valid class name.
18704                PackageParser.Package pkg = pkgSetting.pkg;
18705                if (pkg == null || !pkg.hasComponentClassName(className)) {
18706                    if (pkg != null &&
18707                            pkg.applicationInfo.targetSdkVersion >=
18708                                    Build.VERSION_CODES.JELLY_BEAN) {
18709                        throw new IllegalArgumentException("Component class " + className
18710                                + " does not exist in " + packageName);
18711                    } else {
18712                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18713                                + className + " does not exist in " + packageName);
18714                    }
18715                }
18716                switch (newState) {
18717                case COMPONENT_ENABLED_STATE_ENABLED:
18718                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18719                        return;
18720                    }
18721                    break;
18722                case COMPONENT_ENABLED_STATE_DISABLED:
18723                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18724                        return;
18725                    }
18726                    break;
18727                case COMPONENT_ENABLED_STATE_DEFAULT:
18728                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18729                        return;
18730                    }
18731                    break;
18732                default:
18733                    Slog.e(TAG, "Invalid new component state: " + newState);
18734                    return;
18735                }
18736            }
18737            scheduleWritePackageRestrictionsLocked(userId);
18738            components = mPendingBroadcasts.get(userId, packageName);
18739            final boolean newPackage = components == null;
18740            if (newPackage) {
18741                components = new ArrayList<String>();
18742            }
18743            if (!components.contains(componentName)) {
18744                components.add(componentName);
18745            }
18746            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18747                sendNow = true;
18748                // Purge entry from pending broadcast list if another one exists already
18749                // since we are sending one right away.
18750                mPendingBroadcasts.remove(userId, packageName);
18751            } else {
18752                if (newPackage) {
18753                    mPendingBroadcasts.put(userId, packageName, components);
18754                }
18755                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18756                    // Schedule a message
18757                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18758                }
18759            }
18760        }
18761
18762        long callingId = Binder.clearCallingIdentity();
18763        try {
18764            if (sendNow) {
18765                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18766                sendPackageChangedBroadcast(packageName,
18767                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18768            }
18769        } finally {
18770            Binder.restoreCallingIdentity(callingId);
18771        }
18772    }
18773
18774    @Override
18775    public void flushPackageRestrictionsAsUser(int userId) {
18776        if (!sUserManager.exists(userId)) {
18777            return;
18778        }
18779        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18780                false /* checkShell */, "flushPackageRestrictions");
18781        synchronized (mPackages) {
18782            mSettings.writePackageRestrictionsLPr(userId);
18783            mDirtyUsers.remove(userId);
18784            if (mDirtyUsers.isEmpty()) {
18785                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18786            }
18787        }
18788    }
18789
18790    private void sendPackageChangedBroadcast(String packageName,
18791            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18792        if (DEBUG_INSTALL)
18793            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18794                    + componentNames);
18795        Bundle extras = new Bundle(4);
18796        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18797        String nameList[] = new String[componentNames.size()];
18798        componentNames.toArray(nameList);
18799        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18800        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18801        extras.putInt(Intent.EXTRA_UID, packageUid);
18802        // If this is not reporting a change of the overall package, then only send it
18803        // to registered receivers.  We don't want to launch a swath of apps for every
18804        // little component state change.
18805        final int flags = !componentNames.contains(packageName)
18806                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18807        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18808                new int[] {UserHandle.getUserId(packageUid)});
18809    }
18810
18811    @Override
18812    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18813        if (!sUserManager.exists(userId)) return;
18814        final int uid = Binder.getCallingUid();
18815        final int permission = mContext.checkCallingOrSelfPermission(
18816                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18817        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18818        enforceCrossUserPermission(uid, userId,
18819                true /* requireFullPermission */, true /* checkShell */, "stop package");
18820        // writer
18821        synchronized (mPackages) {
18822            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18823                    allowedByPermission, uid, userId)) {
18824                scheduleWritePackageRestrictionsLocked(userId);
18825            }
18826        }
18827    }
18828
18829    @Override
18830    public String getInstallerPackageName(String packageName) {
18831        // reader
18832        synchronized (mPackages) {
18833            return mSettings.getInstallerPackageNameLPr(packageName);
18834        }
18835    }
18836
18837    public boolean isOrphaned(String packageName) {
18838        // reader
18839        synchronized (mPackages) {
18840            return mSettings.isOrphaned(packageName);
18841        }
18842    }
18843
18844    @Override
18845    public int getApplicationEnabledSetting(String packageName, int userId) {
18846        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18847        int uid = Binder.getCallingUid();
18848        enforceCrossUserPermission(uid, userId,
18849                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18850        // reader
18851        synchronized (mPackages) {
18852            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18853        }
18854    }
18855
18856    @Override
18857    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18858        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18859        int uid = Binder.getCallingUid();
18860        enforceCrossUserPermission(uid, userId,
18861                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18862        // reader
18863        synchronized (mPackages) {
18864            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18865        }
18866    }
18867
18868    @Override
18869    public void enterSafeMode() {
18870        enforceSystemOrRoot("Only the system can request entering safe mode");
18871
18872        if (!mSystemReady) {
18873            mSafeMode = true;
18874        }
18875    }
18876
18877    @Override
18878    public void systemReady() {
18879        mSystemReady = true;
18880
18881        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18882        // disabled after already being started.
18883        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18884                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18885
18886        // Read the compatibilty setting when the system is ready.
18887        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18888                mContext.getContentResolver(),
18889                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18890        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18891        if (DEBUG_SETTINGS) {
18892            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18893        }
18894
18895        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18896
18897        synchronized (mPackages) {
18898            // Verify that all of the preferred activity components actually
18899            // exist.  It is possible for applications to be updated and at
18900            // that point remove a previously declared activity component that
18901            // had been set as a preferred activity.  We try to clean this up
18902            // the next time we encounter that preferred activity, but it is
18903            // possible for the user flow to never be able to return to that
18904            // situation so here we do a sanity check to make sure we haven't
18905            // left any junk around.
18906            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18907            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18908                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18909                removed.clear();
18910                for (PreferredActivity pa : pir.filterSet()) {
18911                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18912                        removed.add(pa);
18913                    }
18914                }
18915                if (removed.size() > 0) {
18916                    for (int r=0; r<removed.size(); r++) {
18917                        PreferredActivity pa = removed.get(r);
18918                        Slog.w(TAG, "Removing dangling preferred activity: "
18919                                + pa.mPref.mComponent);
18920                        pir.removeFilter(pa);
18921                    }
18922                    mSettings.writePackageRestrictionsLPr(
18923                            mSettings.mPreferredActivities.keyAt(i));
18924                }
18925            }
18926
18927            for (int userId : UserManagerService.getInstance().getUserIds()) {
18928                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18929                    grantPermissionsUserIds = ArrayUtils.appendInt(
18930                            grantPermissionsUserIds, userId);
18931                }
18932            }
18933        }
18934        sUserManager.systemReady();
18935
18936        // If we upgraded grant all default permissions before kicking off.
18937        for (int userId : grantPermissionsUserIds) {
18938            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18939        }
18940
18941        // If we did not grant default permissions, we preload from this the
18942        // default permission exceptions lazily to ensure we don't hit the
18943        // disk on a new user creation.
18944        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18945            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18946        }
18947
18948        // Kick off any messages waiting for system ready
18949        if (mPostSystemReadyMessages != null) {
18950            for (Message msg : mPostSystemReadyMessages) {
18951                msg.sendToTarget();
18952            }
18953            mPostSystemReadyMessages = null;
18954        }
18955
18956        // Watch for external volumes that come and go over time
18957        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18958        storage.registerListener(mStorageListener);
18959
18960        mInstallerService.systemReady();
18961        mPackageDexOptimizer.systemReady();
18962
18963        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18964                StorageManagerInternal.class);
18965        StorageManagerInternal.addExternalStoragePolicy(
18966                new StorageManagerInternal.ExternalStorageMountPolicy() {
18967            @Override
18968            public int getMountMode(int uid, String packageName) {
18969                if (Process.isIsolated(uid)) {
18970                    return Zygote.MOUNT_EXTERNAL_NONE;
18971                }
18972                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18973                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18974                }
18975                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18976                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18977                }
18978                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18979                    return Zygote.MOUNT_EXTERNAL_READ;
18980                }
18981                return Zygote.MOUNT_EXTERNAL_WRITE;
18982            }
18983
18984            @Override
18985            public boolean hasExternalStorage(int uid, String packageName) {
18986                return true;
18987            }
18988        });
18989
18990        // Now that we're mostly running, clean up stale users and apps
18991        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18992        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18993    }
18994
18995    @Override
18996    public boolean isSafeMode() {
18997        return mSafeMode;
18998    }
18999
19000    @Override
19001    public boolean hasSystemUidErrors() {
19002        return mHasSystemUidErrors;
19003    }
19004
19005    static String arrayToString(int[] array) {
19006        StringBuffer buf = new StringBuffer(128);
19007        buf.append('[');
19008        if (array != null) {
19009            for (int i=0; i<array.length; i++) {
19010                if (i > 0) buf.append(", ");
19011                buf.append(array[i]);
19012            }
19013        }
19014        buf.append(']');
19015        return buf.toString();
19016    }
19017
19018    static class DumpState {
19019        public static final int DUMP_LIBS = 1 << 0;
19020        public static final int DUMP_FEATURES = 1 << 1;
19021        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19022        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19023        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19024        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19025        public static final int DUMP_PERMISSIONS = 1 << 6;
19026        public static final int DUMP_PACKAGES = 1 << 7;
19027        public static final int DUMP_SHARED_USERS = 1 << 8;
19028        public static final int DUMP_MESSAGES = 1 << 9;
19029        public static final int DUMP_PROVIDERS = 1 << 10;
19030        public static final int DUMP_VERIFIERS = 1 << 11;
19031        public static final int DUMP_PREFERRED = 1 << 12;
19032        public static final int DUMP_PREFERRED_XML = 1 << 13;
19033        public static final int DUMP_KEYSETS = 1 << 14;
19034        public static final int DUMP_VERSION = 1 << 15;
19035        public static final int DUMP_INSTALLS = 1 << 16;
19036        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19037        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19038        public static final int DUMP_FROZEN = 1 << 19;
19039        public static final int DUMP_DEXOPT = 1 << 20;
19040        public static final int DUMP_COMPILER_STATS = 1 << 21;
19041
19042        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19043
19044        private int mTypes;
19045
19046        private int mOptions;
19047
19048        private boolean mTitlePrinted;
19049
19050        private SharedUserSetting mSharedUser;
19051
19052        public boolean isDumping(int type) {
19053            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19054                return true;
19055            }
19056
19057            return (mTypes & type) != 0;
19058        }
19059
19060        public void setDump(int type) {
19061            mTypes |= type;
19062        }
19063
19064        public boolean isOptionEnabled(int option) {
19065            return (mOptions & option) != 0;
19066        }
19067
19068        public void setOptionEnabled(int option) {
19069            mOptions |= option;
19070        }
19071
19072        public boolean onTitlePrinted() {
19073            final boolean printed = mTitlePrinted;
19074            mTitlePrinted = true;
19075            return printed;
19076        }
19077
19078        public boolean getTitlePrinted() {
19079            return mTitlePrinted;
19080        }
19081
19082        public void setTitlePrinted(boolean enabled) {
19083            mTitlePrinted = enabled;
19084        }
19085
19086        public SharedUserSetting getSharedUser() {
19087            return mSharedUser;
19088        }
19089
19090        public void setSharedUser(SharedUserSetting user) {
19091            mSharedUser = user;
19092        }
19093    }
19094
19095    @Override
19096    public void onShellCommand(FileDescriptor in, FileDescriptor out,
19097            FileDescriptor err, String[] args, ShellCallback callback,
19098            ResultReceiver resultReceiver) {
19099        (new PackageManagerShellCommand(this)).exec(
19100                this, in, out, err, args, callback, resultReceiver);
19101    }
19102
19103    @Override
19104    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
19105        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
19106                != PackageManager.PERMISSION_GRANTED) {
19107            pw.println("Permission Denial: can't dump ActivityManager from from pid="
19108                    + Binder.getCallingPid()
19109                    + ", uid=" + Binder.getCallingUid()
19110                    + " without permission "
19111                    + android.Manifest.permission.DUMP);
19112            return;
19113        }
19114
19115        DumpState dumpState = new DumpState();
19116        boolean fullPreferred = false;
19117        boolean checkin = false;
19118
19119        String packageName = null;
19120        ArraySet<String> permissionNames = null;
19121
19122        int opti = 0;
19123        while (opti < args.length) {
19124            String opt = args[opti];
19125            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
19126                break;
19127            }
19128            opti++;
19129
19130            if ("-a".equals(opt)) {
19131                // Right now we only know how to print all.
19132            } else if ("-h".equals(opt)) {
19133                pw.println("Package manager dump options:");
19134                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
19135                pw.println("    --checkin: dump for a checkin");
19136                pw.println("    -f: print details of intent filters");
19137                pw.println("    -h: print this help");
19138                pw.println("  cmd may be one of:");
19139                pw.println("    l[ibraries]: list known shared libraries");
19140                pw.println("    f[eatures]: list device features");
19141                pw.println("    k[eysets]: print known keysets");
19142                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
19143                pw.println("    perm[issions]: dump permissions");
19144                pw.println("    permission [name ...]: dump declaration and use of given permission");
19145                pw.println("    pref[erred]: print preferred package settings");
19146                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
19147                pw.println("    prov[iders]: dump content providers");
19148                pw.println("    p[ackages]: dump installed packages");
19149                pw.println("    s[hared-users]: dump shared user IDs");
19150                pw.println("    m[essages]: print collected runtime messages");
19151                pw.println("    v[erifiers]: print package verifier info");
19152                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
19153                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
19154                pw.println("    version: print database version info");
19155                pw.println("    write: write current settings now");
19156                pw.println("    installs: details about install sessions");
19157                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
19158                pw.println("    dexopt: dump dexopt state");
19159                pw.println("    compiler-stats: dump compiler statistics");
19160                pw.println("    <package.name>: info about given package");
19161                return;
19162            } else if ("--checkin".equals(opt)) {
19163                checkin = true;
19164            } else if ("-f".equals(opt)) {
19165                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19166            } else {
19167                pw.println("Unknown argument: " + opt + "; use -h for help");
19168            }
19169        }
19170
19171        // Is the caller requesting to dump a particular piece of data?
19172        if (opti < args.length) {
19173            String cmd = args[opti];
19174            opti++;
19175            // Is this a package name?
19176            if ("android".equals(cmd) || cmd.contains(".")) {
19177                packageName = cmd;
19178                // When dumping a single package, we always dump all of its
19179                // filter information since the amount of data will be reasonable.
19180                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19181            } else if ("check-permission".equals(cmd)) {
19182                if (opti >= args.length) {
19183                    pw.println("Error: check-permission missing permission argument");
19184                    return;
19185                }
19186                String perm = args[opti];
19187                opti++;
19188                if (opti >= args.length) {
19189                    pw.println("Error: check-permission missing package argument");
19190                    return;
19191                }
19192                String pkg = args[opti];
19193                opti++;
19194                int user = UserHandle.getUserId(Binder.getCallingUid());
19195                if (opti < args.length) {
19196                    try {
19197                        user = Integer.parseInt(args[opti]);
19198                    } catch (NumberFormatException e) {
19199                        pw.println("Error: check-permission user argument is not a number: "
19200                                + args[opti]);
19201                        return;
19202                    }
19203                }
19204                pw.println(checkPermission(perm, pkg, user));
19205                return;
19206            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
19207                dumpState.setDump(DumpState.DUMP_LIBS);
19208            } else if ("f".equals(cmd) || "features".equals(cmd)) {
19209                dumpState.setDump(DumpState.DUMP_FEATURES);
19210            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
19211                if (opti >= args.length) {
19212                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
19213                            | DumpState.DUMP_SERVICE_RESOLVERS
19214                            | DumpState.DUMP_RECEIVER_RESOLVERS
19215                            | DumpState.DUMP_CONTENT_RESOLVERS);
19216                } else {
19217                    while (opti < args.length) {
19218                        String name = args[opti];
19219                        if ("a".equals(name) || "activity".equals(name)) {
19220                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
19221                        } else if ("s".equals(name) || "service".equals(name)) {
19222                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
19223                        } else if ("r".equals(name) || "receiver".equals(name)) {
19224                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19225                        } else if ("c".equals(name) || "content".equals(name)) {
19226                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19227                        } else {
19228                            pw.println("Error: unknown resolver table type: " + name);
19229                            return;
19230                        }
19231                        opti++;
19232                    }
19233                }
19234            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19235                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19236            } else if ("permission".equals(cmd)) {
19237                if (opti >= args.length) {
19238                    pw.println("Error: permission requires permission name");
19239                    return;
19240                }
19241                permissionNames = new ArraySet<>();
19242                while (opti < args.length) {
19243                    permissionNames.add(args[opti]);
19244                    opti++;
19245                }
19246                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19247                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19248            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19249                dumpState.setDump(DumpState.DUMP_PREFERRED);
19250            } else if ("preferred-xml".equals(cmd)) {
19251                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19252                if (opti < args.length && "--full".equals(args[opti])) {
19253                    fullPreferred = true;
19254                    opti++;
19255                }
19256            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19257                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19258            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19259                dumpState.setDump(DumpState.DUMP_PACKAGES);
19260            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19261                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19262            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19263                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19264            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19265                dumpState.setDump(DumpState.DUMP_MESSAGES);
19266            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19267                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19268            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19269                    || "intent-filter-verifiers".equals(cmd)) {
19270                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19271            } else if ("version".equals(cmd)) {
19272                dumpState.setDump(DumpState.DUMP_VERSION);
19273            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19274                dumpState.setDump(DumpState.DUMP_KEYSETS);
19275            } else if ("installs".equals(cmd)) {
19276                dumpState.setDump(DumpState.DUMP_INSTALLS);
19277            } else if ("frozen".equals(cmd)) {
19278                dumpState.setDump(DumpState.DUMP_FROZEN);
19279            } else if ("dexopt".equals(cmd)) {
19280                dumpState.setDump(DumpState.DUMP_DEXOPT);
19281            } else if ("compiler-stats".equals(cmd)) {
19282                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19283            } else if ("write".equals(cmd)) {
19284                synchronized (mPackages) {
19285                    mSettings.writeLPr();
19286                    pw.println("Settings written.");
19287                    return;
19288                }
19289            }
19290        }
19291
19292        if (checkin) {
19293            pw.println("vers,1");
19294        }
19295
19296        // reader
19297        synchronized (mPackages) {
19298            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19299                if (!checkin) {
19300                    if (dumpState.onTitlePrinted())
19301                        pw.println();
19302                    pw.println("Database versions:");
19303                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19304                }
19305            }
19306
19307            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19308                if (!checkin) {
19309                    if (dumpState.onTitlePrinted())
19310                        pw.println();
19311                    pw.println("Verifiers:");
19312                    pw.print("  Required: ");
19313                    pw.print(mRequiredVerifierPackage);
19314                    pw.print(" (uid=");
19315                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19316                            UserHandle.USER_SYSTEM));
19317                    pw.println(")");
19318                } else if (mRequiredVerifierPackage != null) {
19319                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19320                    pw.print(",");
19321                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19322                            UserHandle.USER_SYSTEM));
19323                }
19324            }
19325
19326            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19327                    packageName == null) {
19328                if (mIntentFilterVerifierComponent != null) {
19329                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19330                    if (!checkin) {
19331                        if (dumpState.onTitlePrinted())
19332                            pw.println();
19333                        pw.println("Intent Filter Verifier:");
19334                        pw.print("  Using: ");
19335                        pw.print(verifierPackageName);
19336                        pw.print(" (uid=");
19337                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19338                                UserHandle.USER_SYSTEM));
19339                        pw.println(")");
19340                    } else if (verifierPackageName != null) {
19341                        pw.print("ifv,"); pw.print(verifierPackageName);
19342                        pw.print(",");
19343                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19344                                UserHandle.USER_SYSTEM));
19345                    }
19346                } else {
19347                    pw.println();
19348                    pw.println("No Intent Filter Verifier available!");
19349                }
19350            }
19351
19352            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19353                boolean printedHeader = false;
19354                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19355                while (it.hasNext()) {
19356                    String name = it.next();
19357                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19358                    if (!checkin) {
19359                        if (!printedHeader) {
19360                            if (dumpState.onTitlePrinted())
19361                                pw.println();
19362                            pw.println("Libraries:");
19363                            printedHeader = true;
19364                        }
19365                        pw.print("  ");
19366                    } else {
19367                        pw.print("lib,");
19368                    }
19369                    pw.print(name);
19370                    if (!checkin) {
19371                        pw.print(" -> ");
19372                    }
19373                    if (ent.path != null) {
19374                        if (!checkin) {
19375                            pw.print("(jar) ");
19376                            pw.print(ent.path);
19377                        } else {
19378                            pw.print(",jar,");
19379                            pw.print(ent.path);
19380                        }
19381                    } else {
19382                        if (!checkin) {
19383                            pw.print("(apk) ");
19384                            pw.print(ent.apk);
19385                        } else {
19386                            pw.print(",apk,");
19387                            pw.print(ent.apk);
19388                        }
19389                    }
19390                    pw.println();
19391                }
19392            }
19393
19394            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19395                if (dumpState.onTitlePrinted())
19396                    pw.println();
19397                if (!checkin) {
19398                    pw.println("Features:");
19399                }
19400
19401                for (FeatureInfo feat : mAvailableFeatures.values()) {
19402                    if (checkin) {
19403                        pw.print("feat,");
19404                        pw.print(feat.name);
19405                        pw.print(",");
19406                        pw.println(feat.version);
19407                    } else {
19408                        pw.print("  ");
19409                        pw.print(feat.name);
19410                        if (feat.version > 0) {
19411                            pw.print(" version=");
19412                            pw.print(feat.version);
19413                        }
19414                        pw.println();
19415                    }
19416                }
19417            }
19418
19419            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19420                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19421                        : "Activity Resolver Table:", "  ", packageName,
19422                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19423                    dumpState.setTitlePrinted(true);
19424                }
19425            }
19426            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19427                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19428                        : "Receiver Resolver Table:", "  ", packageName,
19429                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19430                    dumpState.setTitlePrinted(true);
19431                }
19432            }
19433            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19434                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19435                        : "Service Resolver Table:", "  ", packageName,
19436                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19437                    dumpState.setTitlePrinted(true);
19438                }
19439            }
19440            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19441                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19442                        : "Provider Resolver Table:", "  ", packageName,
19443                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19444                    dumpState.setTitlePrinted(true);
19445                }
19446            }
19447
19448            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19449                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19450                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19451                    int user = mSettings.mPreferredActivities.keyAt(i);
19452                    if (pir.dump(pw,
19453                            dumpState.getTitlePrinted()
19454                                ? "\nPreferred Activities User " + user + ":"
19455                                : "Preferred Activities User " + user + ":", "  ",
19456                            packageName, true, false)) {
19457                        dumpState.setTitlePrinted(true);
19458                    }
19459                }
19460            }
19461
19462            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19463                pw.flush();
19464                FileOutputStream fout = new FileOutputStream(fd);
19465                BufferedOutputStream str = new BufferedOutputStream(fout);
19466                XmlSerializer serializer = new FastXmlSerializer();
19467                try {
19468                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19469                    serializer.startDocument(null, true);
19470                    serializer.setFeature(
19471                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19472                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19473                    serializer.endDocument();
19474                    serializer.flush();
19475                } catch (IllegalArgumentException e) {
19476                    pw.println("Failed writing: " + e);
19477                } catch (IllegalStateException e) {
19478                    pw.println("Failed writing: " + e);
19479                } catch (IOException e) {
19480                    pw.println("Failed writing: " + e);
19481                }
19482            }
19483
19484            if (!checkin
19485                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19486                    && packageName == null) {
19487                pw.println();
19488                int count = mSettings.mPackages.size();
19489                if (count == 0) {
19490                    pw.println("No applications!");
19491                    pw.println();
19492                } else {
19493                    final String prefix = "  ";
19494                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19495                    if (allPackageSettings.size() == 0) {
19496                        pw.println("No domain preferred apps!");
19497                        pw.println();
19498                    } else {
19499                        pw.println("App verification status:");
19500                        pw.println();
19501                        count = 0;
19502                        for (PackageSetting ps : allPackageSettings) {
19503                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19504                            if (ivi == null || ivi.getPackageName() == null) continue;
19505                            pw.println(prefix + "Package: " + ivi.getPackageName());
19506                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19507                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19508                            pw.println();
19509                            count++;
19510                        }
19511                        if (count == 0) {
19512                            pw.println(prefix + "No app verification established.");
19513                            pw.println();
19514                        }
19515                        for (int userId : sUserManager.getUserIds()) {
19516                            pw.println("App linkages for user " + userId + ":");
19517                            pw.println();
19518                            count = 0;
19519                            for (PackageSetting ps : allPackageSettings) {
19520                                final long status = ps.getDomainVerificationStatusForUser(userId);
19521                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
19522                                        && !DEBUG_DOMAIN_VERIFICATION) {
19523                                    continue;
19524                                }
19525                                pw.println(prefix + "Package: " + ps.name);
19526                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19527                                String statusStr = IntentFilterVerificationInfo.
19528                                        getStatusStringFromValue(status);
19529                                pw.println(prefix + "Status:  " + statusStr);
19530                                pw.println();
19531                                count++;
19532                            }
19533                            if (count == 0) {
19534                                pw.println(prefix + "No configured app linkages.");
19535                                pw.println();
19536                            }
19537                        }
19538                    }
19539                }
19540            }
19541
19542            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19543                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19544                if (packageName == null && permissionNames == null) {
19545                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19546                        if (iperm == 0) {
19547                            if (dumpState.onTitlePrinted())
19548                                pw.println();
19549                            pw.println("AppOp Permissions:");
19550                        }
19551                        pw.print("  AppOp Permission ");
19552                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19553                        pw.println(":");
19554                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19555                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19556                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19557                        }
19558                    }
19559                }
19560            }
19561
19562            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19563                boolean printedSomething = false;
19564                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19565                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19566                        continue;
19567                    }
19568                    if (!printedSomething) {
19569                        if (dumpState.onTitlePrinted())
19570                            pw.println();
19571                        pw.println("Registered ContentProviders:");
19572                        printedSomething = true;
19573                    }
19574                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19575                    pw.print("    "); pw.println(p.toString());
19576                }
19577                printedSomething = false;
19578                for (Map.Entry<String, PackageParser.Provider> entry :
19579                        mProvidersByAuthority.entrySet()) {
19580                    PackageParser.Provider p = entry.getValue();
19581                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19582                        continue;
19583                    }
19584                    if (!printedSomething) {
19585                        if (dumpState.onTitlePrinted())
19586                            pw.println();
19587                        pw.println("ContentProvider Authorities:");
19588                        printedSomething = true;
19589                    }
19590                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19591                    pw.print("    "); pw.println(p.toString());
19592                    if (p.info != null && p.info.applicationInfo != null) {
19593                        final String appInfo = p.info.applicationInfo.toString();
19594                        pw.print("      applicationInfo="); pw.println(appInfo);
19595                    }
19596                }
19597            }
19598
19599            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19600                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19601            }
19602
19603            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19604                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19605            }
19606
19607            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19608                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19609            }
19610
19611            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19612                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19613            }
19614
19615            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19616                // XXX should handle packageName != null by dumping only install data that
19617                // the given package is involved with.
19618                if (dumpState.onTitlePrinted()) pw.println();
19619                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19620            }
19621
19622            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19623                // XXX should handle packageName != null by dumping only install data that
19624                // the given package is involved with.
19625                if (dumpState.onTitlePrinted()) pw.println();
19626
19627                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19628                ipw.println();
19629                ipw.println("Frozen packages:");
19630                ipw.increaseIndent();
19631                if (mFrozenPackages.size() == 0) {
19632                    ipw.println("(none)");
19633                } else {
19634                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19635                        ipw.println(mFrozenPackages.valueAt(i));
19636                    }
19637                }
19638                ipw.decreaseIndent();
19639            }
19640
19641            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19642                if (dumpState.onTitlePrinted()) pw.println();
19643                dumpDexoptStateLPr(pw, packageName);
19644            }
19645
19646            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19647                if (dumpState.onTitlePrinted()) pw.println();
19648                dumpCompilerStatsLPr(pw, packageName);
19649            }
19650
19651            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19652                if (dumpState.onTitlePrinted()) pw.println();
19653                mSettings.dumpReadMessagesLPr(pw, dumpState);
19654
19655                pw.println();
19656                pw.println("Package warning messages:");
19657                BufferedReader in = null;
19658                String line = null;
19659                try {
19660                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19661                    while ((line = in.readLine()) != null) {
19662                        if (line.contains("ignored: updated version")) continue;
19663                        pw.println(line);
19664                    }
19665                } catch (IOException ignored) {
19666                } finally {
19667                    IoUtils.closeQuietly(in);
19668                }
19669            }
19670
19671            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19672                BufferedReader in = null;
19673                String line = null;
19674                try {
19675                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19676                    while ((line = in.readLine()) != null) {
19677                        if (line.contains("ignored: updated version")) continue;
19678                        pw.print("msg,");
19679                        pw.println(line);
19680                    }
19681                } catch (IOException ignored) {
19682                } finally {
19683                    IoUtils.closeQuietly(in);
19684                }
19685            }
19686        }
19687    }
19688
19689    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19690        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19691        ipw.println();
19692        ipw.println("Dexopt state:");
19693        ipw.increaseIndent();
19694        Collection<PackageParser.Package> packages = null;
19695        if (packageName != null) {
19696            PackageParser.Package targetPackage = mPackages.get(packageName);
19697            if (targetPackage != null) {
19698                packages = Collections.singletonList(targetPackage);
19699            } else {
19700                ipw.println("Unable to find package: " + packageName);
19701                return;
19702            }
19703        } else {
19704            packages = mPackages.values();
19705        }
19706
19707        for (PackageParser.Package pkg : packages) {
19708            ipw.println("[" + pkg.packageName + "]");
19709            ipw.increaseIndent();
19710            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19711            ipw.decreaseIndent();
19712        }
19713    }
19714
19715    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19716        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19717        ipw.println();
19718        ipw.println("Compiler stats:");
19719        ipw.increaseIndent();
19720        Collection<PackageParser.Package> packages = null;
19721        if (packageName != null) {
19722            PackageParser.Package targetPackage = mPackages.get(packageName);
19723            if (targetPackage != null) {
19724                packages = Collections.singletonList(targetPackage);
19725            } else {
19726                ipw.println("Unable to find package: " + packageName);
19727                return;
19728            }
19729        } else {
19730            packages = mPackages.values();
19731        }
19732
19733        for (PackageParser.Package pkg : packages) {
19734            ipw.println("[" + pkg.packageName + "]");
19735            ipw.increaseIndent();
19736
19737            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19738            if (stats == null) {
19739                ipw.println("(No recorded stats)");
19740            } else {
19741                stats.dump(ipw);
19742            }
19743            ipw.decreaseIndent();
19744        }
19745    }
19746
19747    private String dumpDomainString(String packageName) {
19748        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19749                .getList();
19750        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19751
19752        ArraySet<String> result = new ArraySet<>();
19753        if (iviList.size() > 0) {
19754            for (IntentFilterVerificationInfo ivi : iviList) {
19755                for (String host : ivi.getDomains()) {
19756                    result.add(host);
19757                }
19758            }
19759        }
19760        if (filters != null && filters.size() > 0) {
19761            for (IntentFilter filter : filters) {
19762                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19763                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19764                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19765                    result.addAll(filter.getHostsList());
19766                }
19767            }
19768        }
19769
19770        StringBuilder sb = new StringBuilder(result.size() * 16);
19771        for (String domain : result) {
19772            if (sb.length() > 0) sb.append(" ");
19773            sb.append(domain);
19774        }
19775        return sb.toString();
19776    }
19777
19778    // ------- apps on sdcard specific code -------
19779    static final boolean DEBUG_SD_INSTALL = false;
19780
19781    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19782
19783    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19784
19785    private boolean mMediaMounted = false;
19786
19787    static String getEncryptKey() {
19788        try {
19789            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19790                    SD_ENCRYPTION_KEYSTORE_NAME);
19791            if (sdEncKey == null) {
19792                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19793                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19794                if (sdEncKey == null) {
19795                    Slog.e(TAG, "Failed to create encryption keys");
19796                    return null;
19797                }
19798            }
19799            return sdEncKey;
19800        } catch (NoSuchAlgorithmException nsae) {
19801            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19802            return null;
19803        } catch (IOException ioe) {
19804            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19805            return null;
19806        }
19807    }
19808
19809    /*
19810     * Update media status on PackageManager.
19811     */
19812    @Override
19813    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19814        int callingUid = Binder.getCallingUid();
19815        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19816            throw new SecurityException("Media status can only be updated by the system");
19817        }
19818        // reader; this apparently protects mMediaMounted, but should probably
19819        // be a different lock in that case.
19820        synchronized (mPackages) {
19821            Log.i(TAG, "Updating external media status from "
19822                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19823                    + (mediaStatus ? "mounted" : "unmounted"));
19824            if (DEBUG_SD_INSTALL)
19825                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19826                        + ", mMediaMounted=" + mMediaMounted);
19827            if (mediaStatus == mMediaMounted) {
19828                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19829                        : 0, -1);
19830                mHandler.sendMessage(msg);
19831                return;
19832            }
19833            mMediaMounted = mediaStatus;
19834        }
19835        // Queue up an async operation since the package installation may take a
19836        // little while.
19837        mHandler.post(new Runnable() {
19838            public void run() {
19839                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19840            }
19841        });
19842    }
19843
19844    /**
19845     * Called by StorageManagerService when the initial ASECs to scan are available.
19846     * Should block until all the ASEC containers are finished being scanned.
19847     */
19848    public void scanAvailableAsecs() {
19849        updateExternalMediaStatusInner(true, false, false);
19850    }
19851
19852    /*
19853     * Collect information of applications on external media, map them against
19854     * existing containers and update information based on current mount status.
19855     * Please note that we always have to report status if reportStatus has been
19856     * set to true especially when unloading packages.
19857     */
19858    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19859            boolean externalStorage) {
19860        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19861        int[] uidArr = EmptyArray.INT;
19862
19863        final String[] list = PackageHelper.getSecureContainerList();
19864        if (ArrayUtils.isEmpty(list)) {
19865            Log.i(TAG, "No secure containers found");
19866        } else {
19867            // Process list of secure containers and categorize them
19868            // as active or stale based on their package internal state.
19869
19870            // reader
19871            synchronized (mPackages) {
19872                for (String cid : list) {
19873                    // Leave stages untouched for now; installer service owns them
19874                    if (PackageInstallerService.isStageName(cid)) continue;
19875
19876                    if (DEBUG_SD_INSTALL)
19877                        Log.i(TAG, "Processing container " + cid);
19878                    String pkgName = getAsecPackageName(cid);
19879                    if (pkgName == null) {
19880                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19881                        continue;
19882                    }
19883                    if (DEBUG_SD_INSTALL)
19884                        Log.i(TAG, "Looking for pkg : " + pkgName);
19885
19886                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19887                    if (ps == null) {
19888                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19889                        continue;
19890                    }
19891
19892                    /*
19893                     * Skip packages that are not external if we're unmounting
19894                     * external storage.
19895                     */
19896                    if (externalStorage && !isMounted && !isExternal(ps)) {
19897                        continue;
19898                    }
19899
19900                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19901                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19902                    // The package status is changed only if the code path
19903                    // matches between settings and the container id.
19904                    if (ps.codePathString != null
19905                            && ps.codePathString.startsWith(args.getCodePath())) {
19906                        if (DEBUG_SD_INSTALL) {
19907                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19908                                    + " at code path: " + ps.codePathString);
19909                        }
19910
19911                        // We do have a valid package installed on sdcard
19912                        processCids.put(args, ps.codePathString);
19913                        final int uid = ps.appId;
19914                        if (uid != -1) {
19915                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19916                        }
19917                    } else {
19918                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19919                                + ps.codePathString);
19920                    }
19921                }
19922            }
19923
19924            Arrays.sort(uidArr);
19925        }
19926
19927        // Process packages with valid entries.
19928        if (isMounted) {
19929            if (DEBUG_SD_INSTALL)
19930                Log.i(TAG, "Loading packages");
19931            loadMediaPackages(processCids, uidArr, externalStorage);
19932            startCleaningPackages();
19933            mInstallerService.onSecureContainersAvailable();
19934        } else {
19935            if (DEBUG_SD_INSTALL)
19936                Log.i(TAG, "Unloading packages");
19937            unloadMediaPackages(processCids, uidArr, reportStatus);
19938        }
19939    }
19940
19941    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19942            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19943        final int size = infos.size();
19944        final String[] packageNames = new String[size];
19945        final int[] packageUids = new int[size];
19946        for (int i = 0; i < size; i++) {
19947            final ApplicationInfo info = infos.get(i);
19948            packageNames[i] = info.packageName;
19949            packageUids[i] = info.uid;
19950        }
19951        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19952                finishedReceiver);
19953    }
19954
19955    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19956            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19957        sendResourcesChangedBroadcast(mediaStatus, replacing,
19958                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19959    }
19960
19961    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19962            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19963        int size = pkgList.length;
19964        if (size > 0) {
19965            // Send broadcasts here
19966            Bundle extras = new Bundle();
19967            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19968            if (uidArr != null) {
19969                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19970            }
19971            if (replacing) {
19972                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19973            }
19974            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19975                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19976            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19977        }
19978    }
19979
19980   /*
19981     * Look at potentially valid container ids from processCids If package
19982     * information doesn't match the one on record or package scanning fails,
19983     * the cid is added to list of removeCids. We currently don't delete stale
19984     * containers.
19985     */
19986    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19987            boolean externalStorage) {
19988        ArrayList<String> pkgList = new ArrayList<String>();
19989        Set<AsecInstallArgs> keys = processCids.keySet();
19990
19991        for (AsecInstallArgs args : keys) {
19992            String codePath = processCids.get(args);
19993            if (DEBUG_SD_INSTALL)
19994                Log.i(TAG, "Loading container : " + args.cid);
19995            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19996            try {
19997                // Make sure there are no container errors first.
19998                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19999                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20000                            + " when installing from sdcard");
20001                    continue;
20002                }
20003                // Check code path here.
20004                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20005                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20006                            + " does not match one in settings " + codePath);
20007                    continue;
20008                }
20009                // Parse package
20010                int parseFlags = mDefParseFlags;
20011                if (args.isExternalAsec()) {
20012                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20013                }
20014                if (args.isFwdLocked()) {
20015                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20016                }
20017
20018                synchronized (mInstallLock) {
20019                    PackageParser.Package pkg = null;
20020                    try {
20021                        // Sadly we don't know the package name yet to freeze it
20022                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20023                                SCAN_IGNORE_FROZEN, 0, null);
20024                    } catch (PackageManagerException e) {
20025                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20026                    }
20027                    // Scan the package
20028                    if (pkg != null) {
20029                        /*
20030                         * TODO why is the lock being held? doPostInstall is
20031                         * called in other places without the lock. This needs
20032                         * to be straightened out.
20033                         */
20034                        // writer
20035                        synchronized (mPackages) {
20036                            retCode = PackageManager.INSTALL_SUCCEEDED;
20037                            pkgList.add(pkg.packageName);
20038                            // Post process args
20039                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20040                                    pkg.applicationInfo.uid);
20041                        }
20042                    } else {
20043                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20044                    }
20045                }
20046
20047            } finally {
20048                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20049                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20050                }
20051            }
20052        }
20053        // writer
20054        synchronized (mPackages) {
20055            // If the platform SDK has changed since the last time we booted,
20056            // we need to re-grant app permission to catch any new ones that
20057            // appear. This is really a hack, and means that apps can in some
20058            // cases get permissions that the user didn't initially explicitly
20059            // allow... it would be nice to have some better way to handle
20060            // this situation.
20061            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20062                    : mSettings.getInternalVersion();
20063            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20064                    : StorageManager.UUID_PRIVATE_INTERNAL;
20065
20066            int updateFlags = UPDATE_PERMISSIONS_ALL;
20067            if (ver.sdkVersion != mSdkVersion) {
20068                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20069                        + mSdkVersion + "; regranting permissions for external");
20070                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20071            }
20072            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20073
20074            // Yay, everything is now upgraded
20075            ver.forceCurrent();
20076
20077            // can downgrade to reader
20078            // Persist settings
20079            mSettings.writeLPr();
20080        }
20081        // Send a broadcast to let everyone know we are done processing
20082        if (pkgList.size() > 0) {
20083            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20084        }
20085    }
20086
20087   /*
20088     * Utility method to unload a list of specified containers
20089     */
20090    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
20091        // Just unmount all valid containers.
20092        for (AsecInstallArgs arg : cidArgs) {
20093            synchronized (mInstallLock) {
20094                arg.doPostDeleteLI(false);
20095           }
20096       }
20097   }
20098
20099    /*
20100     * Unload packages mounted on external media. This involves deleting package
20101     * data from internal structures, sending broadcasts about disabled packages,
20102     * gc'ing to free up references, unmounting all secure containers
20103     * corresponding to packages on external media, and posting a
20104     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
20105     * that we always have to post this message if status has been requested no
20106     * matter what.
20107     */
20108    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
20109            final boolean reportStatus) {
20110        if (DEBUG_SD_INSTALL)
20111            Log.i(TAG, "unloading media packages");
20112        ArrayList<String> pkgList = new ArrayList<String>();
20113        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
20114        final Set<AsecInstallArgs> keys = processCids.keySet();
20115        for (AsecInstallArgs args : keys) {
20116            String pkgName = args.getPackageName();
20117            if (DEBUG_SD_INSTALL)
20118                Log.i(TAG, "Trying to unload pkg : " + pkgName);
20119            // Delete package internally
20120            PackageRemovedInfo outInfo = new PackageRemovedInfo();
20121            synchronized (mInstallLock) {
20122                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20123                final boolean res;
20124                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
20125                        "unloadMediaPackages")) {
20126                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
20127                            null);
20128                }
20129                if (res) {
20130                    pkgList.add(pkgName);
20131                } else {
20132                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
20133                    failedList.add(args);
20134                }
20135            }
20136        }
20137
20138        // reader
20139        synchronized (mPackages) {
20140            // We didn't update the settings after removing each package;
20141            // write them now for all packages.
20142            mSettings.writeLPr();
20143        }
20144
20145        // We have to absolutely send UPDATED_MEDIA_STATUS only
20146        // after confirming that all the receivers processed the ordered
20147        // broadcast when packages get disabled, force a gc to clean things up.
20148        // and unload all the containers.
20149        if (pkgList.size() > 0) {
20150            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
20151                    new IIntentReceiver.Stub() {
20152                public void performReceive(Intent intent, int resultCode, String data,
20153                        Bundle extras, boolean ordered, boolean sticky,
20154                        int sendingUser) throws RemoteException {
20155                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
20156                            reportStatus ? 1 : 0, 1, keys);
20157                    mHandler.sendMessage(msg);
20158                }
20159            });
20160        } else {
20161            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
20162                    keys);
20163            mHandler.sendMessage(msg);
20164        }
20165    }
20166
20167    private void loadPrivatePackages(final VolumeInfo vol) {
20168        mHandler.post(new Runnable() {
20169            @Override
20170            public void run() {
20171                loadPrivatePackagesInner(vol);
20172            }
20173        });
20174    }
20175
20176    private void loadPrivatePackagesInner(VolumeInfo vol) {
20177        final String volumeUuid = vol.fsUuid;
20178        if (TextUtils.isEmpty(volumeUuid)) {
20179            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20180            return;
20181        }
20182
20183        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20184        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20185        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20186
20187        final VersionInfo ver;
20188        final List<PackageSetting> packages;
20189        synchronized (mPackages) {
20190            ver = mSettings.findOrCreateVersion(volumeUuid);
20191            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20192        }
20193
20194        for (PackageSetting ps : packages) {
20195            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20196            synchronized (mInstallLock) {
20197                final PackageParser.Package pkg;
20198                try {
20199                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20200                    loaded.add(pkg.applicationInfo);
20201
20202                } catch (PackageManagerException e) {
20203                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20204                }
20205
20206                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20207                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20208                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20209                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20210                }
20211            }
20212        }
20213
20214        // Reconcile app data for all started/unlocked users
20215        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20216        final UserManager um = mContext.getSystemService(UserManager.class);
20217        UserManagerInternal umInternal = getUserManagerInternal();
20218        for (UserInfo user : um.getUsers()) {
20219            final int flags;
20220            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20221                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20222            } else if (umInternal.isUserRunning(user.id)) {
20223                flags = StorageManager.FLAG_STORAGE_DE;
20224            } else {
20225                continue;
20226            }
20227
20228            try {
20229                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20230                synchronized (mInstallLock) {
20231                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20232                }
20233            } catch (IllegalStateException e) {
20234                // Device was probably ejected, and we'll process that event momentarily
20235                Slog.w(TAG, "Failed to prepare storage: " + e);
20236            }
20237        }
20238
20239        synchronized (mPackages) {
20240            int updateFlags = UPDATE_PERMISSIONS_ALL;
20241            if (ver.sdkVersion != mSdkVersion) {
20242                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20243                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20244                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20245            }
20246            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20247
20248            // Yay, everything is now upgraded
20249            ver.forceCurrent();
20250
20251            mSettings.writeLPr();
20252        }
20253
20254        for (PackageFreezer freezer : freezers) {
20255            freezer.close();
20256        }
20257
20258        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20259        sendResourcesChangedBroadcast(true, false, loaded, null);
20260    }
20261
20262    private void unloadPrivatePackages(final VolumeInfo vol) {
20263        mHandler.post(new Runnable() {
20264            @Override
20265            public void run() {
20266                unloadPrivatePackagesInner(vol);
20267            }
20268        });
20269    }
20270
20271    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20272        final String volumeUuid = vol.fsUuid;
20273        if (TextUtils.isEmpty(volumeUuid)) {
20274            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20275            return;
20276        }
20277
20278        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20279        synchronized (mInstallLock) {
20280        synchronized (mPackages) {
20281            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20282            for (PackageSetting ps : packages) {
20283                if (ps.pkg == null) continue;
20284
20285                final ApplicationInfo info = ps.pkg.applicationInfo;
20286                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20287                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20288
20289                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20290                        "unloadPrivatePackagesInner")) {
20291                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20292                            false, null)) {
20293                        unloaded.add(info);
20294                    } else {
20295                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20296                    }
20297                }
20298
20299                // Try very hard to release any references to this package
20300                // so we don't risk the system server being killed due to
20301                // open FDs
20302                AttributeCache.instance().removePackage(ps.name);
20303            }
20304
20305            mSettings.writeLPr();
20306        }
20307        }
20308
20309        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20310        sendResourcesChangedBroadcast(false, false, unloaded, null);
20311
20312        // Try very hard to release any references to this path so we don't risk
20313        // the system server being killed due to open FDs
20314        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20315
20316        for (int i = 0; i < 3; i++) {
20317            System.gc();
20318            System.runFinalization();
20319        }
20320    }
20321
20322    /**
20323     * Prepare storage areas for given user on all mounted devices.
20324     */
20325    void prepareUserData(int userId, int userSerial, int flags) {
20326        synchronized (mInstallLock) {
20327            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20328            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20329                final String volumeUuid = vol.getFsUuid();
20330                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20331            }
20332        }
20333    }
20334
20335    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20336            boolean allowRecover) {
20337        // Prepare storage and verify that serial numbers are consistent; if
20338        // there's a mismatch we need to destroy to avoid leaking data
20339        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20340        try {
20341            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20342
20343            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20344                UserManagerService.enforceSerialNumber(
20345                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20346                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20347                    UserManagerService.enforceSerialNumber(
20348                            Environment.getDataSystemDeDirectory(userId), userSerial);
20349                }
20350            }
20351            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20352                UserManagerService.enforceSerialNumber(
20353                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20354                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20355                    UserManagerService.enforceSerialNumber(
20356                            Environment.getDataSystemCeDirectory(userId), userSerial);
20357                }
20358            }
20359
20360            synchronized (mInstallLock) {
20361                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20362            }
20363        } catch (Exception e) {
20364            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20365                    + " because we failed to prepare: " + e);
20366            destroyUserDataLI(volumeUuid, userId,
20367                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20368
20369            if (allowRecover) {
20370                // Try one last time; if we fail again we're really in trouble
20371                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20372            }
20373        }
20374    }
20375
20376    /**
20377     * Destroy storage areas for given user on all mounted devices.
20378     */
20379    void destroyUserData(int userId, int flags) {
20380        synchronized (mInstallLock) {
20381            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20382            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20383                final String volumeUuid = vol.getFsUuid();
20384                destroyUserDataLI(volumeUuid, userId, flags);
20385            }
20386        }
20387    }
20388
20389    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20390        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20391        try {
20392            // Clean up app data, profile data, and media data
20393            mInstaller.destroyUserData(volumeUuid, userId, flags);
20394
20395            // Clean up system data
20396            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20397                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20398                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20399                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20400                }
20401                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20402                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20403                }
20404            }
20405
20406            // Data with special labels is now gone, so finish the job
20407            storage.destroyUserStorage(volumeUuid, userId, flags);
20408
20409        } catch (Exception e) {
20410            logCriticalInfo(Log.WARN,
20411                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20412        }
20413    }
20414
20415    /**
20416     * Examine all users present on given mounted volume, and destroy data
20417     * belonging to users that are no longer valid, or whose user ID has been
20418     * recycled.
20419     */
20420    private void reconcileUsers(String volumeUuid) {
20421        final List<File> files = new ArrayList<>();
20422        Collections.addAll(files, FileUtils
20423                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20424        Collections.addAll(files, FileUtils
20425                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20426        Collections.addAll(files, FileUtils
20427                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20428        Collections.addAll(files, FileUtils
20429                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20430        for (File file : files) {
20431            if (!file.isDirectory()) continue;
20432
20433            final int userId;
20434            final UserInfo info;
20435            try {
20436                userId = Integer.parseInt(file.getName());
20437                info = sUserManager.getUserInfo(userId);
20438            } catch (NumberFormatException e) {
20439                Slog.w(TAG, "Invalid user directory " + file);
20440                continue;
20441            }
20442
20443            boolean destroyUser = false;
20444            if (info == null) {
20445                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20446                        + " because no matching user was found");
20447                destroyUser = true;
20448            } else if (!mOnlyCore) {
20449                try {
20450                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20451                } catch (IOException e) {
20452                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20453                            + " because we failed to enforce serial number: " + e);
20454                    destroyUser = true;
20455                }
20456            }
20457
20458            if (destroyUser) {
20459                synchronized (mInstallLock) {
20460                    destroyUserDataLI(volumeUuid, userId,
20461                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20462                }
20463            }
20464        }
20465    }
20466
20467    private void assertPackageKnown(String volumeUuid, String packageName)
20468            throws PackageManagerException {
20469        synchronized (mPackages) {
20470            // Normalize package name to handle renamed packages
20471            packageName = normalizePackageNameLPr(packageName);
20472
20473            final PackageSetting ps = mSettings.mPackages.get(packageName);
20474            if (ps == null) {
20475                throw new PackageManagerException("Package " + packageName + " is unknown");
20476            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20477                throw new PackageManagerException(
20478                        "Package " + packageName + " found on unknown volume " + volumeUuid
20479                                + "; expected volume " + ps.volumeUuid);
20480            }
20481        }
20482    }
20483
20484    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20485            throws PackageManagerException {
20486        synchronized (mPackages) {
20487            // Normalize package name to handle renamed packages
20488            packageName = normalizePackageNameLPr(packageName);
20489
20490            final PackageSetting ps = mSettings.mPackages.get(packageName);
20491            if (ps == null) {
20492                throw new PackageManagerException("Package " + packageName + " is unknown");
20493            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20494                throw new PackageManagerException(
20495                        "Package " + packageName + " found on unknown volume " + volumeUuid
20496                                + "; expected volume " + ps.volumeUuid);
20497            } else if (!ps.getInstalled(userId)) {
20498                throw new PackageManagerException(
20499                        "Package " + packageName + " not installed for user " + userId);
20500            }
20501        }
20502    }
20503
20504    /**
20505     * Examine all apps present on given mounted volume, and destroy apps that
20506     * aren't expected, either due to uninstallation or reinstallation on
20507     * another volume.
20508     */
20509    private void reconcileApps(String volumeUuid) {
20510        final File[] files = FileUtils
20511                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20512        for (File file : files) {
20513            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20514                    && !PackageInstallerService.isStageName(file.getName());
20515            if (!isPackage) {
20516                // Ignore entries which are not packages
20517                continue;
20518            }
20519
20520            try {
20521                final PackageLite pkg = PackageParser.parsePackageLite(file,
20522                        PackageParser.PARSE_MUST_BE_APK);
20523                assertPackageKnown(volumeUuid, pkg.packageName);
20524
20525            } catch (PackageParserException | PackageManagerException e) {
20526                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20527                synchronized (mInstallLock) {
20528                    removeCodePathLI(file);
20529                }
20530            }
20531        }
20532    }
20533
20534    /**
20535     * Reconcile all app data for the given user.
20536     * <p>
20537     * Verifies that directories exist and that ownership and labeling is
20538     * correct for all installed apps on all mounted volumes.
20539     */
20540    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20541        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20542        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20543            final String volumeUuid = vol.getFsUuid();
20544            synchronized (mInstallLock) {
20545                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20546            }
20547        }
20548    }
20549
20550    /**
20551     * Reconcile all app data on given mounted volume.
20552     * <p>
20553     * Destroys app data that isn't expected, either due to uninstallation or
20554     * reinstallation on another volume.
20555     * <p>
20556     * Verifies that directories exist and that ownership and labeling is
20557     * correct for all installed apps.
20558     */
20559    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20560            boolean migrateAppData) {
20561        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20562                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20563
20564        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20565        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20566
20567        // First look for stale data that doesn't belong, and check if things
20568        // have changed since we did our last restorecon
20569        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20570            if (StorageManager.isFileEncryptedNativeOrEmulated()
20571                    && !StorageManager.isUserKeyUnlocked(userId)) {
20572                throw new RuntimeException(
20573                        "Yikes, someone asked us to reconcile CE storage while " + userId
20574                                + " was still locked; this would have caused massive data loss!");
20575            }
20576
20577            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20578            for (File file : files) {
20579                final String packageName = file.getName();
20580                try {
20581                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20582                } catch (PackageManagerException e) {
20583                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20584                    try {
20585                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20586                                StorageManager.FLAG_STORAGE_CE, 0);
20587                    } catch (InstallerException e2) {
20588                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20589                    }
20590                }
20591            }
20592        }
20593        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20594            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20595            for (File file : files) {
20596                final String packageName = file.getName();
20597                try {
20598                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20599                } catch (PackageManagerException e) {
20600                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20601                    try {
20602                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20603                                StorageManager.FLAG_STORAGE_DE, 0);
20604                    } catch (InstallerException e2) {
20605                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20606                    }
20607                }
20608            }
20609        }
20610
20611        // Ensure that data directories are ready to roll for all packages
20612        // installed for this volume and user
20613        final List<PackageSetting> packages;
20614        synchronized (mPackages) {
20615            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20616        }
20617        int preparedCount = 0;
20618        for (PackageSetting ps : packages) {
20619            final String packageName = ps.name;
20620            if (ps.pkg == null) {
20621                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20622                // TODO: might be due to legacy ASEC apps; we should circle back
20623                // and reconcile again once they're scanned
20624                continue;
20625            }
20626
20627            if (ps.getInstalled(userId)) {
20628                prepareAppDataLIF(ps.pkg, userId, flags);
20629
20630                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20631                    // We may have just shuffled around app data directories, so
20632                    // prepare them one more time
20633                    prepareAppDataLIF(ps.pkg, userId, flags);
20634                }
20635
20636                preparedCount++;
20637            }
20638        }
20639
20640        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20641    }
20642
20643    /**
20644     * Prepare app data for the given app just after it was installed or
20645     * upgraded. This method carefully only touches users that it's installed
20646     * for, and it forces a restorecon to handle any seinfo changes.
20647     * <p>
20648     * Verifies that directories exist and that ownership and labeling is
20649     * correct for all installed apps. If there is an ownership mismatch, it
20650     * will try recovering system apps by wiping data; third-party app data is
20651     * left intact.
20652     * <p>
20653     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20654     */
20655    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20656        final PackageSetting ps;
20657        synchronized (mPackages) {
20658            ps = mSettings.mPackages.get(pkg.packageName);
20659            mSettings.writeKernelMappingLPr(ps);
20660        }
20661
20662        final UserManager um = mContext.getSystemService(UserManager.class);
20663        UserManagerInternal umInternal = getUserManagerInternal();
20664        for (UserInfo user : um.getUsers()) {
20665            final int flags;
20666            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20667                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20668            } else if (umInternal.isUserRunning(user.id)) {
20669                flags = StorageManager.FLAG_STORAGE_DE;
20670            } else {
20671                continue;
20672            }
20673
20674            if (ps.getInstalled(user.id)) {
20675                // TODO: when user data is locked, mark that we're still dirty
20676                prepareAppDataLIF(pkg, user.id, flags);
20677            }
20678        }
20679    }
20680
20681    /**
20682     * Prepare app data for the given app.
20683     * <p>
20684     * Verifies that directories exist and that ownership and labeling is
20685     * correct for all installed apps. If there is an ownership mismatch, this
20686     * will try recovering system apps by wiping data; third-party app data is
20687     * left intact.
20688     */
20689    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20690        if (pkg == null) {
20691            Slog.wtf(TAG, "Package was null!", new Throwable());
20692            return;
20693        }
20694        prepareAppDataLeafLIF(pkg, userId, flags);
20695        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20696        for (int i = 0; i < childCount; i++) {
20697            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20698        }
20699    }
20700
20701    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20702        if (DEBUG_APP_DATA) {
20703            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20704                    + Integer.toHexString(flags));
20705        }
20706
20707        final String volumeUuid = pkg.volumeUuid;
20708        final String packageName = pkg.packageName;
20709        final ApplicationInfo app = pkg.applicationInfo;
20710        final int appId = UserHandle.getAppId(app.uid);
20711
20712        Preconditions.checkNotNull(app.seinfo);
20713
20714        long ceDataInode = -1;
20715        try {
20716            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20717                    appId, app.seinfo, app.targetSdkVersion);
20718        } catch (InstallerException e) {
20719            if (app.isSystemApp()) {
20720                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20721                        + ", but trying to recover: " + e);
20722                destroyAppDataLeafLIF(pkg, userId, flags);
20723                try {
20724                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20725                            appId, app.seinfo, app.targetSdkVersion);
20726                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20727                } catch (InstallerException e2) {
20728                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20729                }
20730            } else {
20731                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20732            }
20733        }
20734
20735        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20736            // TODO: mark this structure as dirty so we persist it!
20737            synchronized (mPackages) {
20738                final PackageSetting ps = mSettings.mPackages.get(packageName);
20739                if (ps != null) {
20740                    ps.setCeDataInode(ceDataInode, userId);
20741                }
20742            }
20743        }
20744
20745        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20746    }
20747
20748    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20749        if (pkg == null) {
20750            Slog.wtf(TAG, "Package was null!", new Throwable());
20751            return;
20752        }
20753        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20754        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20755        for (int i = 0; i < childCount; i++) {
20756            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20757        }
20758    }
20759
20760    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20761        final String volumeUuid = pkg.volumeUuid;
20762        final String packageName = pkg.packageName;
20763        final ApplicationInfo app = pkg.applicationInfo;
20764
20765        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20766            // Create a native library symlink only if we have native libraries
20767            // and if the native libraries are 32 bit libraries. We do not provide
20768            // this symlink for 64 bit libraries.
20769            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20770                final String nativeLibPath = app.nativeLibraryDir;
20771                try {
20772                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20773                            nativeLibPath, userId);
20774                } catch (InstallerException e) {
20775                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20776                }
20777            }
20778        }
20779    }
20780
20781    /**
20782     * For system apps on non-FBE devices, this method migrates any existing
20783     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20784     * requested by the app.
20785     */
20786    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20787        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20788                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20789            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20790                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20791            try {
20792                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20793                        storageTarget);
20794            } catch (InstallerException e) {
20795                logCriticalInfo(Log.WARN,
20796                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20797            }
20798            return true;
20799        } else {
20800            return false;
20801        }
20802    }
20803
20804    public PackageFreezer freezePackage(String packageName, String killReason) {
20805        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20806    }
20807
20808    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20809        return new PackageFreezer(packageName, userId, killReason);
20810    }
20811
20812    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20813            String killReason) {
20814        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20815    }
20816
20817    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20818            String killReason) {
20819        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20820            return new PackageFreezer();
20821        } else {
20822            return freezePackage(packageName, userId, killReason);
20823        }
20824    }
20825
20826    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20827            String killReason) {
20828        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20829    }
20830
20831    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20832            String killReason) {
20833        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20834            return new PackageFreezer();
20835        } else {
20836            return freezePackage(packageName, userId, killReason);
20837        }
20838    }
20839
20840    /**
20841     * Class that freezes and kills the given package upon creation, and
20842     * unfreezes it upon closing. This is typically used when doing surgery on
20843     * app code/data to prevent the app from running while you're working.
20844     */
20845    private class PackageFreezer implements AutoCloseable {
20846        private final String mPackageName;
20847        private final PackageFreezer[] mChildren;
20848
20849        private final boolean mWeFroze;
20850
20851        private final AtomicBoolean mClosed = new AtomicBoolean();
20852        private final CloseGuard mCloseGuard = CloseGuard.get();
20853
20854        /**
20855         * Create and return a stub freezer that doesn't actually do anything,
20856         * typically used when someone requested
20857         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20858         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20859         */
20860        public PackageFreezer() {
20861            mPackageName = null;
20862            mChildren = null;
20863            mWeFroze = false;
20864            mCloseGuard.open("close");
20865        }
20866
20867        public PackageFreezer(String packageName, int userId, String killReason) {
20868            synchronized (mPackages) {
20869                mPackageName = packageName;
20870                mWeFroze = mFrozenPackages.add(mPackageName);
20871
20872                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20873                if (ps != null) {
20874                    killApplication(ps.name, ps.appId, userId, killReason);
20875                }
20876
20877                final PackageParser.Package p = mPackages.get(packageName);
20878                if (p != null && p.childPackages != null) {
20879                    final int N = p.childPackages.size();
20880                    mChildren = new PackageFreezer[N];
20881                    for (int i = 0; i < N; i++) {
20882                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20883                                userId, killReason);
20884                    }
20885                } else {
20886                    mChildren = null;
20887                }
20888            }
20889            mCloseGuard.open("close");
20890        }
20891
20892        @Override
20893        protected void finalize() throws Throwable {
20894            try {
20895                mCloseGuard.warnIfOpen();
20896                close();
20897            } finally {
20898                super.finalize();
20899            }
20900        }
20901
20902        @Override
20903        public void close() {
20904            mCloseGuard.close();
20905            if (mClosed.compareAndSet(false, true)) {
20906                synchronized (mPackages) {
20907                    if (mWeFroze) {
20908                        mFrozenPackages.remove(mPackageName);
20909                    }
20910
20911                    if (mChildren != null) {
20912                        for (PackageFreezer freezer : mChildren) {
20913                            freezer.close();
20914                        }
20915                    }
20916                }
20917            }
20918        }
20919    }
20920
20921    /**
20922     * Verify that given package is currently frozen.
20923     */
20924    private void checkPackageFrozen(String packageName) {
20925        synchronized (mPackages) {
20926            if (!mFrozenPackages.contains(packageName)) {
20927                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20928            }
20929        }
20930    }
20931
20932    @Override
20933    public int movePackage(final String packageName, final String volumeUuid) {
20934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20935
20936        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20937        final int moveId = mNextMoveId.getAndIncrement();
20938        mHandler.post(new Runnable() {
20939            @Override
20940            public void run() {
20941                try {
20942                    movePackageInternal(packageName, volumeUuid, moveId, user);
20943                } catch (PackageManagerException e) {
20944                    Slog.w(TAG, "Failed to move " + packageName, e);
20945                    mMoveCallbacks.notifyStatusChanged(moveId,
20946                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20947                }
20948            }
20949        });
20950        return moveId;
20951    }
20952
20953    private void movePackageInternal(final String packageName, final String volumeUuid,
20954            final int moveId, UserHandle user) throws PackageManagerException {
20955        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20956        final PackageManager pm = mContext.getPackageManager();
20957
20958        final boolean currentAsec;
20959        final String currentVolumeUuid;
20960        final File codeFile;
20961        final String installerPackageName;
20962        final String packageAbiOverride;
20963        final int appId;
20964        final String seinfo;
20965        final String label;
20966        final int targetSdkVersion;
20967        final PackageFreezer freezer;
20968        final int[] installedUserIds;
20969
20970        // reader
20971        synchronized (mPackages) {
20972            final PackageParser.Package pkg = mPackages.get(packageName);
20973            final PackageSetting ps = mSettings.mPackages.get(packageName);
20974            if (pkg == null || ps == null) {
20975                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20976            }
20977
20978            if (pkg.applicationInfo.isSystemApp()) {
20979                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20980                        "Cannot move system application");
20981            }
20982
20983            if (pkg.applicationInfo.isExternalAsec()) {
20984                currentAsec = true;
20985                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20986            } else if (pkg.applicationInfo.isForwardLocked()) {
20987                currentAsec = true;
20988                currentVolumeUuid = "forward_locked";
20989            } else {
20990                currentAsec = false;
20991                currentVolumeUuid = ps.volumeUuid;
20992
20993                final File probe = new File(pkg.codePath);
20994                final File probeOat = new File(probe, "oat");
20995                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20996                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20997                            "Move only supported for modern cluster style installs");
20998                }
20999            }
21000
21001            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21002                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21003                        "Package already moved to " + volumeUuid);
21004            }
21005            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21006                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21007                        "Device admin cannot be moved");
21008            }
21009
21010            if (mFrozenPackages.contains(packageName)) {
21011                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21012                        "Failed to move already frozen package");
21013            }
21014
21015            codeFile = new File(pkg.codePath);
21016            installerPackageName = ps.installerPackageName;
21017            packageAbiOverride = ps.cpuAbiOverrideString;
21018            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21019            seinfo = pkg.applicationInfo.seinfo;
21020            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21021            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21022            freezer = freezePackage(packageName, "movePackageInternal");
21023            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21024        }
21025
21026        final Bundle extras = new Bundle();
21027        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21028        extras.putString(Intent.EXTRA_TITLE, label);
21029        mMoveCallbacks.notifyCreated(moveId, extras);
21030
21031        int installFlags;
21032        final boolean moveCompleteApp;
21033        final File measurePath;
21034
21035        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21036            installFlags = INSTALL_INTERNAL;
21037            moveCompleteApp = !currentAsec;
21038            measurePath = Environment.getDataAppDirectory(volumeUuid);
21039        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21040            installFlags = INSTALL_EXTERNAL;
21041            moveCompleteApp = false;
21042            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21043        } else {
21044            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21045            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21046                    || !volume.isMountedWritable()) {
21047                freezer.close();
21048                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21049                        "Move location not mounted private volume");
21050            }
21051
21052            Preconditions.checkState(!currentAsec);
21053
21054            installFlags = INSTALL_INTERNAL;
21055            moveCompleteApp = true;
21056            measurePath = Environment.getDataAppDirectory(volumeUuid);
21057        }
21058
21059        final PackageStats stats = new PackageStats(null, -1);
21060        synchronized (mInstaller) {
21061            for (int userId : installedUserIds) {
21062                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21063                    freezer.close();
21064                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21065                            "Failed to measure package size");
21066                }
21067            }
21068        }
21069
21070        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21071                + stats.dataSize);
21072
21073        final long startFreeBytes = measurePath.getFreeSpace();
21074        final long sizeBytes;
21075        if (moveCompleteApp) {
21076            sizeBytes = stats.codeSize + stats.dataSize;
21077        } else {
21078            sizeBytes = stats.codeSize;
21079        }
21080
21081        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21082            freezer.close();
21083            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21084                    "Not enough free space to move");
21085        }
21086
21087        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21088
21089        final CountDownLatch installedLatch = new CountDownLatch(1);
21090        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21091            @Override
21092            public void onUserActionRequired(Intent intent) throws RemoteException {
21093                throw new IllegalStateException();
21094            }
21095
21096            @Override
21097            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21098                    Bundle extras) throws RemoteException {
21099                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21100                        + PackageManager.installStatusToString(returnCode, msg));
21101
21102                installedLatch.countDown();
21103                freezer.close();
21104
21105                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21106                switch (status) {
21107                    case PackageInstaller.STATUS_SUCCESS:
21108                        mMoveCallbacks.notifyStatusChanged(moveId,
21109                                PackageManager.MOVE_SUCCEEDED);
21110                        break;
21111                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21112                        mMoveCallbacks.notifyStatusChanged(moveId,
21113                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21114                        break;
21115                    default:
21116                        mMoveCallbacks.notifyStatusChanged(moveId,
21117                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21118                        break;
21119                }
21120            }
21121        };
21122
21123        final MoveInfo move;
21124        if (moveCompleteApp) {
21125            // Kick off a thread to report progress estimates
21126            new Thread() {
21127                @Override
21128                public void run() {
21129                    while (true) {
21130                        try {
21131                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21132                                break;
21133                            }
21134                        } catch (InterruptedException ignored) {
21135                        }
21136
21137                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
21138                        final int progress = 10 + (int) MathUtils.constrain(
21139                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21140                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21141                    }
21142                }
21143            }.start();
21144
21145            final String dataAppName = codeFile.getName();
21146            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21147                    dataAppName, appId, seinfo, targetSdkVersion);
21148        } else {
21149            move = null;
21150        }
21151
21152        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21153
21154        final Message msg = mHandler.obtainMessage(INIT_COPY);
21155        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21156        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21157                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21158                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21159                PackageManager.INSTALL_REASON_UNKNOWN);
21160        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21161        msg.obj = params;
21162
21163        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21164                System.identityHashCode(msg.obj));
21165        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21166                System.identityHashCode(msg.obj));
21167
21168        mHandler.sendMessage(msg);
21169    }
21170
21171    @Override
21172    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21173        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21174
21175        final int realMoveId = mNextMoveId.getAndIncrement();
21176        final Bundle extras = new Bundle();
21177        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21178        mMoveCallbacks.notifyCreated(realMoveId, extras);
21179
21180        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21181            @Override
21182            public void onCreated(int moveId, Bundle extras) {
21183                // Ignored
21184            }
21185
21186            @Override
21187            public void onStatusChanged(int moveId, int status, long estMillis) {
21188                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21189            }
21190        };
21191
21192        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21193        storage.setPrimaryStorageUuid(volumeUuid, callback);
21194        return realMoveId;
21195    }
21196
21197    @Override
21198    public int getMoveStatus(int moveId) {
21199        mContext.enforceCallingOrSelfPermission(
21200                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21201        return mMoveCallbacks.mLastStatus.get(moveId);
21202    }
21203
21204    @Override
21205    public void registerMoveCallback(IPackageMoveObserver callback) {
21206        mContext.enforceCallingOrSelfPermission(
21207                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21208        mMoveCallbacks.register(callback);
21209    }
21210
21211    @Override
21212    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21213        mContext.enforceCallingOrSelfPermission(
21214                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21215        mMoveCallbacks.unregister(callback);
21216    }
21217
21218    @Override
21219    public boolean setInstallLocation(int loc) {
21220        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21221                null);
21222        if (getInstallLocation() == loc) {
21223            return true;
21224        }
21225        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21226                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21227            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21228                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21229            return true;
21230        }
21231        return false;
21232   }
21233
21234    @Override
21235    public int getInstallLocation() {
21236        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21237                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21238                PackageHelper.APP_INSTALL_AUTO);
21239    }
21240
21241    /** Called by UserManagerService */
21242    void cleanUpUser(UserManagerService userManager, int userHandle) {
21243        synchronized (mPackages) {
21244            mDirtyUsers.remove(userHandle);
21245            mUserNeedsBadging.delete(userHandle);
21246            mSettings.removeUserLPw(userHandle);
21247            mPendingBroadcasts.remove(userHandle);
21248            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21249            removeUnusedPackagesLPw(userManager, userHandle);
21250        }
21251    }
21252
21253    /**
21254     * We're removing userHandle and would like to remove any downloaded packages
21255     * that are no longer in use by any other user.
21256     * @param userHandle the user being removed
21257     */
21258    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21259        final boolean DEBUG_CLEAN_APKS = false;
21260        int [] users = userManager.getUserIds();
21261        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21262        while (psit.hasNext()) {
21263            PackageSetting ps = psit.next();
21264            if (ps.pkg == null) {
21265                continue;
21266            }
21267            final String packageName = ps.pkg.packageName;
21268            // Skip over if system app
21269            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21270                continue;
21271            }
21272            if (DEBUG_CLEAN_APKS) {
21273                Slog.i(TAG, "Checking package " + packageName);
21274            }
21275            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21276            if (keep) {
21277                if (DEBUG_CLEAN_APKS) {
21278                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21279                }
21280            } else {
21281                for (int i = 0; i < users.length; i++) {
21282                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21283                        keep = true;
21284                        if (DEBUG_CLEAN_APKS) {
21285                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21286                                    + users[i]);
21287                        }
21288                        break;
21289                    }
21290                }
21291            }
21292            if (!keep) {
21293                if (DEBUG_CLEAN_APKS) {
21294                    Slog.i(TAG, "  Removing package " + packageName);
21295                }
21296                mHandler.post(new Runnable() {
21297                    public void run() {
21298                        deletePackageX(packageName, userHandle, 0);
21299                    } //end run
21300                });
21301            }
21302        }
21303    }
21304
21305    /** Called by UserManagerService */
21306    void createNewUser(int userId, String[] disallowedPackages) {
21307        synchronized (mInstallLock) {
21308            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21309        }
21310        synchronized (mPackages) {
21311            scheduleWritePackageRestrictionsLocked(userId);
21312            scheduleWritePackageListLocked(userId);
21313            applyFactoryDefaultBrowserLPw(userId);
21314            primeDomainVerificationsLPw(userId);
21315        }
21316    }
21317
21318    void onNewUserCreated(final int userId) {
21319        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21320        // If permission review for legacy apps is required, we represent
21321        // dagerous permissions for such apps as always granted runtime
21322        // permissions to keep per user flag state whether review is needed.
21323        // Hence, if a new user is added we have to propagate dangerous
21324        // permission grants for these legacy apps.
21325        if (mPermissionReviewRequired) {
21326            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21327                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21328        }
21329    }
21330
21331    @Override
21332    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21333        mContext.enforceCallingOrSelfPermission(
21334                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21335                "Only package verification agents can read the verifier device identity");
21336
21337        synchronized (mPackages) {
21338            return mSettings.getVerifierDeviceIdentityLPw();
21339        }
21340    }
21341
21342    @Override
21343    public void setPermissionEnforced(String permission, boolean enforced) {
21344        // TODO: Now that we no longer change GID for storage, this should to away.
21345        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21346                "setPermissionEnforced");
21347        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21348            synchronized (mPackages) {
21349                if (mSettings.mReadExternalStorageEnforced == null
21350                        || mSettings.mReadExternalStorageEnforced != enforced) {
21351                    mSettings.mReadExternalStorageEnforced = enforced;
21352                    mSettings.writeLPr();
21353                }
21354            }
21355            // kill any non-foreground processes so we restart them and
21356            // grant/revoke the GID.
21357            final IActivityManager am = ActivityManager.getService();
21358            if (am != null) {
21359                final long token = Binder.clearCallingIdentity();
21360                try {
21361                    am.killProcessesBelowForeground("setPermissionEnforcement");
21362                } catch (RemoteException e) {
21363                } finally {
21364                    Binder.restoreCallingIdentity(token);
21365                }
21366            }
21367        } else {
21368            throw new IllegalArgumentException("No selective enforcement for " + permission);
21369        }
21370    }
21371
21372    @Override
21373    @Deprecated
21374    public boolean isPermissionEnforced(String permission) {
21375        return true;
21376    }
21377
21378    @Override
21379    public boolean isStorageLow() {
21380        final long token = Binder.clearCallingIdentity();
21381        try {
21382            final DeviceStorageMonitorInternal
21383                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21384            if (dsm != null) {
21385                return dsm.isMemoryLow();
21386            } else {
21387                return false;
21388            }
21389        } finally {
21390            Binder.restoreCallingIdentity(token);
21391        }
21392    }
21393
21394    @Override
21395    public IPackageInstaller getPackageInstaller() {
21396        return mInstallerService;
21397    }
21398
21399    private boolean userNeedsBadging(int userId) {
21400        int index = mUserNeedsBadging.indexOfKey(userId);
21401        if (index < 0) {
21402            final UserInfo userInfo;
21403            final long token = Binder.clearCallingIdentity();
21404            try {
21405                userInfo = sUserManager.getUserInfo(userId);
21406            } finally {
21407                Binder.restoreCallingIdentity(token);
21408            }
21409            final boolean b;
21410            if (userInfo != null && userInfo.isManagedProfile()) {
21411                b = true;
21412            } else {
21413                b = false;
21414            }
21415            mUserNeedsBadging.put(userId, b);
21416            return b;
21417        }
21418        return mUserNeedsBadging.valueAt(index);
21419    }
21420
21421    @Override
21422    public KeySet getKeySetByAlias(String packageName, String alias) {
21423        if (packageName == null || alias == null) {
21424            return null;
21425        }
21426        synchronized(mPackages) {
21427            final PackageParser.Package pkg = mPackages.get(packageName);
21428            if (pkg == null) {
21429                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21430                throw new IllegalArgumentException("Unknown package: " + packageName);
21431            }
21432            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21433            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21434        }
21435    }
21436
21437    @Override
21438    public KeySet getSigningKeySet(String packageName) {
21439        if (packageName == null) {
21440            return null;
21441        }
21442        synchronized(mPackages) {
21443            final PackageParser.Package pkg = mPackages.get(packageName);
21444            if (pkg == null) {
21445                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21446                throw new IllegalArgumentException("Unknown package: " + packageName);
21447            }
21448            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21449                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21450                throw new SecurityException("May not access signing KeySet of other apps.");
21451            }
21452            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21453            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21454        }
21455    }
21456
21457    @Override
21458    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21459        if (packageName == null || ks == null) {
21460            return false;
21461        }
21462        synchronized(mPackages) {
21463            final PackageParser.Package pkg = mPackages.get(packageName);
21464            if (pkg == null) {
21465                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21466                throw new IllegalArgumentException("Unknown package: " + packageName);
21467            }
21468            IBinder ksh = ks.getToken();
21469            if (ksh instanceof KeySetHandle) {
21470                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21471                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21472            }
21473            return false;
21474        }
21475    }
21476
21477    @Override
21478    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21479        if (packageName == null || ks == null) {
21480            return false;
21481        }
21482        synchronized(mPackages) {
21483            final PackageParser.Package pkg = mPackages.get(packageName);
21484            if (pkg == null) {
21485                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21486                throw new IllegalArgumentException("Unknown package: " + packageName);
21487            }
21488            IBinder ksh = ks.getToken();
21489            if (ksh instanceof KeySetHandle) {
21490                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21491                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21492            }
21493            return false;
21494        }
21495    }
21496
21497    private void deletePackageIfUnusedLPr(final String packageName) {
21498        PackageSetting ps = mSettings.mPackages.get(packageName);
21499        if (ps == null) {
21500            return;
21501        }
21502        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21503            // TODO Implement atomic delete if package is unused
21504            // It is currently possible that the package will be deleted even if it is installed
21505            // after this method returns.
21506            mHandler.post(new Runnable() {
21507                public void run() {
21508                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21509                }
21510            });
21511        }
21512    }
21513
21514    /**
21515     * Check and throw if the given before/after packages would be considered a
21516     * downgrade.
21517     */
21518    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21519            throws PackageManagerException {
21520        if (after.versionCode < before.mVersionCode) {
21521            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21522                    "Update version code " + after.versionCode + " is older than current "
21523                    + before.mVersionCode);
21524        } else if (after.versionCode == before.mVersionCode) {
21525            if (after.baseRevisionCode < before.baseRevisionCode) {
21526                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21527                        "Update base revision code " + after.baseRevisionCode
21528                        + " is older than current " + before.baseRevisionCode);
21529            }
21530
21531            if (!ArrayUtils.isEmpty(after.splitNames)) {
21532                for (int i = 0; i < after.splitNames.length; i++) {
21533                    final String splitName = after.splitNames[i];
21534                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21535                    if (j != -1) {
21536                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21537                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21538                                    "Update split " + splitName + " revision code "
21539                                    + after.splitRevisionCodes[i] + " is older than current "
21540                                    + before.splitRevisionCodes[j]);
21541                        }
21542                    }
21543                }
21544            }
21545        }
21546    }
21547
21548    private static class MoveCallbacks extends Handler {
21549        private static final int MSG_CREATED = 1;
21550        private static final int MSG_STATUS_CHANGED = 2;
21551
21552        private final RemoteCallbackList<IPackageMoveObserver>
21553                mCallbacks = new RemoteCallbackList<>();
21554
21555        private final SparseIntArray mLastStatus = new SparseIntArray();
21556
21557        public MoveCallbacks(Looper looper) {
21558            super(looper);
21559        }
21560
21561        public void register(IPackageMoveObserver callback) {
21562            mCallbacks.register(callback);
21563        }
21564
21565        public void unregister(IPackageMoveObserver callback) {
21566            mCallbacks.unregister(callback);
21567        }
21568
21569        @Override
21570        public void handleMessage(Message msg) {
21571            final SomeArgs args = (SomeArgs) msg.obj;
21572            final int n = mCallbacks.beginBroadcast();
21573            for (int i = 0; i < n; i++) {
21574                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21575                try {
21576                    invokeCallback(callback, msg.what, args);
21577                } catch (RemoteException ignored) {
21578                }
21579            }
21580            mCallbacks.finishBroadcast();
21581            args.recycle();
21582        }
21583
21584        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21585                throws RemoteException {
21586            switch (what) {
21587                case MSG_CREATED: {
21588                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21589                    break;
21590                }
21591                case MSG_STATUS_CHANGED: {
21592                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21593                    break;
21594                }
21595            }
21596        }
21597
21598        private void notifyCreated(int moveId, Bundle extras) {
21599            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21600
21601            final SomeArgs args = SomeArgs.obtain();
21602            args.argi1 = moveId;
21603            args.arg2 = extras;
21604            obtainMessage(MSG_CREATED, args).sendToTarget();
21605        }
21606
21607        private void notifyStatusChanged(int moveId, int status) {
21608            notifyStatusChanged(moveId, status, -1);
21609        }
21610
21611        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21612            Slog.v(TAG, "Move " + moveId + " status " + status);
21613
21614            final SomeArgs args = SomeArgs.obtain();
21615            args.argi1 = moveId;
21616            args.argi2 = status;
21617            args.arg3 = estMillis;
21618            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21619
21620            synchronized (mLastStatus) {
21621                mLastStatus.put(moveId, status);
21622            }
21623        }
21624    }
21625
21626    private final static class OnPermissionChangeListeners extends Handler {
21627        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21628
21629        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21630                new RemoteCallbackList<>();
21631
21632        public OnPermissionChangeListeners(Looper looper) {
21633            super(looper);
21634        }
21635
21636        @Override
21637        public void handleMessage(Message msg) {
21638            switch (msg.what) {
21639                case MSG_ON_PERMISSIONS_CHANGED: {
21640                    final int uid = msg.arg1;
21641                    handleOnPermissionsChanged(uid);
21642                } break;
21643            }
21644        }
21645
21646        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21647            mPermissionListeners.register(listener);
21648
21649        }
21650
21651        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21652            mPermissionListeners.unregister(listener);
21653        }
21654
21655        public void onPermissionsChanged(int uid) {
21656            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21657                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21658            }
21659        }
21660
21661        private void handleOnPermissionsChanged(int uid) {
21662            final int count = mPermissionListeners.beginBroadcast();
21663            try {
21664                for (int i = 0; i < count; i++) {
21665                    IOnPermissionsChangeListener callback = mPermissionListeners
21666                            .getBroadcastItem(i);
21667                    try {
21668                        callback.onPermissionsChanged(uid);
21669                    } catch (RemoteException e) {
21670                        Log.e(TAG, "Permission listener is dead", e);
21671                    }
21672                }
21673            } finally {
21674                mPermissionListeners.finishBroadcast();
21675            }
21676        }
21677    }
21678
21679    private class PackageManagerInternalImpl extends PackageManagerInternal {
21680        @Override
21681        public void setLocationPackagesProvider(PackagesProvider provider) {
21682            synchronized (mPackages) {
21683                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21684            }
21685        }
21686
21687        @Override
21688        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21689            synchronized (mPackages) {
21690                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21691            }
21692        }
21693
21694        @Override
21695        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21696            synchronized (mPackages) {
21697                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21698            }
21699        }
21700
21701        @Override
21702        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21703            synchronized (mPackages) {
21704                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21705            }
21706        }
21707
21708        @Override
21709        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21710            synchronized (mPackages) {
21711                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21712            }
21713        }
21714
21715        @Override
21716        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21717            synchronized (mPackages) {
21718                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21719            }
21720        }
21721
21722        @Override
21723        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21724            synchronized (mPackages) {
21725                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21726                        packageName, userId);
21727            }
21728        }
21729
21730        @Override
21731        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21732            synchronized (mPackages) {
21733                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21734                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21735                        packageName, userId);
21736            }
21737        }
21738
21739        @Override
21740        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21741            synchronized (mPackages) {
21742                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21743                        packageName, userId);
21744            }
21745        }
21746
21747        @Override
21748        public void setKeepUninstalledPackages(final List<String> packageList) {
21749            Preconditions.checkNotNull(packageList);
21750            List<String> removedFromList = null;
21751            synchronized (mPackages) {
21752                if (mKeepUninstalledPackages != null) {
21753                    final int packagesCount = mKeepUninstalledPackages.size();
21754                    for (int i = 0; i < packagesCount; i++) {
21755                        String oldPackage = mKeepUninstalledPackages.get(i);
21756                        if (packageList != null && packageList.contains(oldPackage)) {
21757                            continue;
21758                        }
21759                        if (removedFromList == null) {
21760                            removedFromList = new ArrayList<>();
21761                        }
21762                        removedFromList.add(oldPackage);
21763                    }
21764                }
21765                mKeepUninstalledPackages = new ArrayList<>(packageList);
21766                if (removedFromList != null) {
21767                    final int removedCount = removedFromList.size();
21768                    for (int i = 0; i < removedCount; i++) {
21769                        deletePackageIfUnusedLPr(removedFromList.get(i));
21770                    }
21771                }
21772            }
21773        }
21774
21775        @Override
21776        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21777            synchronized (mPackages) {
21778                // If we do not support permission review, done.
21779                if (!mPermissionReviewRequired) {
21780                    return false;
21781                }
21782
21783                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21784                if (packageSetting == null) {
21785                    return false;
21786                }
21787
21788                // Permission review applies only to apps not supporting the new permission model.
21789                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21790                    return false;
21791                }
21792
21793                // Legacy apps have the permission and get user consent on launch.
21794                PermissionsState permissionsState = packageSetting.getPermissionsState();
21795                return permissionsState.isPermissionReviewRequired(userId);
21796            }
21797        }
21798
21799        @Override
21800        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21801            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21802        }
21803
21804        @Override
21805        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21806                int userId) {
21807            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21808        }
21809
21810        @Override
21811        public void setDeviceAndProfileOwnerPackages(
21812                int deviceOwnerUserId, String deviceOwnerPackage,
21813                SparseArray<String> profileOwnerPackages) {
21814            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21815                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21816        }
21817
21818        @Override
21819        public boolean isPackageDataProtected(int userId, String packageName) {
21820            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21821        }
21822
21823        @Override
21824        public boolean isPackageEphemeral(int userId, String packageName) {
21825            synchronized (mPackages) {
21826                PackageParser.Package p = mPackages.get(packageName);
21827                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21828            }
21829        }
21830
21831        @Override
21832        public boolean wasPackageEverLaunched(String packageName, int userId) {
21833            synchronized (mPackages) {
21834                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21835            }
21836        }
21837
21838        @Override
21839        public void grantRuntimePermission(String packageName, String name, int userId,
21840                boolean overridePolicy) {
21841            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21842                    overridePolicy);
21843        }
21844
21845        @Override
21846        public void revokeRuntimePermission(String packageName, String name, int userId,
21847                boolean overridePolicy) {
21848            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21849                    overridePolicy);
21850        }
21851
21852        @Override
21853        public String getNameForUid(int uid) {
21854            return PackageManagerService.this.getNameForUid(uid);
21855        }
21856
21857        @Override
21858        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21859                Intent origIntent, String resolvedType, Intent launchIntent,
21860                String callingPackage, int userId) {
21861            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21862                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21863        }
21864
21865        public String getSetupWizardPackageName() {
21866            return mSetupWizardPackage;
21867        }
21868    }
21869
21870    @Override
21871    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21872        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21873        synchronized (mPackages) {
21874            final long identity = Binder.clearCallingIdentity();
21875            try {
21876                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21877                        packageNames, userId);
21878            } finally {
21879                Binder.restoreCallingIdentity(identity);
21880            }
21881        }
21882    }
21883
21884    private static void enforceSystemOrPhoneCaller(String tag) {
21885        int callingUid = Binder.getCallingUid();
21886        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21887            throw new SecurityException(
21888                    "Cannot call " + tag + " from UID " + callingUid);
21889        }
21890    }
21891
21892    boolean isHistoricalPackageUsageAvailable() {
21893        return mPackageUsage.isHistoricalPackageUsageAvailable();
21894    }
21895
21896    /**
21897     * Return a <b>copy</b> of the collection of packages known to the package manager.
21898     * @return A copy of the values of mPackages.
21899     */
21900    Collection<PackageParser.Package> getPackages() {
21901        synchronized (mPackages) {
21902            return new ArrayList<>(mPackages.values());
21903        }
21904    }
21905
21906    /**
21907     * Logs process start information (including base APK hash) to the security log.
21908     * @hide
21909     */
21910    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21911            String apkFile, int pid) {
21912        if (!SecurityLog.isLoggingEnabled()) {
21913            return;
21914        }
21915        Bundle data = new Bundle();
21916        data.putLong("startTimestamp", System.currentTimeMillis());
21917        data.putString("processName", processName);
21918        data.putInt("uid", uid);
21919        data.putString("seinfo", seinfo);
21920        data.putString("apkFile", apkFile);
21921        data.putInt("pid", pid);
21922        Message msg = mProcessLoggingHandler.obtainMessage(
21923                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21924        msg.setData(data);
21925        mProcessLoggingHandler.sendMessage(msg);
21926    }
21927
21928    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21929        return mCompilerStats.getPackageStats(pkgName);
21930    }
21931
21932    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21933        return getOrCreateCompilerPackageStats(pkg.packageName);
21934    }
21935
21936    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21937        return mCompilerStats.getOrCreatePackageStats(pkgName);
21938    }
21939
21940    public void deleteCompilerPackageStats(String pkgName) {
21941        mCompilerStats.deletePackageStats(pkgName);
21942    }
21943
21944    @Override
21945    public int getInstallReason(String packageName, int userId) {
21946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
21947                true /* requireFullPermission */, false /* checkShell */,
21948                "get install reason");
21949        synchronized (mPackages) {
21950            final PackageSetting ps = mSettings.mPackages.get(packageName);
21951            if (ps != null) {
21952                return ps.getInstallReason(userId);
21953            }
21954        }
21955        return PackageManager.INSTALL_REASON_UNKNOWN;
21956    }
21957}
21958