PackageManagerService.java revision 5733d9de2ce946789c4d777179eb251cc3526d27
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.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ComponentInfo;
130import android.content.pm.EphemeralApplicationInfo;
131import android.content.pm.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.EphemeralResponse;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManagerInternal;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.system.ErrnoException;
215import android.system.Os;
216import android.text.TextUtils;
217import android.text.format.DateUtils;
218import android.util.ArrayMap;
219import android.util.ArraySet;
220import android.util.Base64;
221import android.util.DisplayMetrics;
222import android.util.EventLog;
223import android.util.ExceptionUtils;
224import android.util.Log;
225import android.util.LogPrinter;
226import android.util.MathUtils;
227import android.util.PackageUtils;
228import android.util.Pair;
229import android.util.PrintStreamPrinter;
230import android.util.Slog;
231import android.util.SparseArray;
232import android.util.SparseBooleanArray;
233import android.util.SparseIntArray;
234import android.util.Xml;
235import android.util.jar.StrictJarFile;
236import android.view.Display;
237
238import com.android.internal.R;
239import com.android.internal.annotations.GuardedBy;
240import com.android.internal.app.IMediaContainerService;
241import com.android.internal.app.ResolverActivity;
242import com.android.internal.content.NativeLibraryHelper;
243import com.android.internal.content.PackageHelper;
244import com.android.internal.logging.MetricsLogger;
245import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
246import com.android.internal.os.IParcelFileDescriptorFactory;
247import com.android.internal.os.RoSystemProperties;
248import com.android.internal.os.SomeArgs;
249import com.android.internal.os.Zygote;
250import com.android.internal.telephony.CarrierAppUtils;
251import com.android.internal.util.ArrayUtils;
252import com.android.internal.util.FastPrintWriter;
253import com.android.internal.util.FastXmlSerializer;
254import com.android.internal.util.IndentingPrintWriter;
255import com.android.internal.util.Preconditions;
256import com.android.internal.util.XmlUtils;
257import com.android.server.AttributeCache;
258import com.android.server.EventLogTags;
259import com.android.server.FgThread;
260import com.android.server.IntentResolver;
261import com.android.server.LocalServices;
262import com.android.server.ServiceThread;
263import com.android.server.SystemConfig;
264import com.android.server.Watchdog;
265import com.android.server.net.NetworkPolicyManagerInternal;
266import com.android.server.pm.Installer.InstallerException;
267import com.android.server.pm.PermissionsState.PermissionState;
268import com.android.server.pm.Settings.DatabaseVersion;
269import com.android.server.pm.Settings.VersionInfo;
270import com.android.server.pm.dex.DexManager;
271import com.android.server.storage.DeviceStorageMonitorInternal;
272
273import dalvik.system.CloseGuard;
274import dalvik.system.DexFile;
275import dalvik.system.VMRuntime;
276
277import libcore.io.IoUtils;
278import libcore.util.EmptyArray;
279
280import org.xmlpull.v1.XmlPullParser;
281import org.xmlpull.v1.XmlPullParserException;
282import org.xmlpull.v1.XmlSerializer;
283
284import java.io.BufferedOutputStream;
285import java.io.BufferedReader;
286import java.io.ByteArrayInputStream;
287import java.io.ByteArrayOutputStream;
288import java.io.File;
289import java.io.FileDescriptor;
290import java.io.FileInputStream;
291import java.io.FileNotFoundException;
292import java.io.FileOutputStream;
293import java.io.FileReader;
294import java.io.FilenameFilter;
295import java.io.IOException;
296import java.io.PrintWriter;
297import java.nio.charset.StandardCharsets;
298import java.security.DigestInputStream;
299import java.security.MessageDigest;
300import java.security.NoSuchAlgorithmException;
301import java.security.PublicKey;
302import java.security.SecureRandom;
303import java.security.cert.Certificate;
304import java.security.cert.CertificateEncodingException;
305import java.security.cert.CertificateException;
306import java.text.SimpleDateFormat;
307import java.util.ArrayList;
308import java.util.Arrays;
309import java.util.Collection;
310import java.util.Collections;
311import java.util.Comparator;
312import java.util.Date;
313import java.util.HashSet;
314import java.util.HashMap;
315import java.util.Iterator;
316import java.util.List;
317import java.util.Map;
318import java.util.Objects;
319import java.util.Set;
320import java.util.concurrent.CountDownLatch;
321import java.util.concurrent.TimeUnit;
322import java.util.concurrent.atomic.AtomicBoolean;
323import java.util.concurrent.atomic.AtomicInteger;
324
325/**
326 * Keep track of all those APKs everywhere.
327 * <p>
328 * Internally there are two important locks:
329 * <ul>
330 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
331 * and other related state. It is a fine-grained lock that should only be held
332 * momentarily, as it's one of the most contended locks in the system.
333 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
334 * operations typically involve heavy lifting of application data on disk. Since
335 * {@code installd} is single-threaded, and it's operations can often be slow,
336 * this lock should never be acquired while already holding {@link #mPackages}.
337 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
338 * holding {@link #mInstallLock}.
339 * </ul>
340 * Many internal methods rely on the caller to hold the appropriate locks, and
341 * this contract is expressed through method name suffixes:
342 * <ul>
343 * <li>fooLI(): the caller must hold {@link #mInstallLock}
344 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
345 * being modified must be frozen
346 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
347 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
348 * </ul>
349 * <p>
350 * Because this class is very central to the platform's security; please run all
351 * CTS and unit tests whenever making modifications:
352 *
353 * <pre>
354 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
355 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
356 * </pre>
357 */
358public class PackageManagerService extends IPackageManager.Stub {
359    static final String TAG = "PackageManager";
360    static final boolean DEBUG_SETTINGS = false;
361    static final boolean DEBUG_PREFERRED = false;
362    static final boolean DEBUG_UPGRADE = false;
363    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
364    private static final boolean DEBUG_BACKUP = false;
365    private static final boolean DEBUG_INSTALL = false;
366    private static final boolean DEBUG_REMOVE = false;
367    private static final boolean DEBUG_BROADCASTS = false;
368    private static final boolean DEBUG_SHOW_INFO = false;
369    private static final boolean DEBUG_PACKAGE_INFO = false;
370    private static final boolean DEBUG_INTENT_MATCHING = false;
371    private static final boolean DEBUG_PACKAGE_SCANNING = false;
372    private static final boolean DEBUG_VERIFY = false;
373    private static final boolean DEBUG_FILTERS = false;
374
375    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
376    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
377    // user, but by default initialize to this.
378    static final boolean DEBUG_DEXOPT = false;
379
380    private static final boolean DEBUG_ABI_SELECTION = false;
381    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
382    private static final boolean DEBUG_TRIAGED_MISSING = false;
383    private static final boolean DEBUG_APP_DATA = false;
384
385    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
386    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
387
388    private static final boolean DISABLE_EPHEMERAL_APPS = false;
389    private static final boolean HIDE_EPHEMERAL_APIS = true;
390
391    private static final boolean ENABLE_QUOTA =
392            SystemProperties.getBoolean("persist.fw.quota", false);
393
394    private static final int RADIO_UID = Process.PHONE_UID;
395    private static final int LOG_UID = Process.LOG_UID;
396    private static final int NFC_UID = Process.NFC_UID;
397    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
398    private static final int SHELL_UID = Process.SHELL_UID;
399
400    // Cap the size of permission trees that 3rd party apps can define
401    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
402
403    // Suffix used during package installation when copying/moving
404    // package apks to install directory.
405    private static final String INSTALL_PACKAGE_SUFFIX = "-";
406
407    static final int SCAN_NO_DEX = 1<<1;
408    static final int SCAN_FORCE_DEX = 1<<2;
409    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
410    static final int SCAN_NEW_INSTALL = 1<<4;
411    static final int SCAN_UPDATE_TIME = 1<<5;
412    static final int SCAN_BOOTING = 1<<6;
413    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
414    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
415    static final int SCAN_REPLACING = 1<<9;
416    static final int SCAN_REQUIRE_KNOWN = 1<<10;
417    static final int SCAN_MOVE = 1<<11;
418    static final int SCAN_INITIAL = 1<<12;
419    static final int SCAN_CHECK_ONLY = 1<<13;
420    static final int SCAN_DONT_KILL_APP = 1<<14;
421    static final int SCAN_IGNORE_FROZEN = 1<<15;
422    static final int REMOVE_CHATTY = 1<<16;
423    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
424
425    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
426
427    private static final int[] EMPTY_INT_ARRAY = new int[0];
428
429    /**
430     * Timeout (in milliseconds) after which the watchdog should declare that
431     * our handler thread is wedged.  The usual default for such things is one
432     * minute but we sometimes do very lengthy I/O operations on this thread,
433     * such as installing multi-gigabyte applications, so ours needs to be longer.
434     */
435    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
436
437    /**
438     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
439     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
440     * settings entry if available, otherwise we use the hardcoded default.  If it's been
441     * more than this long since the last fstrim, we force one during the boot sequence.
442     *
443     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
444     * one gets run at the next available charging+idle time.  This final mandatory
445     * no-fstrim check kicks in only of the other scheduling criteria is never met.
446     */
447    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
448
449    /**
450     * Whether verification is enabled by default.
451     */
452    private static final boolean DEFAULT_VERIFY_ENABLE = true;
453
454    /**
455     * The default maximum time to wait for the verification agent to return in
456     * milliseconds.
457     */
458    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
459
460    /**
461     * The default response for package verification timeout.
462     *
463     * This can be either PackageManager.VERIFICATION_ALLOW or
464     * PackageManager.VERIFICATION_REJECT.
465     */
466    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
467
468    static final String PLATFORM_PACKAGE_NAME = "android";
469
470    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
471
472    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
473            DEFAULT_CONTAINER_PACKAGE,
474            "com.android.defcontainer.DefaultContainerService");
475
476    private static final String KILL_APP_REASON_GIDS_CHANGED =
477            "permission grant or revoke changed gids";
478
479    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
480            "permissions revoked";
481
482    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
483
484    private static final String PACKAGE_SCHEME = "package";
485
486    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
487    /**
488     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
489     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
490     * VENDOR_OVERLAY_DIR.
491     */
492    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
493    /**
494     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
495     * is in VENDOR_OVERLAY_THEME_PROPERTY.
496     */
497    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
498            = "persist.vendor.overlay.theme";
499
500    /** Permission grant: not grant the permission. */
501    private static final int GRANT_DENIED = 1;
502
503    /** Permission grant: grant the permission as an install permission. */
504    private static final int GRANT_INSTALL = 2;
505
506    /** Permission grant: grant the permission as a runtime one. */
507    private static final int GRANT_RUNTIME = 3;
508
509    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
510    private static final int GRANT_UPGRADE = 4;
511
512    /** Canonical intent used to identify what counts as a "web browser" app */
513    private static final Intent sBrowserIntent;
514    static {
515        sBrowserIntent = new Intent();
516        sBrowserIntent.setAction(Intent.ACTION_VIEW);
517        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
518        sBrowserIntent.setData(Uri.parse("http:"));
519    }
520
521    /**
522     * The set of all protected actions [i.e. those actions for which a high priority
523     * intent filter is disallowed].
524     */
525    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
526    static {
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
530        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
531    }
532
533    // Compilation reasons.
534    public static final int REASON_FIRST_BOOT = 0;
535    public static final int REASON_BOOT = 1;
536    public static final int REASON_INSTALL = 2;
537    public static final int REASON_BACKGROUND_DEXOPT = 3;
538    public static final int REASON_AB_OTA = 4;
539    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
540    public static final int REASON_SHARED_APK = 6;
541    public static final int REASON_FORCED_DEXOPT = 7;
542    public static final int REASON_CORE_APP = 8;
543
544    public static final int REASON_LAST = REASON_CORE_APP;
545
546    /** Special library name that skips shared libraries check during compilation. */
547    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
548
549    /** All dangerous permission names in the same order as the events in MetricsEvent */
550    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
551            Manifest.permission.READ_CALENDAR,
552            Manifest.permission.WRITE_CALENDAR,
553            Manifest.permission.CAMERA,
554            Manifest.permission.READ_CONTACTS,
555            Manifest.permission.WRITE_CONTACTS,
556            Manifest.permission.GET_ACCOUNTS,
557            Manifest.permission.ACCESS_FINE_LOCATION,
558            Manifest.permission.ACCESS_COARSE_LOCATION,
559            Manifest.permission.RECORD_AUDIO,
560            Manifest.permission.READ_PHONE_STATE,
561            Manifest.permission.CALL_PHONE,
562            Manifest.permission.READ_CALL_LOG,
563            Manifest.permission.WRITE_CALL_LOG,
564            Manifest.permission.ADD_VOICEMAIL,
565            Manifest.permission.USE_SIP,
566            Manifest.permission.PROCESS_OUTGOING_CALLS,
567            Manifest.permission.READ_CELL_BROADCASTS,
568            Manifest.permission.BODY_SENSORS,
569            Manifest.permission.SEND_SMS,
570            Manifest.permission.RECEIVE_SMS,
571            Manifest.permission.READ_SMS,
572            Manifest.permission.RECEIVE_WAP_PUSH,
573            Manifest.permission.RECEIVE_MMS,
574            Manifest.permission.READ_EXTERNAL_STORAGE,
575            Manifest.permission.WRITE_EXTERNAL_STORAGE,
576            Manifest.permission.READ_PHONE_NUMBER);
577
578
579    /**
580     * Version number for the package parser cache. Increment this whenever the format or
581     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
582     */
583    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
584
585    /**
586     * Whether the package parser cache is enabled.
587     */
588    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
589
590    final ServiceThread mHandlerThread;
591
592    final PackageHandler mHandler;
593
594    private final ProcessLoggingHandler mProcessLoggingHandler;
595
596    /**
597     * Messages for {@link #mHandler} that need to wait for system ready before
598     * being dispatched.
599     */
600    private ArrayList<Message> mPostSystemReadyMessages;
601
602    final int mSdkVersion = Build.VERSION.SDK_INT;
603
604    final Context mContext;
605    final boolean mFactoryTest;
606    final boolean mOnlyCore;
607    final DisplayMetrics mMetrics;
608    final int mDefParseFlags;
609    final String[] mSeparateProcesses;
610    final boolean mIsUpgrade;
611    final boolean mIsPreNUpgrade;
612    final boolean mIsPreNMR1Upgrade;
613
614    @GuardedBy("mPackages")
615    private boolean mDexOptDialogShown;
616
617    /** The location for ASEC container files on internal storage. */
618    final String mAsecInternalPath;
619
620    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
621    // LOCK HELD.  Can be called with mInstallLock held.
622    @GuardedBy("mInstallLock")
623    final Installer mInstaller;
624
625    /** Directory where installed third-party apps stored */
626    final File mAppInstallDir;
627    final File mEphemeralInstallDir;
628
629    /**
630     * Directory to which applications installed internally have their
631     * 32 bit native libraries copied.
632     */
633    private File mAppLib32InstallDir;
634
635    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
636    // apps.
637    final File mDrmAppPrivateInstallDir;
638
639    // ----------------------------------------------------------------
640
641    // Lock for state used when installing and doing other long running
642    // operations.  Methods that must be called with this lock held have
643    // the suffix "LI".
644    final Object mInstallLock = new Object();
645
646    // ----------------------------------------------------------------
647
648    // Keys are String (package name), values are Package.  This also serves
649    // as the lock for the global state.  Methods that must be called with
650    // this lock held have the prefix "LP".
651    @GuardedBy("mPackages")
652    final ArrayMap<String, PackageParser.Package> mPackages =
653            new ArrayMap<String, PackageParser.Package>();
654
655    final ArrayMap<String, Set<String>> mKnownCodebase =
656            new ArrayMap<String, Set<String>>();
657
658    // Tracks available target package names -> overlay package paths.
659    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
660        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
661
662    /**
663     * Tracks new system packages [received in an OTA] that we expect to
664     * find updated user-installed versions. Keys are package name, values
665     * are package location.
666     */
667    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
668    /**
669     * Tracks high priority intent filters for protected actions. During boot, certain
670     * filter actions are protected and should never be allowed to have a high priority
671     * intent filter for them. However, there is one, and only one exception -- the
672     * setup wizard. It must be able to define a high priority intent filter for these
673     * actions to ensure there are no escapes from the wizard. We need to delay processing
674     * of these during boot as we need to look at all of the system packages in order
675     * to know which component is the setup wizard.
676     */
677    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
678    /**
679     * Whether or not processing protected filters should be deferred.
680     */
681    private boolean mDeferProtectedFilters = true;
682
683    /**
684     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
685     */
686    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
687    /**
688     * Whether or not system app permissions should be promoted from install to runtime.
689     */
690    boolean mPromoteSystemApps;
691
692    @GuardedBy("mPackages")
693    final Settings mSettings;
694
695    /**
696     * Set of package names that are currently "frozen", which means active
697     * surgery is being done on the code/data for that package. The platform
698     * will refuse to launch frozen packages to avoid race conditions.
699     *
700     * @see PackageFreezer
701     */
702    @GuardedBy("mPackages")
703    final ArraySet<String> mFrozenPackages = new ArraySet<>();
704
705    final ProtectedPackages mProtectedPackages;
706
707    boolean mFirstBoot;
708
709    // System configuration read by SystemConfig.
710    final int[] mGlobalGids;
711    final SparseArray<ArraySet<String>> mSystemPermissions;
712    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
713
714    // If mac_permissions.xml was found for seinfo labeling.
715    boolean mFoundPolicyFile;
716
717    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
718
719    public static final class SharedLibraryEntry {
720        public final String path;
721        public final String apk;
722        public final SharedLibraryInfo info;
723
724        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
725                String declaringPackageName, int declaringPackageVersionCode) {
726            path = _path;
727            apk = _apk;
728            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
729                    declaringPackageName, declaringPackageVersionCode), null);
730        }
731    }
732
733    // Currently known shared libraries.
734    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
735    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
736            new ArrayMap<>();
737
738    // All available activities, for your resolving pleasure.
739    final ActivityIntentResolver mActivities =
740            new ActivityIntentResolver();
741
742    // All available receivers, for your resolving pleasure.
743    final ActivityIntentResolver mReceivers =
744            new ActivityIntentResolver();
745
746    // All available services, for your resolving pleasure.
747    final ServiceIntentResolver mServices = new ServiceIntentResolver();
748
749    // All available providers, for your resolving pleasure.
750    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
751
752    // Mapping from provider base names (first directory in content URI codePath)
753    // to the provider information.
754    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
755            new ArrayMap<String, PackageParser.Provider>();
756
757    // Mapping from instrumentation class names to info about them.
758    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
759            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
760
761    // Mapping from permission names to info about them.
762    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
763            new ArrayMap<String, PackageParser.PermissionGroup>();
764
765    // Packages whose data we have transfered into another package, thus
766    // should no longer exist.
767    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
768
769    // Broadcast actions that are only available to the system.
770    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
771
772    /** List of packages waiting for verification. */
773    final SparseArray<PackageVerificationState> mPendingVerification
774            = new SparseArray<PackageVerificationState>();
775
776    /** Set of packages associated with each app op permission. */
777    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
778
779    final PackageInstallerService mInstallerService;
780
781    private final PackageDexOptimizer mPackageDexOptimizer;
782    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
783    // is used by other apps).
784    private final DexManager mDexManager;
785
786    private AtomicInteger mNextMoveId = new AtomicInteger();
787    private final MoveCallbacks mMoveCallbacks;
788
789    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
790
791    // Cache of users who need badging.
792    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
793
794    /** Token for keys in mPendingVerification. */
795    private int mPendingVerificationToken = 0;
796
797    volatile boolean mSystemReady;
798    volatile boolean mSafeMode;
799    volatile boolean mHasSystemUidErrors;
800
801    ApplicationInfo mAndroidApplication;
802    final ActivityInfo mResolveActivity = new ActivityInfo();
803    final ResolveInfo mResolveInfo = new ResolveInfo();
804    ComponentName mResolveComponentName;
805    PackageParser.Package mPlatformPackage;
806    ComponentName mCustomResolverComponentName;
807
808    boolean mResolverReplaced = false;
809
810    private final @Nullable ComponentName mIntentFilterVerifierComponent;
811    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
812
813    private int mIntentFilterVerificationToken = 0;
814
815    /** The service connection to the ephemeral resolver */
816    final EphemeralResolverConnection mEphemeralResolverConnection;
817
818    /** Component used to install ephemeral applications */
819    ComponentName mEphemeralInstallerComponent;
820    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
821    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
822
823    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
824            = new SparseArray<IntentFilterVerificationState>();
825
826    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
827
828    // List of packages names to keep cached, even if they are uninstalled for all users
829    private List<String> mKeepUninstalledPackages;
830
831    private UserManagerInternal mUserManagerInternal;
832
833    private File mCacheDir;
834
835    private static class IFVerificationParams {
836        PackageParser.Package pkg;
837        boolean replacing;
838        int userId;
839        int verifierUid;
840
841        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
842                int _userId, int _verifierUid) {
843            pkg = _pkg;
844            replacing = _replacing;
845            userId = _userId;
846            replacing = _replacing;
847            verifierUid = _verifierUid;
848        }
849    }
850
851    private interface IntentFilterVerifier<T extends IntentFilter> {
852        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
853                                               T filter, String packageName);
854        void startVerifications(int userId);
855        void receiveVerificationResponse(int verificationId);
856    }
857
858    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
859        private Context mContext;
860        private ComponentName mIntentFilterVerifierComponent;
861        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
862
863        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
864            mContext = context;
865            mIntentFilterVerifierComponent = verifierComponent;
866        }
867
868        private String getDefaultScheme() {
869            return IntentFilter.SCHEME_HTTPS;
870        }
871
872        @Override
873        public void startVerifications(int userId) {
874            // Launch verifications requests
875            int count = mCurrentIntentFilterVerifications.size();
876            for (int n=0; n<count; n++) {
877                int verificationId = mCurrentIntentFilterVerifications.get(n);
878                final IntentFilterVerificationState ivs =
879                        mIntentFilterVerificationStates.get(verificationId);
880
881                String packageName = ivs.getPackageName();
882
883                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
884                final int filterCount = filters.size();
885                ArraySet<String> domainsSet = new ArraySet<>();
886                for (int m=0; m<filterCount; m++) {
887                    PackageParser.ActivityIntentInfo filter = filters.get(m);
888                    domainsSet.addAll(filter.getHostsList());
889                }
890                synchronized (mPackages) {
891                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
892                            packageName, domainsSet) != null) {
893                        scheduleWriteSettingsLocked();
894                    }
895                }
896                sendVerificationRequest(userId, verificationId, ivs);
897            }
898            mCurrentIntentFilterVerifications.clear();
899        }
900
901        private void sendVerificationRequest(int userId, int verificationId,
902                IntentFilterVerificationState ivs) {
903
904            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
905            verificationIntent.putExtra(
906                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
907                    verificationId);
908            verificationIntent.putExtra(
909                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
910                    getDefaultScheme());
911            verificationIntent.putExtra(
912                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
913                    ivs.getHostsString());
914            verificationIntent.putExtra(
915                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
916                    ivs.getPackageName());
917            verificationIntent.setComponent(mIntentFilterVerifierComponent);
918            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
919
920            UserHandle user = new UserHandle(userId);
921            mContext.sendBroadcastAsUser(verificationIntent, user);
922            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
923                    "Sending IntentFilter verification broadcast");
924        }
925
926        public void receiveVerificationResponse(int verificationId) {
927            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
928
929            final boolean verified = ivs.isVerified();
930
931            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
932            final int count = filters.size();
933            if (DEBUG_DOMAIN_VERIFICATION) {
934                Slog.i(TAG, "Received verification response " + verificationId
935                        + " for " + count + " filters, verified=" + verified);
936            }
937            for (int n=0; n<count; n++) {
938                PackageParser.ActivityIntentInfo filter = filters.get(n);
939                filter.setVerified(verified);
940
941                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
942                        + " verified with result:" + verified + " and hosts:"
943                        + ivs.getHostsString());
944            }
945
946            mIntentFilterVerificationStates.remove(verificationId);
947
948            final String packageName = ivs.getPackageName();
949            IntentFilterVerificationInfo ivi = null;
950
951            synchronized (mPackages) {
952                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
953            }
954            if (ivi == null) {
955                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
956                        + verificationId + " packageName:" + packageName);
957                return;
958            }
959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
960                    "Updating IntentFilterVerificationInfo for package " + packageName
961                            +" verificationId:" + verificationId);
962
963            synchronized (mPackages) {
964                if (verified) {
965                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
966                } else {
967                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
968                }
969                scheduleWriteSettingsLocked();
970
971                final int userId = ivs.getUserId();
972                if (userId != UserHandle.USER_ALL) {
973                    final int userStatus =
974                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
975
976                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
977                    boolean needUpdate = false;
978
979                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
980                    // already been set by the User thru the Disambiguation dialog
981                    switch (userStatus) {
982                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
983                            if (verified) {
984                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
985                            } else {
986                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
987                            }
988                            needUpdate = true;
989                            break;
990
991                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
992                            if (verified) {
993                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
994                                needUpdate = true;
995                            }
996                            break;
997
998                        default:
999                            // Nothing to do
1000                    }
1001
1002                    if (needUpdate) {
1003                        mSettings.updateIntentFilterVerificationStatusLPw(
1004                                packageName, updatedStatus, userId);
1005                        scheduleWritePackageRestrictionsLocked(userId);
1006                    }
1007                }
1008            }
1009        }
1010
1011        @Override
1012        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1013                    ActivityIntentInfo filter, String packageName) {
1014            if (!hasValidDomains(filter)) {
1015                return false;
1016            }
1017            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1018            if (ivs == null) {
1019                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1020                        packageName);
1021            }
1022            if (DEBUG_DOMAIN_VERIFICATION) {
1023                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1024            }
1025            ivs.addFilter(filter);
1026            return true;
1027        }
1028
1029        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1030                int userId, int verificationId, String packageName) {
1031            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1032                    verifierUid, userId, packageName);
1033            ivs.setPendingState();
1034            synchronized (mPackages) {
1035                mIntentFilterVerificationStates.append(verificationId, ivs);
1036                mCurrentIntentFilterVerifications.add(verificationId);
1037            }
1038            return ivs;
1039        }
1040    }
1041
1042    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1043        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1044                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1045                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1046    }
1047
1048    // Set of pending broadcasts for aggregating enable/disable of components.
1049    static class PendingPackageBroadcasts {
1050        // for each user id, a map of <package name -> components within that package>
1051        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1052
1053        public PendingPackageBroadcasts() {
1054            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1055        }
1056
1057        public ArrayList<String> get(int userId, String packageName) {
1058            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1059            return packages.get(packageName);
1060        }
1061
1062        public void put(int userId, String packageName, ArrayList<String> components) {
1063            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1064            packages.put(packageName, components);
1065        }
1066
1067        public void remove(int userId, String packageName) {
1068            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1069            if (packages != null) {
1070                packages.remove(packageName);
1071            }
1072        }
1073
1074        public void remove(int userId) {
1075            mUidMap.remove(userId);
1076        }
1077
1078        public int userIdCount() {
1079            return mUidMap.size();
1080        }
1081
1082        public int userIdAt(int n) {
1083            return mUidMap.keyAt(n);
1084        }
1085
1086        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1087            return mUidMap.get(userId);
1088        }
1089
1090        public int size() {
1091            // total number of pending broadcast entries across all userIds
1092            int num = 0;
1093            for (int i = 0; i< mUidMap.size(); i++) {
1094                num += mUidMap.valueAt(i).size();
1095            }
1096            return num;
1097        }
1098
1099        public void clear() {
1100            mUidMap.clear();
1101        }
1102
1103        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1104            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1105            if (map == null) {
1106                map = new ArrayMap<String, ArrayList<String>>();
1107                mUidMap.put(userId, map);
1108            }
1109            return map;
1110        }
1111    }
1112    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1113
1114    // Service Connection to remote media container service to copy
1115    // package uri's from external media onto secure containers
1116    // or internal storage.
1117    private IMediaContainerService mContainerService = null;
1118
1119    static final int SEND_PENDING_BROADCAST = 1;
1120    static final int MCS_BOUND = 3;
1121    static final int END_COPY = 4;
1122    static final int INIT_COPY = 5;
1123    static final int MCS_UNBIND = 6;
1124    static final int START_CLEANING_PACKAGE = 7;
1125    static final int FIND_INSTALL_LOC = 8;
1126    static final int POST_INSTALL = 9;
1127    static final int MCS_RECONNECT = 10;
1128    static final int MCS_GIVE_UP = 11;
1129    static final int UPDATED_MEDIA_STATUS = 12;
1130    static final int WRITE_SETTINGS = 13;
1131    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1132    static final int PACKAGE_VERIFIED = 15;
1133    static final int CHECK_PENDING_VERIFICATION = 16;
1134    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1135    static final int INTENT_FILTER_VERIFIED = 18;
1136    static final int WRITE_PACKAGE_LIST = 19;
1137    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1138
1139    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1140
1141    // Delay time in millisecs
1142    static final int BROADCAST_DELAY = 10 * 1000;
1143
1144    static UserManagerService sUserManager;
1145
1146    // Stores a list of users whose package restrictions file needs to be updated
1147    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1148
1149    final private DefaultContainerConnection mDefContainerConn =
1150            new DefaultContainerConnection();
1151    class DefaultContainerConnection implements ServiceConnection {
1152        public void onServiceConnected(ComponentName name, IBinder service) {
1153            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1154            final IMediaContainerService imcs = IMediaContainerService.Stub
1155                    .asInterface(Binder.allowBlocking(service));
1156            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1157        }
1158
1159        public void onServiceDisconnected(ComponentName name) {
1160            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1161        }
1162    }
1163
1164    // Recordkeeping of restore-after-install operations that are currently in flight
1165    // between the Package Manager and the Backup Manager
1166    static class PostInstallData {
1167        public InstallArgs args;
1168        public PackageInstalledInfo res;
1169
1170        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1171            args = _a;
1172            res = _r;
1173        }
1174    }
1175
1176    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1177    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1178
1179    // XML tags for backup/restore of various bits of state
1180    private static final String TAG_PREFERRED_BACKUP = "pa";
1181    private static final String TAG_DEFAULT_APPS = "da";
1182    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1183
1184    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1185    private static final String TAG_ALL_GRANTS = "rt-grants";
1186    private static final String TAG_GRANT = "grant";
1187    private static final String ATTR_PACKAGE_NAME = "pkg";
1188
1189    private static final String TAG_PERMISSION = "perm";
1190    private static final String ATTR_PERMISSION_NAME = "name";
1191    private static final String ATTR_IS_GRANTED = "g";
1192    private static final String ATTR_USER_SET = "set";
1193    private static final String ATTR_USER_FIXED = "fixed";
1194    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1195
1196    // System/policy permission grants are not backed up
1197    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1198            FLAG_PERMISSION_POLICY_FIXED
1199            | FLAG_PERMISSION_SYSTEM_FIXED
1200            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1201
1202    // And we back up these user-adjusted states
1203    private static final int USER_RUNTIME_GRANT_MASK =
1204            FLAG_PERMISSION_USER_SET
1205            | FLAG_PERMISSION_USER_FIXED
1206            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1207
1208    final @Nullable String mRequiredVerifierPackage;
1209    final @NonNull String mRequiredInstallerPackage;
1210    final @NonNull String mRequiredUninstallerPackage;
1211    final @Nullable String mSetupWizardPackage;
1212    final @Nullable String mStorageManagerPackage;
1213    final @NonNull String mServicesSystemSharedLibraryPackageName;
1214    final @NonNull String mSharedSystemSharedLibraryPackageName;
1215
1216    final boolean mPermissionReviewRequired;
1217
1218    private final PackageUsage mPackageUsage = new PackageUsage();
1219    private final CompilerStats mCompilerStats = new CompilerStats();
1220
1221    class PackageHandler extends Handler {
1222        private boolean mBound = false;
1223        final ArrayList<HandlerParams> mPendingInstalls =
1224            new ArrayList<HandlerParams>();
1225
1226        private boolean connectToService() {
1227            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1228                    " DefaultContainerService");
1229            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1230            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1231            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1232                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1233                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1234                mBound = true;
1235                return true;
1236            }
1237            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1238            return false;
1239        }
1240
1241        private void disconnectService() {
1242            mContainerService = null;
1243            mBound = false;
1244            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1245            mContext.unbindService(mDefContainerConn);
1246            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1247        }
1248
1249        PackageHandler(Looper looper) {
1250            super(looper);
1251        }
1252
1253        public void handleMessage(Message msg) {
1254            try {
1255                doHandleMessage(msg);
1256            } finally {
1257                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1258            }
1259        }
1260
1261        void doHandleMessage(Message msg) {
1262            switch (msg.what) {
1263                case INIT_COPY: {
1264                    HandlerParams params = (HandlerParams) msg.obj;
1265                    int idx = mPendingInstalls.size();
1266                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1267                    // If a bind was already initiated we dont really
1268                    // need to do anything. The pending install
1269                    // will be processed later on.
1270                    if (!mBound) {
1271                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1272                                System.identityHashCode(mHandler));
1273                        // If this is the only one pending we might
1274                        // have to bind to the service again.
1275                        if (!connectToService()) {
1276                            Slog.e(TAG, "Failed to bind to media container service");
1277                            params.serviceError();
1278                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1279                                    System.identityHashCode(mHandler));
1280                            if (params.traceMethod != null) {
1281                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1282                                        params.traceCookie);
1283                            }
1284                            return;
1285                        } else {
1286                            // Once we bind to the service, the first
1287                            // pending request will be processed.
1288                            mPendingInstalls.add(idx, params);
1289                        }
1290                    } else {
1291                        mPendingInstalls.add(idx, params);
1292                        // Already bound to the service. Just make
1293                        // sure we trigger off processing the first request.
1294                        if (idx == 0) {
1295                            mHandler.sendEmptyMessage(MCS_BOUND);
1296                        }
1297                    }
1298                    break;
1299                }
1300                case MCS_BOUND: {
1301                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1302                    if (msg.obj != null) {
1303                        mContainerService = (IMediaContainerService) msg.obj;
1304                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1305                                System.identityHashCode(mHandler));
1306                    }
1307                    if (mContainerService == null) {
1308                        if (!mBound) {
1309                            // Something seriously wrong since we are not bound and we are not
1310                            // waiting for connection. Bail out.
1311                            Slog.e(TAG, "Cannot bind to media container service");
1312                            for (HandlerParams params : mPendingInstalls) {
1313                                // Indicate service bind error
1314                                params.serviceError();
1315                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1316                                        System.identityHashCode(params));
1317                                if (params.traceMethod != null) {
1318                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1319                                            params.traceMethod, params.traceCookie);
1320                                }
1321                                return;
1322                            }
1323                            mPendingInstalls.clear();
1324                        } else {
1325                            Slog.w(TAG, "Waiting to connect to media container service");
1326                        }
1327                    } else if (mPendingInstalls.size() > 0) {
1328                        HandlerParams params = mPendingInstalls.get(0);
1329                        if (params != null) {
1330                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1331                                    System.identityHashCode(params));
1332                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1333                            if (params.startCopy()) {
1334                                // We are done...  look for more work or to
1335                                // go idle.
1336                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1337                                        "Checking for more work or unbind...");
1338                                // Delete pending install
1339                                if (mPendingInstalls.size() > 0) {
1340                                    mPendingInstalls.remove(0);
1341                                }
1342                                if (mPendingInstalls.size() == 0) {
1343                                    if (mBound) {
1344                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1345                                                "Posting delayed MCS_UNBIND");
1346                                        removeMessages(MCS_UNBIND);
1347                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1348                                        // Unbind after a little delay, to avoid
1349                                        // continual thrashing.
1350                                        sendMessageDelayed(ubmsg, 10000);
1351                                    }
1352                                } else {
1353                                    // There are more pending requests in queue.
1354                                    // Just post MCS_BOUND message to trigger processing
1355                                    // of next pending install.
1356                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1357                                            "Posting MCS_BOUND for next work");
1358                                    mHandler.sendEmptyMessage(MCS_BOUND);
1359                                }
1360                            }
1361                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1362                        }
1363                    } else {
1364                        // Should never happen ideally.
1365                        Slog.w(TAG, "Empty queue");
1366                    }
1367                    break;
1368                }
1369                case MCS_RECONNECT: {
1370                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1371                    if (mPendingInstalls.size() > 0) {
1372                        if (mBound) {
1373                            disconnectService();
1374                        }
1375                        if (!connectToService()) {
1376                            Slog.e(TAG, "Failed to bind to media container service");
1377                            for (HandlerParams params : mPendingInstalls) {
1378                                // Indicate service bind error
1379                                params.serviceError();
1380                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1381                                        System.identityHashCode(params));
1382                            }
1383                            mPendingInstalls.clear();
1384                        }
1385                    }
1386                    break;
1387                }
1388                case MCS_UNBIND: {
1389                    // If there is no actual work left, then time to unbind.
1390                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1391
1392                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1393                        if (mBound) {
1394                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1395
1396                            disconnectService();
1397                        }
1398                    } else if (mPendingInstalls.size() > 0) {
1399                        // There are more pending requests in queue.
1400                        // Just post MCS_BOUND message to trigger processing
1401                        // of next pending install.
1402                        mHandler.sendEmptyMessage(MCS_BOUND);
1403                    }
1404
1405                    break;
1406                }
1407                case MCS_GIVE_UP: {
1408                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1409                    HandlerParams params = mPendingInstalls.remove(0);
1410                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1411                            System.identityHashCode(params));
1412                    break;
1413                }
1414                case SEND_PENDING_BROADCAST: {
1415                    String packages[];
1416                    ArrayList<String> components[];
1417                    int size = 0;
1418                    int uids[];
1419                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420                    synchronized (mPackages) {
1421                        if (mPendingBroadcasts == null) {
1422                            return;
1423                        }
1424                        size = mPendingBroadcasts.size();
1425                        if (size <= 0) {
1426                            // Nothing to be done. Just return
1427                            return;
1428                        }
1429                        packages = new String[size];
1430                        components = new ArrayList[size];
1431                        uids = new int[size];
1432                        int i = 0;  // filling out the above arrays
1433
1434                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1435                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1436                            Iterator<Map.Entry<String, ArrayList<String>>> it
1437                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1438                                            .entrySet().iterator();
1439                            while (it.hasNext() && i < size) {
1440                                Map.Entry<String, ArrayList<String>> ent = it.next();
1441                                packages[i] = ent.getKey();
1442                                components[i] = ent.getValue();
1443                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1444                                uids[i] = (ps != null)
1445                                        ? UserHandle.getUid(packageUserId, ps.appId)
1446                                        : -1;
1447                                i++;
1448                            }
1449                        }
1450                        size = i;
1451                        mPendingBroadcasts.clear();
1452                    }
1453                    // Send broadcasts
1454                    for (int i = 0; i < size; i++) {
1455                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1456                    }
1457                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1458                    break;
1459                }
1460                case START_CLEANING_PACKAGE: {
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1462                    final String packageName = (String)msg.obj;
1463                    final int userId = msg.arg1;
1464                    final boolean andCode = msg.arg2 != 0;
1465                    synchronized (mPackages) {
1466                        if (userId == UserHandle.USER_ALL) {
1467                            int[] users = sUserManager.getUserIds();
1468                            for (int user : users) {
1469                                mSettings.addPackageToCleanLPw(
1470                                        new PackageCleanItem(user, packageName, andCode));
1471                            }
1472                        } else {
1473                            mSettings.addPackageToCleanLPw(
1474                                    new PackageCleanItem(userId, packageName, andCode));
1475                        }
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                    startCleaningPackages();
1479                } break;
1480                case POST_INSTALL: {
1481                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1482
1483                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1484                    final boolean didRestore = (msg.arg2 != 0);
1485                    mRunningInstalls.delete(msg.arg1);
1486
1487                    if (data != null) {
1488                        InstallArgs args = data.args;
1489                        PackageInstalledInfo parentRes = data.res;
1490
1491                        final boolean grantPermissions = (args.installFlags
1492                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1493                        final boolean killApp = (args.installFlags
1494                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1495                        final String[] grantedPermissions = args.installGrantPermissions;
1496
1497                        // Handle the parent package
1498                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1499                                grantedPermissions, didRestore, args.installerPackageName,
1500                                args.observer);
1501
1502                        // Handle the child packages
1503                        final int childCount = (parentRes.addedChildPackages != null)
1504                                ? parentRes.addedChildPackages.size() : 0;
1505                        for (int i = 0; i < childCount; i++) {
1506                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1507                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1508                                    grantedPermissions, false, args.installerPackageName,
1509                                    args.observer);
1510                        }
1511
1512                        // Log tracing if needed
1513                        if (args.traceMethod != null) {
1514                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1515                                    args.traceCookie);
1516                        }
1517                    } else {
1518                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1519                    }
1520
1521                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1522                } break;
1523                case UPDATED_MEDIA_STATUS: {
1524                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1525                    boolean reportStatus = msg.arg1 == 1;
1526                    boolean doGc = msg.arg2 == 1;
1527                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1528                    if (doGc) {
1529                        // Force a gc to clear up stale containers.
1530                        Runtime.getRuntime().gc();
1531                    }
1532                    if (msg.obj != null) {
1533                        @SuppressWarnings("unchecked")
1534                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1535                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1536                        // Unload containers
1537                        unloadAllContainers(args);
1538                    }
1539                    if (reportStatus) {
1540                        try {
1541                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                    "Invoking StorageManagerService call back");
1543                            PackageHelper.getStorageManager().finishMediaUpdate();
1544                        } catch (RemoteException e) {
1545                            Log.e(TAG, "StorageManagerService not running?");
1546                        }
1547                    }
1548                } break;
1549                case WRITE_SETTINGS: {
1550                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1551                    synchronized (mPackages) {
1552                        removeMessages(WRITE_SETTINGS);
1553                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1554                        mSettings.writeLPr();
1555                        mDirtyUsers.clear();
1556                    }
1557                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1558                } break;
1559                case WRITE_PACKAGE_RESTRICTIONS: {
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1561                    synchronized (mPackages) {
1562                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1563                        for (int userId : mDirtyUsers) {
1564                            mSettings.writePackageRestrictionsLPr(userId);
1565                        }
1566                        mDirtyUsers.clear();
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                } break;
1570                case WRITE_PACKAGE_LIST: {
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1572                    synchronized (mPackages) {
1573                        removeMessages(WRITE_PACKAGE_LIST);
1574                        mSettings.writePackageListLPr(msg.arg1);
1575                    }
1576                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1577                } break;
1578                case CHECK_PENDING_VERIFICATION: {
1579                    final int verificationId = msg.arg1;
1580                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1581
1582                    if ((state != null) && !state.timeoutExtended()) {
1583                        final InstallArgs args = state.getInstallArgs();
1584                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1585
1586                        Slog.i(TAG, "Verification timed out for " + originUri);
1587                        mPendingVerification.remove(verificationId);
1588
1589                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1590
1591                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1592                            Slog.i(TAG, "Continuing with installation of " + originUri);
1593                            state.setVerifierResponse(Binder.getCallingUid(),
1594                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1595                            broadcastPackageVerified(verificationId, originUri,
1596                                    PackageManager.VERIFICATION_ALLOW,
1597                                    state.getInstallArgs().getUser());
1598                            try {
1599                                ret = args.copyApk(mContainerService, true);
1600                            } catch (RemoteException e) {
1601                                Slog.e(TAG, "Could not contact the ContainerService");
1602                            }
1603                        } else {
1604                            broadcastPackageVerified(verificationId, originUri,
1605                                    PackageManager.VERIFICATION_REJECT,
1606                                    state.getInstallArgs().getUser());
1607                        }
1608
1609                        Trace.asyncTraceEnd(
1610                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1611
1612                        processPendingInstall(args, ret);
1613                        mHandler.sendEmptyMessage(MCS_UNBIND);
1614                    }
1615                    break;
1616                }
1617                case PACKAGE_VERIFIED: {
1618                    final int verificationId = msg.arg1;
1619
1620                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1621                    if (state == null) {
1622                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1623                        break;
1624                    }
1625
1626                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1627
1628                    state.setVerifierResponse(response.callerUid, response.code);
1629
1630                    if (state.isVerificationComplete()) {
1631                        mPendingVerification.remove(verificationId);
1632
1633                        final InstallArgs args = state.getInstallArgs();
1634                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1635
1636                        int ret;
1637                        if (state.isInstallAllowed()) {
1638                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1639                            broadcastPackageVerified(verificationId, originUri,
1640                                    response.code, state.getInstallArgs().getUser());
1641                            try {
1642                                ret = args.copyApk(mContainerService, true);
1643                            } catch (RemoteException e) {
1644                                Slog.e(TAG, "Could not contact the ContainerService");
1645                            }
1646                        } else {
1647                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1648                        }
1649
1650                        Trace.asyncTraceEnd(
1651                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1652
1653                        processPendingInstall(args, ret);
1654                        mHandler.sendEmptyMessage(MCS_UNBIND);
1655                    }
1656
1657                    break;
1658                }
1659                case START_INTENT_FILTER_VERIFICATIONS: {
1660                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1661                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1662                            params.replacing, params.pkg);
1663                    break;
1664                }
1665                case INTENT_FILTER_VERIFIED: {
1666                    final int verificationId = msg.arg1;
1667
1668                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1669                            verificationId);
1670                    if (state == null) {
1671                        Slog.w(TAG, "Invalid IntentFilter verification token "
1672                                + verificationId + " received");
1673                        break;
1674                    }
1675
1676                    final int userId = state.getUserId();
1677
1678                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1679                            "Processing IntentFilter verification with token:"
1680                            + verificationId + " and userId:" + userId);
1681
1682                    final IntentFilterVerificationResponse response =
1683                            (IntentFilterVerificationResponse) msg.obj;
1684
1685                    state.setVerifierResponse(response.callerUid, response.code);
1686
1687                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1688                            "IntentFilter verification with token:" + verificationId
1689                            + " and userId:" + userId
1690                            + " is settings verifier response with response code:"
1691                            + response.code);
1692
1693                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1694                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1695                                + response.getFailedDomainsString());
1696                    }
1697
1698                    if (state.isVerificationComplete()) {
1699                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1700                    } else {
1701                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1702                                "IntentFilter verification with token:" + verificationId
1703                                + " was not said to be complete");
1704                    }
1705
1706                    break;
1707                }
1708                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1709                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1710                            mEphemeralResolverConnection,
1711                            (EphemeralRequest) msg.obj,
1712                            mEphemeralInstallerActivity,
1713                            mHandler);
1714                }
1715            }
1716        }
1717    }
1718
1719    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1720            boolean killApp, String[] grantedPermissions,
1721            boolean launchedForRestore, String installerPackage,
1722            IPackageInstallObserver2 installObserver) {
1723        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1724            // Send the removed broadcasts
1725            if (res.removedInfo != null) {
1726                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1727            }
1728
1729            // Now that we successfully installed the package, grant runtime
1730            // permissions if requested before broadcasting the install. Also
1731            // for legacy apps in permission review mode we clear the permission
1732            // review flag which is used to emulate runtime permissions for
1733            // legacy apps.
1734            if (grantPermissions) {
1735                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1736            }
1737
1738            final boolean update = res.removedInfo != null
1739                    && res.removedInfo.removedPackage != null;
1740
1741            // If this is the first time we have child packages for a disabled privileged
1742            // app that had no children, we grant requested runtime permissions to the new
1743            // children if the parent on the system image had them already granted.
1744            if (res.pkg.parentPackage != null) {
1745                synchronized (mPackages) {
1746                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1747                }
1748            }
1749
1750            synchronized (mPackages) {
1751                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1752            }
1753
1754            final String packageName = res.pkg.applicationInfo.packageName;
1755
1756            // Determine the set of users who are adding this package for
1757            // the first time vs. those who are seeing an update.
1758            int[] firstUsers = EMPTY_INT_ARRAY;
1759            int[] updateUsers = EMPTY_INT_ARRAY;
1760            if (res.origUsers == null || res.origUsers.length == 0) {
1761                firstUsers = res.newUsers;
1762            } else {
1763                for (int newUser : res.newUsers) {
1764                    boolean isNew = true;
1765                    for (int origUser : res.origUsers) {
1766                        if (origUser == newUser) {
1767                            isNew = false;
1768                            break;
1769                        }
1770                    }
1771                    if (isNew) {
1772                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1773                    } else {
1774                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1775                    }
1776                }
1777            }
1778
1779            // Send installed broadcasts if the install/update is not ephemeral
1780            // and the package is not a static shared lib.
1781            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1782                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1783
1784                // Send added for users that see the package for the first time
1785                // sendPackageAddedForNewUsers also deals with system apps
1786                int appId = UserHandle.getAppId(res.uid);
1787                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1788                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1789
1790                // Send added for users that don't see the package for the first time
1791                Bundle extras = new Bundle(1);
1792                extras.putInt(Intent.EXTRA_UID, res.uid);
1793                if (update) {
1794                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1795                }
1796                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1797                        extras, 0 /*flags*/, null /*targetPackage*/,
1798                        null /*finishedReceiver*/, updateUsers);
1799
1800                // Send replaced for users that don't see the package for the first time
1801                if (update) {
1802                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1803                            packageName, extras, 0 /*flags*/,
1804                            null /*targetPackage*/, null /*finishedReceiver*/,
1805                            updateUsers);
1806                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1807                            null /*package*/, null /*extras*/, 0 /*flags*/,
1808                            packageName /*targetPackage*/,
1809                            null /*finishedReceiver*/, updateUsers);
1810                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1811                    // First-install and we did a restore, so we're responsible for the
1812                    // first-launch broadcast.
1813                    if (DEBUG_BACKUP) {
1814                        Slog.i(TAG, "Post-restore of " + packageName
1815                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1816                    }
1817                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1818                }
1819
1820                // Send broadcast package appeared if forward locked/external for all users
1821                // treat asec-hosted packages like removable media on upgrade
1822                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1823                    if (DEBUG_INSTALL) {
1824                        Slog.i(TAG, "upgrading pkg " + res.pkg
1825                                + " is ASEC-hosted -> AVAILABLE");
1826                    }
1827                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1828                    ArrayList<String> pkgList = new ArrayList<>(1);
1829                    pkgList.add(packageName);
1830                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1831                }
1832            }
1833
1834            // Work that needs to happen on first install within each user
1835            if (firstUsers != null && firstUsers.length > 0) {
1836                synchronized (mPackages) {
1837                    for (int userId : firstUsers) {
1838                        // If this app is a browser and it's newly-installed for some
1839                        // users, clear any default-browser state in those users. The
1840                        // app's nature doesn't depend on the user, so we can just check
1841                        // its browser nature in any user and generalize.
1842                        if (packageIsBrowser(packageName, userId)) {
1843                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1844                        }
1845
1846                        // We may also need to apply pending (restored) runtime
1847                        // permission grants within these users.
1848                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1849                    }
1850                }
1851            }
1852
1853            // Log current value of "unknown sources" setting
1854            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1855                    getUnknownSourcesSettings());
1856
1857            // Force a gc to clear up things
1858            Runtime.getRuntime().gc();
1859
1860            // Remove the replaced package's older resources safely now
1861            // We delete after a gc for applications  on sdcard.
1862            if (res.removedInfo != null && res.removedInfo.args != null) {
1863                synchronized (mInstallLock) {
1864                    res.removedInfo.args.doPostDeleteLI(true);
1865                }
1866            }
1867        }
1868
1869        // If someone is watching installs - notify them
1870        if (installObserver != null) {
1871            try {
1872                Bundle extras = extrasForInstallResult(res);
1873                installObserver.onPackageInstalled(res.name, res.returnCode,
1874                        res.returnMsg, extras);
1875            } catch (RemoteException e) {
1876                Slog.i(TAG, "Observer no longer exists.");
1877            }
1878        }
1879    }
1880
1881    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1882            PackageParser.Package pkg) {
1883        if (pkg.parentPackage == null) {
1884            return;
1885        }
1886        if (pkg.requestedPermissions == null) {
1887            return;
1888        }
1889        final PackageSetting disabledSysParentPs = mSettings
1890                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1891        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1892                || !disabledSysParentPs.isPrivileged()
1893                || (disabledSysParentPs.childPackageNames != null
1894                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1895            return;
1896        }
1897        final int[] allUserIds = sUserManager.getUserIds();
1898        final int permCount = pkg.requestedPermissions.size();
1899        for (int i = 0; i < permCount; i++) {
1900            String permission = pkg.requestedPermissions.get(i);
1901            BasePermission bp = mSettings.mPermissions.get(permission);
1902            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1903                continue;
1904            }
1905            for (int userId : allUserIds) {
1906                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1907                        permission, userId)) {
1908                    grantRuntimePermission(pkg.packageName, permission, userId);
1909                }
1910            }
1911        }
1912    }
1913
1914    private StorageEventListener mStorageListener = new StorageEventListener() {
1915        @Override
1916        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1917            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1918                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1919                    final String volumeUuid = vol.getFsUuid();
1920
1921                    // Clean up any users or apps that were removed or recreated
1922                    // while this volume was missing
1923                    reconcileUsers(volumeUuid);
1924                    reconcileApps(volumeUuid);
1925
1926                    // Clean up any install sessions that expired or were
1927                    // cancelled while this volume was missing
1928                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1929
1930                    loadPrivatePackages(vol);
1931
1932                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1933                    unloadPrivatePackages(vol);
1934                }
1935            }
1936
1937            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1938                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1939                    updateExternalMediaStatus(true, false);
1940                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1941                    updateExternalMediaStatus(false, false);
1942                }
1943            }
1944        }
1945
1946        @Override
1947        public void onVolumeForgotten(String fsUuid) {
1948            if (TextUtils.isEmpty(fsUuid)) {
1949                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1950                return;
1951            }
1952
1953            // Remove any apps installed on the forgotten volume
1954            synchronized (mPackages) {
1955                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1956                for (PackageSetting ps : packages) {
1957                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1958                    deletePackageVersioned(new VersionedPackage(ps.name,
1959                            PackageManager.VERSION_CODE_HIGHEST),
1960                            new LegacyPackageDeleteObserver(null).getBinder(),
1961                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1962                    // Try very hard to release any references to this package
1963                    // so we don't risk the system server being killed due to
1964                    // open FDs
1965                    AttributeCache.instance().removePackage(ps.name);
1966                }
1967
1968                mSettings.onVolumeForgotten(fsUuid);
1969                mSettings.writeLPr();
1970            }
1971        }
1972    };
1973
1974    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1975            String[] grantedPermissions) {
1976        for (int userId : userIds) {
1977            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1978        }
1979    }
1980
1981    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1982            String[] grantedPermissions) {
1983        SettingBase sb = (SettingBase) pkg.mExtras;
1984        if (sb == null) {
1985            return;
1986        }
1987
1988        PermissionsState permissionsState = sb.getPermissionsState();
1989
1990        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1991                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1992
1993        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1994                >= Build.VERSION_CODES.M;
1995
1996        for (String permission : pkg.requestedPermissions) {
1997            final BasePermission bp;
1998            synchronized (mPackages) {
1999                bp = mSettings.mPermissions.get(permission);
2000            }
2001            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2002                    && (grantedPermissions == null
2003                           || ArrayUtils.contains(grantedPermissions, permission))) {
2004                final int flags = permissionsState.getPermissionFlags(permission, userId);
2005                if (supportsRuntimePermissions) {
2006                    // Installer cannot change immutable permissions.
2007                    if ((flags & immutableFlags) == 0) {
2008                        grantRuntimePermission(pkg.packageName, permission, userId);
2009                    }
2010                } else if (mPermissionReviewRequired) {
2011                    // In permission review mode we clear the review flag when we
2012                    // are asked to install the app with all permissions granted.
2013                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2014                        updatePermissionFlags(permission, pkg.packageName,
2015                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2016                    }
2017                }
2018            }
2019        }
2020    }
2021
2022    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2023        Bundle extras = null;
2024        switch (res.returnCode) {
2025            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2026                extras = new Bundle();
2027                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2028                        res.origPermission);
2029                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2030                        res.origPackage);
2031                break;
2032            }
2033            case PackageManager.INSTALL_SUCCEEDED: {
2034                extras = new Bundle();
2035                extras.putBoolean(Intent.EXTRA_REPLACING,
2036                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2037                break;
2038            }
2039        }
2040        return extras;
2041    }
2042
2043    void scheduleWriteSettingsLocked() {
2044        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2045            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2046        }
2047    }
2048
2049    void scheduleWritePackageListLocked(int userId) {
2050        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2051            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2052            msg.arg1 = userId;
2053            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2054        }
2055    }
2056
2057    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2058        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2059        scheduleWritePackageRestrictionsLocked(userId);
2060    }
2061
2062    void scheduleWritePackageRestrictionsLocked(int userId) {
2063        final int[] userIds = (userId == UserHandle.USER_ALL)
2064                ? sUserManager.getUserIds() : new int[]{userId};
2065        for (int nextUserId : userIds) {
2066            if (!sUserManager.exists(nextUserId)) return;
2067            mDirtyUsers.add(nextUserId);
2068            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2069                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2070            }
2071        }
2072    }
2073
2074    public static PackageManagerService main(Context context, Installer installer,
2075            boolean factoryTest, boolean onlyCore) {
2076        // Self-check for initial settings.
2077        PackageManagerServiceCompilerMapping.checkProperties();
2078
2079        PackageManagerService m = new PackageManagerService(context, installer,
2080                factoryTest, onlyCore);
2081        m.enableSystemUserPackages();
2082        ServiceManager.addService("package", m);
2083        return m;
2084    }
2085
2086    private void enableSystemUserPackages() {
2087        if (!UserManager.isSplitSystemUser()) {
2088            return;
2089        }
2090        // For system user, enable apps based on the following conditions:
2091        // - app is whitelisted or belong to one of these groups:
2092        //   -- system app which has no launcher icons
2093        //   -- system app which has INTERACT_ACROSS_USERS permission
2094        //   -- system IME app
2095        // - app is not in the blacklist
2096        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2097        Set<String> enableApps = new ArraySet<>();
2098        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2099                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2100                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2101        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2102        enableApps.addAll(wlApps);
2103        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2104                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2105        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2106        enableApps.removeAll(blApps);
2107        Log.i(TAG, "Applications installed for system user: " + enableApps);
2108        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2109                UserHandle.SYSTEM);
2110        final int allAppsSize = allAps.size();
2111        synchronized (mPackages) {
2112            for (int i = 0; i < allAppsSize; i++) {
2113                String pName = allAps.get(i);
2114                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2115                // Should not happen, but we shouldn't be failing if it does
2116                if (pkgSetting == null) {
2117                    continue;
2118                }
2119                boolean install = enableApps.contains(pName);
2120                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2121                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2122                            + " for system user");
2123                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2124                }
2125            }
2126        }
2127    }
2128
2129    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2130        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2131                Context.DISPLAY_SERVICE);
2132        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2133    }
2134
2135    /**
2136     * Requests that files preopted on a secondary system partition be copied to the data partition
2137     * if possible.  Note that the actual copying of the files is accomplished by init for security
2138     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2139     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2140     */
2141    private static void requestCopyPreoptedFiles() {
2142        final int WAIT_TIME_MS = 100;
2143        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2144        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2145            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2146            // We will wait for up to 100 seconds.
2147            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2148            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2149                try {
2150                    Thread.sleep(WAIT_TIME_MS);
2151                } catch (InterruptedException e) {
2152                    // Do nothing
2153                }
2154                if (SystemClock.uptimeMillis() > timeEnd) {
2155                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2156                    Slog.wtf(TAG, "cppreopt did not finish!");
2157                    break;
2158                }
2159            }
2160        }
2161    }
2162
2163    public PackageManagerService(Context context, Installer installer,
2164            boolean factoryTest, boolean onlyCore) {
2165        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2166        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2167                SystemClock.uptimeMillis());
2168
2169        if (mSdkVersion <= 0) {
2170            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2171        }
2172
2173        mContext = context;
2174
2175        mPermissionReviewRequired = context.getResources().getBoolean(
2176                R.bool.config_permissionReviewRequired);
2177
2178        mFactoryTest = factoryTest;
2179        mOnlyCore = onlyCore;
2180        mMetrics = new DisplayMetrics();
2181        mSettings = new Settings(mPackages);
2182        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2183                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2184        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2185                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2186        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2187                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2188        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2189                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2190        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2191                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2192        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2193                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2194
2195        String separateProcesses = SystemProperties.get("debug.separate_processes");
2196        if (separateProcesses != null && separateProcesses.length() > 0) {
2197            if ("*".equals(separateProcesses)) {
2198                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2199                mSeparateProcesses = null;
2200                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2201            } else {
2202                mDefParseFlags = 0;
2203                mSeparateProcesses = separateProcesses.split(",");
2204                Slog.w(TAG, "Running with debug.separate_processes: "
2205                        + separateProcesses);
2206            }
2207        } else {
2208            mDefParseFlags = 0;
2209            mSeparateProcesses = null;
2210        }
2211
2212        mInstaller = installer;
2213        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2214                "*dexopt*");
2215        mDexManager = new DexManager();
2216        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2217
2218        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2219                FgThread.get().getLooper());
2220
2221        getDefaultDisplayMetrics(context, mMetrics);
2222
2223        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2224        SystemConfig systemConfig = SystemConfig.getInstance();
2225        mGlobalGids = systemConfig.getGlobalGids();
2226        mSystemPermissions = systemConfig.getSystemPermissions();
2227        mAvailableFeatures = systemConfig.getAvailableFeatures();
2228        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2229
2230        mProtectedPackages = new ProtectedPackages(mContext);
2231
2232        synchronized (mInstallLock) {
2233        // writer
2234        synchronized (mPackages) {
2235            mHandlerThread = new ServiceThread(TAG,
2236                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2237            mHandlerThread.start();
2238            mHandler = new PackageHandler(mHandlerThread.getLooper());
2239            mProcessLoggingHandler = new ProcessLoggingHandler();
2240            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2241
2242            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2243            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2244
2245            File dataDir = Environment.getDataDirectory();
2246            mAppInstallDir = new File(dataDir, "app");
2247            mAppLib32InstallDir = new File(dataDir, "app-lib");
2248            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2249            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2250            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2251
2252            sUserManager = new UserManagerService(context, this, mPackages);
2253
2254            // Propagate permission configuration in to package manager.
2255            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2256                    = systemConfig.getPermissions();
2257            for (int i=0; i<permConfig.size(); i++) {
2258                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2259                BasePermission bp = mSettings.mPermissions.get(perm.name);
2260                if (bp == null) {
2261                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2262                    mSettings.mPermissions.put(perm.name, bp);
2263                }
2264                if (perm.gids != null) {
2265                    bp.setGids(perm.gids, perm.perUser);
2266                }
2267            }
2268
2269            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2270            final int builtInLibCount = libConfig.size();
2271            for (int i = 0; i < builtInLibCount; i++) {
2272                String name = libConfig.keyAt(i);
2273                String path = libConfig.valueAt(i);
2274                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2275                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2276            }
2277
2278            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2279
2280            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2281            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2283
2284            // Clean up orphaned packages for which the code path doesn't exist
2285            // and they are an update to a system app - caused by bug/32321269
2286            final int packageSettingCount = mSettings.mPackages.size();
2287            for (int i = packageSettingCount - 1; i >= 0; i--) {
2288                PackageSetting ps = mSettings.mPackages.valueAt(i);
2289                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2290                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2291                    mSettings.mPackages.removeAt(i);
2292                    mSettings.enableSystemPackageLPw(ps.name);
2293                }
2294            }
2295
2296            if (mFirstBoot) {
2297                requestCopyPreoptedFiles();
2298            }
2299
2300            String customResolverActivity = Resources.getSystem().getString(
2301                    R.string.config_customResolverActivity);
2302            if (TextUtils.isEmpty(customResolverActivity)) {
2303                customResolverActivity = null;
2304            } else {
2305                mCustomResolverComponentName = ComponentName.unflattenFromString(
2306                        customResolverActivity);
2307            }
2308
2309            long startTime = SystemClock.uptimeMillis();
2310
2311            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2312                    startTime);
2313
2314            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2315            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2316
2317            if (bootClassPath == null) {
2318                Slog.w(TAG, "No BOOTCLASSPATH found!");
2319            }
2320
2321            if (systemServerClassPath == null) {
2322                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2323            }
2324
2325            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2326            final String[] dexCodeInstructionSets =
2327                    getDexCodeInstructionSets(
2328                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2329
2330            /**
2331             * Ensure all external libraries have had dexopt run on them.
2332             */
2333            if (mSharedLibraries.size() > 0) {
2334                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2335                // NOTE: For now, we're compiling these system "shared libraries"
2336                // (and framework jars) into all available architectures. It's possible
2337                // to compile them only when we come across an app that uses them (there's
2338                // already logic for that in scanPackageLI) but that adds some complexity.
2339                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2340                    final int libCount = mSharedLibraries.size();
2341                    for (int i = 0; i < libCount; i++) {
2342                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2343                        final int versionCount = versionedLib.size();
2344                        for (int j = 0; j < versionCount; j++) {
2345                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2346                            final String libPath = libEntry.path != null
2347                                    ? libEntry.path : libEntry.apk;
2348                            if (libPath == null) {
2349                                continue;
2350                            }
2351                            try {
2352                                // Shared libraries do not have profiles so we perform a full
2353                                // AOT compilation (if needed).
2354                                int dexoptNeeded = DexFile.getDexOptNeeded(
2355                                        libPath, dexCodeInstructionSet,
2356                                        getCompilerFilterForReason(REASON_SHARED_APK),
2357                                        false /* newProfile */);
2358                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2359                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2360                                            dexCodeInstructionSet, dexoptNeeded, null,
2361                                            DEXOPT_PUBLIC,
2362                                            getCompilerFilterForReason(REASON_SHARED_APK),
2363                                            StorageManager.UUID_PRIVATE_INTERNAL,
2364                                            SKIP_SHARED_LIBRARY_CHECK);
2365                                }
2366                            } catch (FileNotFoundException e) {
2367                                Slog.w(TAG, "Library not found: " + libPath);
2368                            } catch (IOException | InstallerException e) {
2369                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2370                                        + e.getMessage());
2371                            }
2372                        }
2373                    }
2374                }
2375                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2376            }
2377
2378            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2379
2380            final VersionInfo ver = mSettings.getInternalVersion();
2381            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2382
2383            // when upgrading from pre-M, promote system app permissions from install to runtime
2384            mPromoteSystemApps =
2385                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2386
2387            // When upgrading from pre-N, we need to handle package extraction like first boot,
2388            // as there is no profiling data available.
2389            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2390
2391            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2392
2393            // save off the names of pre-existing system packages prior to scanning; we don't
2394            // want to automatically grant runtime permissions for new system apps
2395            if (mPromoteSystemApps) {
2396                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2397                while (pkgSettingIter.hasNext()) {
2398                    PackageSetting ps = pkgSettingIter.next();
2399                    if (isSystemApp(ps)) {
2400                        mExistingSystemPackages.add(ps.name);
2401                    }
2402                }
2403            }
2404
2405            mCacheDir = preparePackageParserCache(mIsUpgrade);
2406
2407            // Set flag to monitor and not change apk file paths when
2408            // scanning install directories.
2409            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2410
2411            if (mIsUpgrade || mFirstBoot) {
2412                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2413            }
2414
2415            // Collect vendor overlay packages. (Do this before scanning any apps.)
2416            // For security and version matching reason, only consider
2417            // overlay packages if they reside in the right directory.
2418            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2419            if (overlayThemeDir.isEmpty()) {
2420                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2421            }
2422            if (!overlayThemeDir.isEmpty()) {
2423                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2424                        | PackageParser.PARSE_IS_SYSTEM
2425                        | PackageParser.PARSE_IS_SYSTEM_DIR
2426                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2427            }
2428            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2429                    | PackageParser.PARSE_IS_SYSTEM
2430                    | PackageParser.PARSE_IS_SYSTEM_DIR
2431                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2432
2433            // Find base frameworks (resource packages without code).
2434            scanDirTracedLI(frameworkDir, mDefParseFlags
2435                    | PackageParser.PARSE_IS_SYSTEM
2436                    | PackageParser.PARSE_IS_SYSTEM_DIR
2437                    | PackageParser.PARSE_IS_PRIVILEGED,
2438                    scanFlags | SCAN_NO_DEX, 0);
2439
2440            // Collected privileged system packages.
2441            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2442            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2443                    | PackageParser.PARSE_IS_SYSTEM
2444                    | PackageParser.PARSE_IS_SYSTEM_DIR
2445                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2446
2447            // Collect ordinary system packages.
2448            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2449            scanDirTracedLI(systemAppDir, mDefParseFlags
2450                    | PackageParser.PARSE_IS_SYSTEM
2451                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2452
2453            // Collect all vendor packages.
2454            File vendorAppDir = new File("/vendor/app");
2455            try {
2456                vendorAppDir = vendorAppDir.getCanonicalFile();
2457            } catch (IOException e) {
2458                // failed to look up canonical path, continue with original one
2459            }
2460            scanDirTracedLI(vendorAppDir, mDefParseFlags
2461                    | PackageParser.PARSE_IS_SYSTEM
2462                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2463
2464            // Collect all OEM packages.
2465            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2466            scanDirTracedLI(oemAppDir, mDefParseFlags
2467                    | PackageParser.PARSE_IS_SYSTEM
2468                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2469
2470            // Prune any system packages that no longer exist.
2471            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2472            if (!mOnlyCore) {
2473                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2474                while (psit.hasNext()) {
2475                    PackageSetting ps = psit.next();
2476
2477                    /*
2478                     * If this is not a system app, it can't be a
2479                     * disable system app.
2480                     */
2481                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2482                        continue;
2483                    }
2484
2485                    /*
2486                     * If the package is scanned, it's not erased.
2487                     */
2488                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2489                    if (scannedPkg != null) {
2490                        /*
2491                         * If the system app is both scanned and in the
2492                         * disabled packages list, then it must have been
2493                         * added via OTA. Remove it from the currently
2494                         * scanned package so the previously user-installed
2495                         * application can be scanned.
2496                         */
2497                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2498                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2499                                    + ps.name + "; removing system app.  Last known codePath="
2500                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2501                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2502                                    + scannedPkg.mVersionCode);
2503                            removePackageLI(scannedPkg, true);
2504                            mExpectingBetter.put(ps.name, ps.codePath);
2505                        }
2506
2507                        continue;
2508                    }
2509
2510                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2511                        psit.remove();
2512                        logCriticalInfo(Log.WARN, "System package " + ps.name
2513                                + " no longer exists; it's data will be wiped");
2514                        // Actual deletion of code and data will be handled by later
2515                        // reconciliation step
2516                    } else {
2517                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2518                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2519                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2520                        }
2521                    }
2522                }
2523            }
2524
2525            //look for any incomplete package installations
2526            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2527            for (int i = 0; i < deletePkgsList.size(); i++) {
2528                // Actual deletion of code and data will be handled by later
2529                // reconciliation step
2530                final String packageName = deletePkgsList.get(i).name;
2531                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2532                synchronized (mPackages) {
2533                    mSettings.removePackageLPw(packageName);
2534                }
2535            }
2536
2537            //delete tmp files
2538            deleteTempPackageFiles();
2539
2540            // Remove any shared userIDs that have no associated packages
2541            mSettings.pruneSharedUsersLPw();
2542
2543            if (!mOnlyCore) {
2544                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2545                        SystemClock.uptimeMillis());
2546                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2547
2548                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2549                        | PackageParser.PARSE_FORWARD_LOCK,
2550                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2551
2552                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2553                        | PackageParser.PARSE_IS_EPHEMERAL,
2554                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2555
2556                /**
2557                 * Remove disable package settings for any updated system
2558                 * apps that were removed via an OTA. If they're not a
2559                 * previously-updated app, remove them completely.
2560                 * Otherwise, just revoke their system-level permissions.
2561                 */
2562                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2563                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2564                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2565
2566                    String msg;
2567                    if (deletedPkg == null) {
2568                        msg = "Updated system package " + deletedAppName
2569                                + " no longer exists; it's data will be wiped";
2570                        // Actual deletion of code and data will be handled by later
2571                        // reconciliation step
2572                    } else {
2573                        msg = "Updated system app + " + deletedAppName
2574                                + " no longer present; removing system privileges for "
2575                                + deletedAppName;
2576
2577                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2578
2579                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2580                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2581                    }
2582                    logCriticalInfo(Log.WARN, msg);
2583                }
2584
2585                /**
2586                 * Make sure all system apps that we expected to appear on
2587                 * the userdata partition actually showed up. If they never
2588                 * appeared, crawl back and revive the system version.
2589                 */
2590                for (int i = 0; i < mExpectingBetter.size(); i++) {
2591                    final String packageName = mExpectingBetter.keyAt(i);
2592                    if (!mPackages.containsKey(packageName)) {
2593                        final File scanFile = mExpectingBetter.valueAt(i);
2594
2595                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2596                                + " but never showed up; reverting to system");
2597
2598                        int reparseFlags = mDefParseFlags;
2599                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2600                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2601                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2602                                    | PackageParser.PARSE_IS_PRIVILEGED;
2603                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2604                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2605                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2606                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2607                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2608                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2609                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2610                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2611                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2612                        } else {
2613                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2614                            continue;
2615                        }
2616
2617                        mSettings.enableSystemPackageLPw(packageName);
2618
2619                        try {
2620                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2621                        } catch (PackageManagerException e) {
2622                            Slog.e(TAG, "Failed to parse original system package: "
2623                                    + e.getMessage());
2624                        }
2625                    }
2626                }
2627            }
2628            mExpectingBetter.clear();
2629
2630            // Resolve the storage manager.
2631            mStorageManagerPackage = getStorageManagerPackageName();
2632
2633            // Resolve protected action filters. Only the setup wizard is allowed to
2634            // have a high priority filter for these actions.
2635            mSetupWizardPackage = getSetupWizardPackageName();
2636            if (mProtectedFilters.size() > 0) {
2637                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2638                    Slog.i(TAG, "No setup wizard;"
2639                        + " All protected intents capped to priority 0");
2640                }
2641                for (ActivityIntentInfo filter : mProtectedFilters) {
2642                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2643                        if (DEBUG_FILTERS) {
2644                            Slog.i(TAG, "Found setup wizard;"
2645                                + " allow priority " + filter.getPriority() + ";"
2646                                + " package: " + filter.activity.info.packageName
2647                                + " activity: " + filter.activity.className
2648                                + " priority: " + filter.getPriority());
2649                        }
2650                        // skip setup wizard; allow it to keep the high priority filter
2651                        continue;
2652                    }
2653                    Slog.w(TAG, "Protected action; cap priority to 0;"
2654                            + " package: " + filter.activity.info.packageName
2655                            + " activity: " + filter.activity.className
2656                            + " origPrio: " + filter.getPriority());
2657                    filter.setPriority(0);
2658                }
2659            }
2660            mDeferProtectedFilters = false;
2661            mProtectedFilters.clear();
2662
2663            // Now that we know all of the shared libraries, update all clients to have
2664            // the correct library paths.
2665            updateAllSharedLibrariesLPw(null);
2666
2667            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2668                // NOTE: We ignore potential failures here during a system scan (like
2669                // the rest of the commands above) because there's precious little we
2670                // can do about it. A settings error is reported, though.
2671                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2672            }
2673
2674            // Now that we know all the packages we are keeping,
2675            // read and update their last usage times.
2676            mPackageUsage.read(mPackages);
2677            mCompilerStats.read();
2678
2679            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2680                    SystemClock.uptimeMillis());
2681            Slog.i(TAG, "Time to scan packages: "
2682                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2683                    + " seconds");
2684
2685            // If the platform SDK has changed since the last time we booted,
2686            // we need to re-grant app permission to catch any new ones that
2687            // appear.  This is really a hack, and means that apps can in some
2688            // cases get permissions that the user didn't initially explicitly
2689            // allow...  it would be nice to have some better way to handle
2690            // this situation.
2691            int updateFlags = UPDATE_PERMISSIONS_ALL;
2692            if (ver.sdkVersion != mSdkVersion) {
2693                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2694                        + mSdkVersion + "; regranting permissions for internal storage");
2695                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2696            }
2697            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2698            ver.sdkVersion = mSdkVersion;
2699
2700            // If this is the first boot or an update from pre-M, and it is a normal
2701            // boot, then we need to initialize the default preferred apps across
2702            // all defined users.
2703            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2704                for (UserInfo user : sUserManager.getUsers(true)) {
2705                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2706                    applyFactoryDefaultBrowserLPw(user.id);
2707                    primeDomainVerificationsLPw(user.id);
2708                }
2709            }
2710
2711            // Prepare storage for system user really early during boot,
2712            // since core system apps like SettingsProvider and SystemUI
2713            // can't wait for user to start
2714            final int storageFlags;
2715            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2716                storageFlags = StorageManager.FLAG_STORAGE_DE;
2717            } else {
2718                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2719            }
2720            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2721                    storageFlags, true /* migrateAppData */);
2722
2723            // If this is first boot after an OTA, and a normal boot, then
2724            // we need to clear code cache directories.
2725            // Note that we do *not* clear the application profiles. These remain valid
2726            // across OTAs and are used to drive profile verification (post OTA) and
2727            // profile compilation (without waiting to collect a fresh set of profiles).
2728            if (mIsUpgrade && !onlyCore) {
2729                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2730                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2731                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2732                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2733                        // No apps are running this early, so no need to freeze
2734                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2735                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2736                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2737                    }
2738                }
2739                ver.fingerprint = Build.FINGERPRINT;
2740            }
2741
2742            checkDefaultBrowser();
2743
2744            // clear only after permissions and other defaults have been updated
2745            mExistingSystemPackages.clear();
2746            mPromoteSystemApps = false;
2747
2748            // All the changes are done during package scanning.
2749            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2750
2751            // can downgrade to reader
2752            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2753            mSettings.writeLPr();
2754            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2755
2756            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2757            // early on (before the package manager declares itself as early) because other
2758            // components in the system server might ask for package contexts for these apps.
2759            //
2760            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2761            // (i.e, that the data partition is unavailable).
2762            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2763                long start = System.nanoTime();
2764                List<PackageParser.Package> coreApps = new ArrayList<>();
2765                for (PackageParser.Package pkg : mPackages.values()) {
2766                    if (pkg.coreApp) {
2767                        coreApps.add(pkg);
2768                    }
2769                }
2770
2771                int[] stats = performDexOptUpgrade(coreApps, false,
2772                        getCompilerFilterForReason(REASON_CORE_APP));
2773
2774                final int elapsedTimeSeconds =
2775                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2776                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2777
2778                if (DEBUG_DEXOPT) {
2779                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2780                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2781                }
2782
2783
2784                // TODO: Should we log these stats to tron too ?
2785                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2786                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2787                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2788                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2789            }
2790
2791            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2792                    SystemClock.uptimeMillis());
2793
2794            if (!mOnlyCore) {
2795                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2796                mRequiredInstallerPackage = getRequiredInstallerLPr();
2797                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2798                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2799                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2800                        mIntentFilterVerifierComponent);
2801                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2802                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2803                        SharedLibraryInfo.VERSION_UNDEFINED);
2804                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2805                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2806                        SharedLibraryInfo.VERSION_UNDEFINED);
2807            } else {
2808                mRequiredVerifierPackage = null;
2809                mRequiredInstallerPackage = null;
2810                mRequiredUninstallerPackage = null;
2811                mIntentFilterVerifierComponent = null;
2812                mIntentFilterVerifier = null;
2813                mServicesSystemSharedLibraryPackageName = null;
2814                mSharedSystemSharedLibraryPackageName = null;
2815            }
2816
2817            mInstallerService = new PackageInstallerService(context, this);
2818
2819            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2820            if (ephemeralResolverComponent != null) {
2821                if (DEBUG_EPHEMERAL) {
2822                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2823                }
2824                mEphemeralResolverConnection =
2825                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2826            } else {
2827                mEphemeralResolverConnection = null;
2828            }
2829            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2830            if (mEphemeralInstallerComponent != null) {
2831                if (DEBUG_EPHEMERAL) {
2832                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2833                }
2834                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2835            }
2836
2837            // Read and update the usage of dex files.
2838            // Do this at the end of PM init so that all the packages have their
2839            // data directory reconciled.
2840            // At this point we know the code paths of the packages, so we can validate
2841            // the disk file and build the internal cache.
2842            // The usage file is expected to be small so loading and verifying it
2843            // should take a fairly small time compare to the other activities (e.g. package
2844            // scanning).
2845            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2846            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2847            for (int userId : currentUserIds) {
2848                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2849            }
2850            mDexManager.load(userPackages);
2851        } // synchronized (mPackages)
2852        } // synchronized (mInstallLock)
2853
2854        // Now after opening every single application zip, make sure they
2855        // are all flushed.  Not really needed, but keeps things nice and
2856        // tidy.
2857        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2858        Runtime.getRuntime().gc();
2859        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2860
2861        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2862        FallbackCategoryProvider.loadFallbacks();
2863        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2864
2865        // The initial scanning above does many calls into installd while
2866        // holding the mPackages lock, but we're mostly interested in yelling
2867        // once we have a booted system.
2868        mInstaller.setWarnIfHeld(mPackages);
2869
2870        // Expose private service for system components to use.
2871        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2872        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2873    }
2874
2875    private static File preparePackageParserCache(boolean isUpgrade) {
2876        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2877            return null;
2878        }
2879
2880        // Disable package parsing on eng builds to allow for faster incremental development.
2881        if ("eng".equals(Build.TYPE)) {
2882            return null;
2883        }
2884
2885        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2886            Slog.i(TAG, "Disabling package parser cache due to system property.");
2887            return null;
2888        }
2889
2890        // The base directory for the package parser cache lives under /data/system/.
2891        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2892                "package_cache");
2893        if (cacheBaseDir == null) {
2894            return null;
2895        }
2896
2897        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2898        // This also serves to "GC" unused entries when the package cache version changes (which
2899        // can only happen during upgrades).
2900        if (isUpgrade) {
2901            FileUtils.deleteContents(cacheBaseDir);
2902        }
2903
2904
2905        // Return the versioned package cache directory. This is something like
2906        // "/data/system/package_cache/1"
2907        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2908
2909        // The following is a workaround to aid development on non-numbered userdebug
2910        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2911        // the system partition is newer.
2912        //
2913        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2914        // that starts with "eng." to signify that this is an engineering build and not
2915        // destined for release.
2916        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2917            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2918
2919            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2920            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2921            // in general and should not be used for production changes. In this specific case,
2922            // we know that they will work.
2923            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2924            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2925                FileUtils.deleteContents(cacheBaseDir);
2926                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2927            }
2928        }
2929
2930        return cacheDir;
2931    }
2932
2933    @Override
2934    public boolean isFirstBoot() {
2935        return mFirstBoot;
2936    }
2937
2938    @Override
2939    public boolean isOnlyCoreApps() {
2940        return mOnlyCore;
2941    }
2942
2943    @Override
2944    public boolean isUpgrade() {
2945        return mIsUpgrade;
2946    }
2947
2948    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2949        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2950
2951        final List<ResolveInfo> matches = queryIntentReceiversInternal(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            return matches.get(0).getComponentInfo().packageName;
2956        } else if (matches.size() == 0) {
2957            Log.e(TAG, "There should probably be a verifier, but, none were found");
2958            return null;
2959        }
2960        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2961    }
2962
2963    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2964        synchronized (mPackages) {
2965            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2966            if (libraryEntry == null) {
2967                throw new IllegalStateException("Missing required shared library:" + name);
2968            }
2969            return libraryEntry.apk;
2970        }
2971    }
2972
2973    private @NonNull String getRequiredInstallerLPr() {
2974        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2975        intent.addCategory(Intent.CATEGORY_DEFAULT);
2976        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2977
2978        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2979                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2980                UserHandle.USER_SYSTEM);
2981        if (matches.size() == 1) {
2982            ResolveInfo resolveInfo = matches.get(0);
2983            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2984                throw new RuntimeException("The installer must be a privileged app");
2985            }
2986            return matches.get(0).getComponentInfo().packageName;
2987        } else {
2988            throw new RuntimeException("There must be exactly one installer; found " + matches);
2989        }
2990    }
2991
2992    private @NonNull String getRequiredUninstallerLPr() {
2993        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2994        intent.addCategory(Intent.CATEGORY_DEFAULT);
2995        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2996
2997        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2998                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2999                UserHandle.USER_SYSTEM);
3000        if (resolveInfo == null ||
3001                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3002            throw new RuntimeException("There must be exactly one uninstaller; found "
3003                    + resolveInfo);
3004        }
3005        return resolveInfo.getComponentInfo().packageName;
3006    }
3007
3008    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3009        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3010
3011        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3012                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3013                UserHandle.USER_SYSTEM);
3014        ResolveInfo best = null;
3015        final int N = matches.size();
3016        for (int i = 0; i < N; i++) {
3017            final ResolveInfo cur = matches.get(i);
3018            final String packageName = cur.getComponentInfo().packageName;
3019            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3020                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3021                continue;
3022            }
3023
3024            if (best == null || cur.priority > best.priority) {
3025                best = cur;
3026            }
3027        }
3028
3029        if (best != null) {
3030            return best.getComponentInfo().getComponentName();
3031        } else {
3032            throw new RuntimeException("There must be at least one intent filter verifier");
3033        }
3034    }
3035
3036    private @Nullable ComponentName getEphemeralResolverLPr() {
3037        final String[] packageArray =
3038                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3039        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3040            if (DEBUG_EPHEMERAL) {
3041                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3042            }
3043            return null;
3044        }
3045
3046        final int resolveFlags =
3047                MATCH_DIRECT_BOOT_AWARE
3048                | MATCH_DIRECT_BOOT_UNAWARE
3049                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3050        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3051        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3052                resolveFlags, UserHandle.USER_SYSTEM);
3053
3054        final int N = resolvers.size();
3055        if (N == 0) {
3056            if (DEBUG_EPHEMERAL) {
3057                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3058            }
3059            return null;
3060        }
3061
3062        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3063        for (int i = 0; i < N; i++) {
3064            final ResolveInfo info = resolvers.get(i);
3065
3066            if (info.serviceInfo == null) {
3067                continue;
3068            }
3069
3070            final String packageName = info.serviceInfo.packageName;
3071            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3072                if (DEBUG_EPHEMERAL) {
3073                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3074                            + " pkg: " + packageName + ", info:" + info);
3075                }
3076                continue;
3077            }
3078
3079            if (DEBUG_EPHEMERAL) {
3080                Slog.v(TAG, "Ephemeral resolver found;"
3081                        + " pkg: " + packageName + ", info:" + info);
3082            }
3083            return new ComponentName(packageName, info.serviceInfo.name);
3084        }
3085        if (DEBUG_EPHEMERAL) {
3086            Slog.v(TAG, "Ephemeral resolver NOT found");
3087        }
3088        return null;
3089    }
3090
3091    private @Nullable ComponentName getEphemeralInstallerLPr() {
3092        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3093        intent.addCategory(Intent.CATEGORY_DEFAULT);
3094        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3095
3096        final int resolveFlags =
3097                MATCH_DIRECT_BOOT_AWARE
3098                | MATCH_DIRECT_BOOT_UNAWARE
3099                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3100        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3101                resolveFlags, UserHandle.USER_SYSTEM);
3102        Iterator<ResolveInfo> iter = matches.iterator();
3103        while (iter.hasNext()) {
3104            final ResolveInfo rInfo = iter.next();
3105            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3106            if (ps != null) {
3107                final PermissionsState permissionsState = ps.getPermissionsState();
3108                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3109                    continue;
3110                }
3111            }
3112            iter.remove();
3113        }
3114        if (matches.size() == 0) {
3115            return null;
3116        } else if (matches.size() == 1) {
3117            return matches.get(0).getComponentInfo().getComponentName();
3118        } else {
3119            throw new RuntimeException(
3120                    "There must be at most one ephemeral installer; found " + matches);
3121        }
3122    }
3123
3124    private void primeDomainVerificationsLPw(int userId) {
3125        if (DEBUG_DOMAIN_VERIFICATION) {
3126            Slog.d(TAG, "Priming domain verifications in user " + userId);
3127        }
3128
3129        SystemConfig systemConfig = SystemConfig.getInstance();
3130        ArraySet<String> packages = systemConfig.getLinkedApps();
3131
3132        for (String packageName : packages) {
3133            PackageParser.Package pkg = mPackages.get(packageName);
3134            if (pkg != null) {
3135                if (!pkg.isSystemApp()) {
3136                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3137                    continue;
3138                }
3139
3140                ArraySet<String> domains = null;
3141                for (PackageParser.Activity a : pkg.activities) {
3142                    for (ActivityIntentInfo filter : a.intents) {
3143                        if (hasValidDomains(filter)) {
3144                            if (domains == null) {
3145                                domains = new ArraySet<String>();
3146                            }
3147                            domains.addAll(filter.getHostsList());
3148                        }
3149                    }
3150                }
3151
3152                if (domains != null && domains.size() > 0) {
3153                    if (DEBUG_DOMAIN_VERIFICATION) {
3154                        Slog.v(TAG, "      + " + packageName);
3155                    }
3156                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3157                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3158                    // and then 'always' in the per-user state actually used for intent resolution.
3159                    final IntentFilterVerificationInfo ivi;
3160                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3162                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3163                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3164                } else {
3165                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3166                            + "' does not handle web links");
3167                }
3168            } else {
3169                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3170            }
3171        }
3172
3173        scheduleWritePackageRestrictionsLocked(userId);
3174        scheduleWriteSettingsLocked();
3175    }
3176
3177    private void applyFactoryDefaultBrowserLPw(int userId) {
3178        // The default browser app's package name is stored in a string resource,
3179        // with a product-specific overlay used for vendor customization.
3180        String browserPkg = mContext.getResources().getString(
3181                com.android.internal.R.string.default_browser);
3182        if (!TextUtils.isEmpty(browserPkg)) {
3183            // non-empty string => required to be a known package
3184            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3185            if (ps == null) {
3186                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3187                browserPkg = null;
3188            } else {
3189                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3190            }
3191        }
3192
3193        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3194        // default.  If there's more than one, just leave everything alone.
3195        if (browserPkg == null) {
3196            calculateDefaultBrowserLPw(userId);
3197        }
3198    }
3199
3200    private void calculateDefaultBrowserLPw(int userId) {
3201        List<String> allBrowsers = resolveAllBrowserApps(userId);
3202        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3203        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3204    }
3205
3206    private List<String> resolveAllBrowserApps(int userId) {
3207        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3208        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3209                PackageManager.MATCH_ALL, userId);
3210
3211        final int count = list.size();
3212        List<String> result = new ArrayList<String>(count);
3213        for (int i=0; i<count; i++) {
3214            ResolveInfo info = list.get(i);
3215            if (info.activityInfo == null
3216                    || !info.handleAllWebDataURI
3217                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3218                    || result.contains(info.activityInfo.packageName)) {
3219                continue;
3220            }
3221            result.add(info.activityInfo.packageName);
3222        }
3223
3224        return result;
3225    }
3226
3227    private boolean packageIsBrowser(String packageName, int userId) {
3228        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3229                PackageManager.MATCH_ALL, userId);
3230        final int N = list.size();
3231        for (int i = 0; i < N; i++) {
3232            ResolveInfo info = list.get(i);
3233            if (packageName.equals(info.activityInfo.packageName)) {
3234                return true;
3235            }
3236        }
3237        return false;
3238    }
3239
3240    private void checkDefaultBrowser() {
3241        final int myUserId = UserHandle.myUserId();
3242        final String packageName = getDefaultBrowserPackageName(myUserId);
3243        if (packageName != null) {
3244            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3245            if (info == null) {
3246                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3247                synchronized (mPackages) {
3248                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3249                }
3250            }
3251        }
3252    }
3253
3254    @Override
3255    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3256            throws RemoteException {
3257        try {
3258            return super.onTransact(code, data, reply, flags);
3259        } catch (RuntimeException e) {
3260            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3261                Slog.wtf(TAG, "Package Manager Crash", e);
3262            }
3263            throw e;
3264        }
3265    }
3266
3267    static int[] appendInts(int[] cur, int[] add) {
3268        if (add == null) return cur;
3269        if (cur == null) return add;
3270        final int N = add.length;
3271        for (int i=0; i<N; i++) {
3272            cur = appendInt(cur, add[i]);
3273        }
3274        return cur;
3275    }
3276
3277    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3278        if (!sUserManager.exists(userId)) return null;
3279        if (ps == null) {
3280            return null;
3281        }
3282        final PackageParser.Package p = ps.pkg;
3283        if (p == null) {
3284            return null;
3285        }
3286        // Filter out ephemeral app metadata:
3287        //   * The system/shell/root can see metadata for any app
3288        //   * An installed app can see metadata for 1) other installed apps
3289        //     and 2) ephemeral apps that have explicitly interacted with it
3290        //   * Ephemeral apps can only see their own metadata
3291        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3292        if (callingAppId != Process.SYSTEM_UID
3293                && callingAppId != Process.SHELL_UID
3294                && callingAppId != Process.ROOT_UID) {
3295            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3296            if (ephemeralPackageName != null) {
3297                // ephemeral apps can only get information on themselves
3298                if (!ephemeralPackageName.equals(p.packageName)) {
3299                    return null;
3300                }
3301            } else {
3302                if (p.applicationInfo.isEphemeralApp()) {
3303                    // only get access to the ephemeral app if we've been granted access
3304                    if (!mEphemeralApplicationRegistry.isEphemeralAccessGranted(
3305                            userId, callingAppId, ps.appId)) {
3306                        return null;
3307                    }
3308                }
3309            }
3310        }
3311
3312        final PermissionsState permissionsState = ps.getPermissionsState();
3313
3314        // Compute GIDs only if requested
3315        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3316                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3317        // Compute granted permissions only if package has requested permissions
3318        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3319                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3320        final PackageUserState state = ps.readUserState(userId);
3321
3322        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3323                && ps.isSystem()) {
3324            flags |= MATCH_ANY_USER;
3325        }
3326
3327        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3328                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3329
3330        if (packageInfo == null) {
3331            return null;
3332        }
3333
3334        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3335                resolveExternalPackageNameLPr(p);
3336
3337        return packageInfo;
3338    }
3339
3340    @Override
3341    public void checkPackageStartable(String packageName, int userId) {
3342        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3343
3344        synchronized (mPackages) {
3345            final PackageSetting ps = mSettings.mPackages.get(packageName);
3346            if (ps == null) {
3347                throw new SecurityException("Package " + packageName + " was not found!");
3348            }
3349
3350            if (!ps.getInstalled(userId)) {
3351                throw new SecurityException(
3352                        "Package " + packageName + " was not installed for user " + userId + "!");
3353            }
3354
3355            if (mSafeMode && !ps.isSystem()) {
3356                throw new SecurityException("Package " + packageName + " not a system app!");
3357            }
3358
3359            if (mFrozenPackages.contains(packageName)) {
3360                throw new SecurityException("Package " + packageName + " is currently frozen!");
3361            }
3362
3363            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3364                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3365                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3366            }
3367        }
3368    }
3369
3370    @Override
3371    public boolean isPackageAvailable(String packageName, int userId) {
3372        if (!sUserManager.exists(userId)) return false;
3373        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3374                false /* requireFullPermission */, false /* checkShell */, "is package available");
3375        synchronized (mPackages) {
3376            PackageParser.Package p = mPackages.get(packageName);
3377            if (p != null) {
3378                final PackageSetting ps = (PackageSetting) p.mExtras;
3379                if (ps != null) {
3380                    final PackageUserState state = ps.readUserState(userId);
3381                    if (state != null) {
3382                        return PackageParser.isAvailable(state);
3383                    }
3384                }
3385            }
3386        }
3387        return false;
3388    }
3389
3390    @Override
3391    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3392        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3393                flags, userId);
3394    }
3395
3396    @Override
3397    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3398            int flags, int userId) {
3399        return getPackageInfoInternal(versionedPackage.getPackageName(),
3400                // TODO: We will change version code to long, so in the new API it is long
3401                (int) versionedPackage.getVersionCode(), flags, userId);
3402    }
3403
3404    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3405            int flags, int userId) {
3406        if (!sUserManager.exists(userId)) return null;
3407        flags = updateFlagsForPackage(flags, userId, packageName);
3408        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3409                false /* requireFullPermission */, false /* checkShell */, "get package info");
3410
3411        // reader
3412        synchronized (mPackages) {
3413            // Normalize package name to handle renamed packages and static libs
3414            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3415
3416            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3417            if (matchFactoryOnly) {
3418                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3419                if (ps != null) {
3420                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3421                        return null;
3422                    }
3423                    return generatePackageInfo(ps, flags, userId);
3424                }
3425            }
3426
3427            PackageParser.Package p = mPackages.get(packageName);
3428            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3429                return null;
3430            }
3431            if (DEBUG_PACKAGE_INFO)
3432                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3433            if (p != null) {
3434                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3435                        Binder.getCallingUid(), userId)) {
3436                    return null;
3437                }
3438                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3439            }
3440            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3441                final PackageSetting ps = mSettings.mPackages.get(packageName);
3442                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3443                    return null;
3444                }
3445                return generatePackageInfo(ps, flags, userId);
3446            }
3447        }
3448        return null;
3449    }
3450
3451
3452    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3453        // System/shell/root get to see all static libs
3454        final int appId = UserHandle.getAppId(uid);
3455        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3456                || appId == Process.ROOT_UID) {
3457            return false;
3458        }
3459
3460        // No package means no static lib as it is always on internal storage
3461        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3462            return false;
3463        }
3464
3465        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3466                ps.pkg.staticSharedLibVersion);
3467        if (libEntry == null) {
3468            return false;
3469        }
3470
3471        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3472        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3473        if (uidPackageNames == null) {
3474            return true;
3475        }
3476
3477        for (String uidPackageName : uidPackageNames) {
3478            if (ps.name.equals(uidPackageName)) {
3479                return false;
3480            }
3481            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3482            if (uidPs != null) {
3483                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3484                        libEntry.info.getName());
3485                if (index < 0) {
3486                    continue;
3487                }
3488                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3489                    return false;
3490                }
3491            }
3492        }
3493        return true;
3494    }
3495
3496    @Override
3497    public String[] currentToCanonicalPackageNames(String[] names) {
3498        String[] out = new String[names.length];
3499        // reader
3500        synchronized (mPackages) {
3501            for (int i=names.length-1; i>=0; i--) {
3502                PackageSetting ps = mSettings.mPackages.get(names[i]);
3503                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3504            }
3505        }
3506        return out;
3507    }
3508
3509    @Override
3510    public String[] canonicalToCurrentPackageNames(String[] names) {
3511        String[] out = new String[names.length];
3512        // reader
3513        synchronized (mPackages) {
3514            for (int i=names.length-1; i>=0; i--) {
3515                String cur = mSettings.getRenamedPackageLPr(names[i]);
3516                out[i] = cur != null ? cur : names[i];
3517            }
3518        }
3519        return out;
3520    }
3521
3522    @Override
3523    public int getPackageUid(String packageName, int flags, int userId) {
3524        if (!sUserManager.exists(userId)) return -1;
3525        flags = updateFlagsForPackage(flags, userId, packageName);
3526        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3527                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3528
3529        // reader
3530        synchronized (mPackages) {
3531            final PackageParser.Package p = mPackages.get(packageName);
3532            if (p != null && p.isMatch(flags)) {
3533                return UserHandle.getUid(userId, p.applicationInfo.uid);
3534            }
3535            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3536                final PackageSetting ps = mSettings.mPackages.get(packageName);
3537                if (ps != null && ps.isMatch(flags)) {
3538                    return UserHandle.getUid(userId, ps.appId);
3539                }
3540            }
3541        }
3542
3543        return -1;
3544    }
3545
3546    @Override
3547    public int[] getPackageGids(String packageName, int flags, int userId) {
3548        if (!sUserManager.exists(userId)) return null;
3549        flags = updateFlagsForPackage(flags, userId, packageName);
3550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3551                false /* requireFullPermission */, false /* checkShell */,
3552                "getPackageGids");
3553
3554        // reader
3555        synchronized (mPackages) {
3556            final PackageParser.Package p = mPackages.get(packageName);
3557            if (p != null && p.isMatch(flags)) {
3558                PackageSetting ps = (PackageSetting) p.mExtras;
3559                // TODO: Shouldn't this be checking for package installed state for userId and
3560                // return null?
3561                return ps.getPermissionsState().computeGids(userId);
3562            }
3563            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3564                final PackageSetting ps = mSettings.mPackages.get(packageName);
3565                if (ps != null && ps.isMatch(flags)) {
3566                    return ps.getPermissionsState().computeGids(userId);
3567                }
3568            }
3569        }
3570
3571        return null;
3572    }
3573
3574    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3575        if (bp.perm != null) {
3576            return PackageParser.generatePermissionInfo(bp.perm, flags);
3577        }
3578        PermissionInfo pi = new PermissionInfo();
3579        pi.name = bp.name;
3580        pi.packageName = bp.sourcePackage;
3581        pi.nonLocalizedLabel = bp.name;
3582        pi.protectionLevel = bp.protectionLevel;
3583        return pi;
3584    }
3585
3586    @Override
3587    public PermissionInfo getPermissionInfo(String name, int flags) {
3588        // reader
3589        synchronized (mPackages) {
3590            final BasePermission p = mSettings.mPermissions.get(name);
3591            if (p != null) {
3592                return generatePermissionInfo(p, flags);
3593            }
3594            return null;
3595        }
3596    }
3597
3598    @Override
3599    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3600            int flags) {
3601        // reader
3602        synchronized (mPackages) {
3603            if (group != null && !mPermissionGroups.containsKey(group)) {
3604                // This is thrown as NameNotFoundException
3605                return null;
3606            }
3607
3608            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3609            for (BasePermission p : mSettings.mPermissions.values()) {
3610                if (group == null) {
3611                    if (p.perm == null || p.perm.info.group == null) {
3612                        out.add(generatePermissionInfo(p, flags));
3613                    }
3614                } else {
3615                    if (p.perm != null && group.equals(p.perm.info.group)) {
3616                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3617                    }
3618                }
3619            }
3620            return new ParceledListSlice<>(out);
3621        }
3622    }
3623
3624    @Override
3625    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3626        // reader
3627        synchronized (mPackages) {
3628            return PackageParser.generatePermissionGroupInfo(
3629                    mPermissionGroups.get(name), flags);
3630        }
3631    }
3632
3633    @Override
3634    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3635        // reader
3636        synchronized (mPackages) {
3637            final int N = mPermissionGroups.size();
3638            ArrayList<PermissionGroupInfo> out
3639                    = new ArrayList<PermissionGroupInfo>(N);
3640            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3641                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3642            }
3643            return new ParceledListSlice<>(out);
3644        }
3645    }
3646
3647    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3648            int uid, int userId) {
3649        if (!sUserManager.exists(userId)) return null;
3650        PackageSetting ps = mSettings.mPackages.get(packageName);
3651        if (ps != null) {
3652            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3653                return null;
3654            }
3655            if (ps.pkg == null) {
3656                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3657                if (pInfo != null) {
3658                    return pInfo.applicationInfo;
3659                }
3660                return null;
3661            }
3662            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3663                    ps.readUserState(userId), userId);
3664            if (ai != null) {
3665                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3666            }
3667            return ai;
3668        }
3669        return null;
3670    }
3671
3672    @Override
3673    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3674        if (!sUserManager.exists(userId)) return null;
3675        flags = updateFlagsForApplication(flags, userId, packageName);
3676        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3677                false /* requireFullPermission */, false /* checkShell */, "get application info");
3678
3679        // writer
3680        synchronized (mPackages) {
3681            // Normalize package name to handle renamed packages and static libs
3682            packageName = resolveInternalPackageNameLPr(packageName,
3683                    PackageManager.VERSION_CODE_HIGHEST);
3684
3685            PackageParser.Package p = mPackages.get(packageName);
3686            if (DEBUG_PACKAGE_INFO) Log.v(
3687                    TAG, "getApplicationInfo " + packageName
3688                    + ": " + p);
3689            if (p != null) {
3690                PackageSetting ps = mSettings.mPackages.get(packageName);
3691                if (ps == null) return null;
3692                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3693                    return null;
3694                }
3695                // Note: isEnabledLP() does not apply here - always return info
3696                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3697                        p, flags, ps.readUserState(userId), userId);
3698                if (ai != null) {
3699                    ai.packageName = resolveExternalPackageNameLPr(p);
3700                }
3701                return ai;
3702            }
3703            if ("android".equals(packageName)||"system".equals(packageName)) {
3704                return mAndroidApplication;
3705            }
3706            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3707                // Already generates the external package name
3708                return generateApplicationInfoFromSettingsLPw(packageName,
3709                        Binder.getCallingUid(), flags, userId);
3710            }
3711        }
3712        return null;
3713    }
3714
3715    private String normalizePackageNameLPr(String packageName) {
3716        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3717        return normalizedPackageName != null ? normalizedPackageName : packageName;
3718    }
3719
3720    @Override
3721    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3722            final IPackageDataObserver observer) {
3723        mContext.enforceCallingOrSelfPermission(
3724                android.Manifest.permission.CLEAR_APP_CACHE, null);
3725        // Queue up an async operation since clearing cache may take a little while.
3726        mHandler.post(new Runnable() {
3727            public void run() {
3728                mHandler.removeCallbacks(this);
3729                boolean success = true;
3730                synchronized (mInstallLock) {
3731                    try {
3732                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3733                    } catch (InstallerException e) {
3734                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3735                        success = false;
3736                    }
3737                }
3738                if (observer != null) {
3739                    try {
3740                        observer.onRemoveCompleted(null, success);
3741                    } catch (RemoteException e) {
3742                        Slog.w(TAG, "RemoveException when invoking call back");
3743                    }
3744                }
3745            }
3746        });
3747    }
3748
3749    @Override
3750    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3751            final IntentSender pi) {
3752        mContext.enforceCallingOrSelfPermission(
3753                android.Manifest.permission.CLEAR_APP_CACHE, null);
3754        // Queue up an async operation since clearing cache may take a little while.
3755        mHandler.post(new Runnable() {
3756            public void run() {
3757                mHandler.removeCallbacks(this);
3758                boolean success = true;
3759                synchronized (mInstallLock) {
3760                    try {
3761                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3762                    } catch (InstallerException e) {
3763                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3764                        success = false;
3765                    }
3766                }
3767                if(pi != null) {
3768                    try {
3769                        // Callback via pending intent
3770                        int code = success ? 1 : 0;
3771                        pi.sendIntent(null, code, null,
3772                                null, null);
3773                    } catch (SendIntentException e1) {
3774                        Slog.i(TAG, "Failed to send pending intent");
3775                    }
3776                }
3777            }
3778        });
3779    }
3780
3781    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3782        synchronized (mInstallLock) {
3783            try {
3784                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3785            } catch (InstallerException e) {
3786                throw new IOException("Failed to free enough space", e);
3787            }
3788        }
3789    }
3790
3791    /**
3792     * Update given flags based on encryption status of current user.
3793     */
3794    private int updateFlags(int flags, int userId) {
3795        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3796                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3797            // Caller expressed an explicit opinion about what encryption
3798            // aware/unaware components they want to see, so fall through and
3799            // give them what they want
3800        } else {
3801            // Caller expressed no opinion, so match based on user state
3802            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3803                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3804            } else {
3805                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3806            }
3807        }
3808        return flags;
3809    }
3810
3811    private UserManagerInternal getUserManagerInternal() {
3812        if (mUserManagerInternal == null) {
3813            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3814        }
3815        return mUserManagerInternal;
3816    }
3817
3818    /**
3819     * Update given flags when being used to request {@link PackageInfo}.
3820     */
3821    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3822        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3823        boolean triaged = true;
3824        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3825                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3826            // Caller is asking for component details, so they'd better be
3827            // asking for specific encryption matching behavior, or be triaged
3828            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3829                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3830                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3831                triaged = false;
3832            }
3833        }
3834        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3835                | PackageManager.MATCH_SYSTEM_ONLY
3836                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3837            triaged = false;
3838        }
3839        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3840            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3841                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3842                    + Debug.getCallers(5));
3843        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3844                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3845            // If the caller wants all packages and has a restricted profile associated with it,
3846            // then match all users. This is to make sure that launchers that need to access work
3847            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3848            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3849            flags |= PackageManager.MATCH_ANY_USER;
3850        }
3851        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3852            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3853                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3854        }
3855        return updateFlags(flags, userId);
3856    }
3857
3858    /**
3859     * Update given flags when being used to request {@link ApplicationInfo}.
3860     */
3861    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3862        return updateFlagsForPackage(flags, userId, cookie);
3863    }
3864
3865    /**
3866     * Update given flags when being used to request {@link ComponentInfo}.
3867     */
3868    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3869        if (cookie instanceof Intent) {
3870            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3871                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3872            }
3873        }
3874
3875        boolean triaged = true;
3876        // Caller is asking for component details, so they'd better be
3877        // asking for specific encryption matching behavior, or be triaged
3878        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3879                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3880                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3881            triaged = false;
3882        }
3883        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3884            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3885                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3886        }
3887
3888        return updateFlags(flags, userId);
3889    }
3890
3891    /**
3892     * Update given intent when being used to request {@link ResolveInfo}.
3893     */
3894    private Intent updateIntentForResolve(Intent intent) {
3895        if (intent.getSelector() != null) {
3896            intent = intent.getSelector();
3897        }
3898        if (DEBUG_PREFERRED) {
3899            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3900        }
3901        return intent;
3902    }
3903
3904    /**
3905     * Update given flags when being used to request {@link ResolveInfo}.
3906     */
3907    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3908        // Safe mode means we shouldn't match any third-party components
3909        if (mSafeMode) {
3910            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3911        }
3912        final int callingUid = Binder.getCallingUid();
3913        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3914            // The system sees all components
3915            flags |= PackageManager.MATCH_EPHEMERAL;
3916        } else if (getEphemeralPackageName(callingUid) != null) {
3917            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3918            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3919            flags |= PackageManager.MATCH_EPHEMERAL;
3920        } else {
3921            // Otherwise, prevent leaking ephemeral components
3922            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3923            flags &= ~PackageManager.MATCH_EPHEMERAL;
3924        }
3925        return updateFlagsForComponent(flags, userId, cookie);
3926    }
3927
3928    @Override
3929    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3930        if (!sUserManager.exists(userId)) return null;
3931        flags = updateFlagsForComponent(flags, userId, component);
3932        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3933                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3934        synchronized (mPackages) {
3935            PackageParser.Activity a = mActivities.mActivities.get(component);
3936
3937            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3938            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3939                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3940                if (ps == null) return null;
3941                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3942                        userId);
3943            }
3944            if (mResolveComponentName.equals(component)) {
3945                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3946                        new PackageUserState(), userId);
3947            }
3948        }
3949        return null;
3950    }
3951
3952    @Override
3953    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3954            String resolvedType) {
3955        synchronized (mPackages) {
3956            if (component.equals(mResolveComponentName)) {
3957                // The resolver supports EVERYTHING!
3958                return true;
3959            }
3960            PackageParser.Activity a = mActivities.mActivities.get(component);
3961            if (a == null) {
3962                return false;
3963            }
3964            for (int i=0; i<a.intents.size(); i++) {
3965                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3966                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3967                    return true;
3968                }
3969            }
3970            return false;
3971        }
3972    }
3973
3974    @Override
3975    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3976        if (!sUserManager.exists(userId)) return null;
3977        flags = updateFlagsForComponent(flags, userId, component);
3978        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3979                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3980        synchronized (mPackages) {
3981            PackageParser.Activity a = mReceivers.mActivities.get(component);
3982            if (DEBUG_PACKAGE_INFO) Log.v(
3983                TAG, "getReceiverInfo " + component + ": " + a);
3984            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3985                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3986                if (ps == null) return null;
3987                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3988                        userId);
3989            }
3990        }
3991        return null;
3992    }
3993
3994    @Override
3995    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
3996        if (!sUserManager.exists(userId)) return null;
3997        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
3998
3999        flags = updateFlagsForPackage(flags, userId, null);
4000
4001        final boolean canSeeStaticLibraries =
4002                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4003                        == PERMISSION_GRANTED
4004                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4005                        == PERMISSION_GRANTED
4006                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4007                        == PERMISSION_GRANTED
4008                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4009                        == PERMISSION_GRANTED;
4010
4011        synchronized (mPackages) {
4012            List<SharedLibraryInfo> result = null;
4013
4014            final int libCount = mSharedLibraries.size();
4015            for (int i = 0; i < libCount; i++) {
4016                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4017                if (versionedLib == null) {
4018                    continue;
4019                }
4020
4021                final int versionCount = versionedLib.size();
4022                for (int j = 0; j < versionCount; j++) {
4023                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4024                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4025                        break;
4026                    }
4027                    final long identity = Binder.clearCallingIdentity();
4028                    try {
4029                        // TODO: We will change version code to long, so in the new API it is long
4030                        PackageInfo packageInfo = getPackageInfoVersioned(
4031                                libInfo.getDeclaringPackage(), flags, userId);
4032                        if (packageInfo == null) {
4033                            continue;
4034                        }
4035                    } finally {
4036                        Binder.restoreCallingIdentity(identity);
4037                    }
4038
4039                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4040                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4041                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4042
4043                    if (result == null) {
4044                        result = new ArrayList<>();
4045                    }
4046                    result.add(resLibInfo);
4047                }
4048            }
4049
4050            return result != null ? new ParceledListSlice<>(result) : null;
4051        }
4052    }
4053
4054    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4055            SharedLibraryInfo libInfo, int flags, int userId) {
4056        List<VersionedPackage> versionedPackages = null;
4057        final int packageCount = mSettings.mPackages.size();
4058        for (int i = 0; i < packageCount; i++) {
4059            PackageSetting ps = mSettings.mPackages.valueAt(i);
4060
4061            if (ps == null) {
4062                continue;
4063            }
4064
4065            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4066                continue;
4067            }
4068
4069            final String libName = libInfo.getName();
4070            if (libInfo.isStatic()) {
4071                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4072                if (libIdx < 0) {
4073                    continue;
4074                }
4075                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4076                    continue;
4077                }
4078                if (versionedPackages == null) {
4079                    versionedPackages = new ArrayList<>();
4080                }
4081                // If the dependent is a static shared lib, use the public package name
4082                String dependentPackageName = ps.name;
4083                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4084                    dependentPackageName = ps.pkg.manifestPackageName;
4085                }
4086                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4087            } else if (ps.pkg != null) {
4088                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4089                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4090                    if (versionedPackages == null) {
4091                        versionedPackages = new ArrayList<>();
4092                    }
4093                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4094                }
4095            }
4096        }
4097
4098        return versionedPackages;
4099    }
4100
4101    @Override
4102    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4103        if (!sUserManager.exists(userId)) return null;
4104        flags = updateFlagsForComponent(flags, userId, component);
4105        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4106                false /* requireFullPermission */, false /* checkShell */, "get service info");
4107        synchronized (mPackages) {
4108            PackageParser.Service s = mServices.mServices.get(component);
4109            if (DEBUG_PACKAGE_INFO) Log.v(
4110                TAG, "getServiceInfo " + component + ": " + s);
4111            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4112                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4113                if (ps == null) return null;
4114                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4115                        userId);
4116            }
4117        }
4118        return null;
4119    }
4120
4121    @Override
4122    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        flags = updateFlagsForComponent(flags, userId, component);
4125        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4126                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4127        synchronized (mPackages) {
4128            PackageParser.Provider p = mProviders.mProviders.get(component);
4129            if (DEBUG_PACKAGE_INFO) Log.v(
4130                TAG, "getProviderInfo " + component + ": " + p);
4131            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4132                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4133                if (ps == null) return null;
4134                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4135                        userId);
4136            }
4137        }
4138        return null;
4139    }
4140
4141    @Override
4142    public String[] getSystemSharedLibraryNames() {
4143        synchronized (mPackages) {
4144            Set<String> libs = null;
4145            final int libCount = mSharedLibraries.size();
4146            for (int i = 0; i < libCount; i++) {
4147                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4148                if (versionedLib == null) {
4149                    continue;
4150                }
4151                final int versionCount = versionedLib.size();
4152                for (int j = 0; j < versionCount; j++) {
4153                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4154                    if (!libEntry.info.isStatic()) {
4155                        if (libs == null) {
4156                            libs = new ArraySet<>();
4157                        }
4158                        libs.add(libEntry.info.getName());
4159                        break;
4160                    }
4161                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4162                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4163                            UserHandle.getUserId(Binder.getCallingUid()))) {
4164                        if (libs == null) {
4165                            libs = new ArraySet<>();
4166                        }
4167                        libs.add(libEntry.info.getName());
4168                        break;
4169                    }
4170                }
4171            }
4172
4173            if (libs != null) {
4174                String[] libsArray = new String[libs.size()];
4175                libs.toArray(libsArray);
4176                return libsArray;
4177            }
4178
4179            return null;
4180        }
4181    }
4182
4183    @Override
4184    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4185        synchronized (mPackages) {
4186            return mServicesSystemSharedLibraryPackageName;
4187        }
4188    }
4189
4190    @Override
4191    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4192        synchronized (mPackages) {
4193            return mSharedSystemSharedLibraryPackageName;
4194        }
4195    }
4196
4197    @Override
4198    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4199        synchronized (mPackages) {
4200            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
4201
4202            final FeatureInfo fi = new FeatureInfo();
4203            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4204                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
4205            res.add(fi);
4206
4207            return new ParceledListSlice<>(res);
4208        }
4209    }
4210
4211    @Override
4212    public boolean hasSystemFeature(String name, int version) {
4213        synchronized (mPackages) {
4214            final FeatureInfo feat = mAvailableFeatures.get(name);
4215            if (feat == null) {
4216                return false;
4217            } else {
4218                return feat.version >= version;
4219            }
4220        }
4221    }
4222
4223    @Override
4224    public int checkPermission(String permName, String pkgName, int userId) {
4225        if (!sUserManager.exists(userId)) {
4226            return PackageManager.PERMISSION_DENIED;
4227        }
4228
4229        synchronized (mPackages) {
4230            final PackageParser.Package p = mPackages.get(pkgName);
4231            if (p != null && p.mExtras != null) {
4232                final PackageSetting ps = (PackageSetting) p.mExtras;
4233                final PermissionsState permissionsState = ps.getPermissionsState();
4234                if (permissionsState.hasPermission(permName, userId)) {
4235                    return PackageManager.PERMISSION_GRANTED;
4236                }
4237                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4238                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4239                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4240                    return PackageManager.PERMISSION_GRANTED;
4241                }
4242            }
4243        }
4244
4245        return PackageManager.PERMISSION_DENIED;
4246    }
4247
4248    @Override
4249    public int checkUidPermission(String permName, int uid) {
4250        final int userId = UserHandle.getUserId(uid);
4251
4252        if (!sUserManager.exists(userId)) {
4253            return PackageManager.PERMISSION_DENIED;
4254        }
4255
4256        synchronized (mPackages) {
4257            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4258            if (obj != null) {
4259                final SettingBase ps = (SettingBase) obj;
4260                final PermissionsState permissionsState = ps.getPermissionsState();
4261                if (permissionsState.hasPermission(permName, userId)) {
4262                    return PackageManager.PERMISSION_GRANTED;
4263                }
4264                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4265                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4266                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4267                    return PackageManager.PERMISSION_GRANTED;
4268                }
4269            } else {
4270                ArraySet<String> perms = mSystemPermissions.get(uid);
4271                if (perms != null) {
4272                    if (perms.contains(permName)) {
4273                        return PackageManager.PERMISSION_GRANTED;
4274                    }
4275                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4276                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4277                        return PackageManager.PERMISSION_GRANTED;
4278                    }
4279                }
4280            }
4281        }
4282
4283        return PackageManager.PERMISSION_DENIED;
4284    }
4285
4286    @Override
4287    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4288        if (UserHandle.getCallingUserId() != userId) {
4289            mContext.enforceCallingPermission(
4290                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4291                    "isPermissionRevokedByPolicy for user " + userId);
4292        }
4293
4294        if (checkPermission(permission, packageName, userId)
4295                == PackageManager.PERMISSION_GRANTED) {
4296            return false;
4297        }
4298
4299        final long identity = Binder.clearCallingIdentity();
4300        try {
4301            final int flags = getPermissionFlags(permission, packageName, userId);
4302            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4303        } finally {
4304            Binder.restoreCallingIdentity(identity);
4305        }
4306    }
4307
4308    @Override
4309    public String getPermissionControllerPackageName() {
4310        synchronized (mPackages) {
4311            return mRequiredInstallerPackage;
4312        }
4313    }
4314
4315    /**
4316     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4317     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4318     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4319     * @param message the message to log on security exception
4320     */
4321    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4322            boolean checkShell, String message) {
4323        if (userId < 0) {
4324            throw new IllegalArgumentException("Invalid userId " + userId);
4325        }
4326        if (checkShell) {
4327            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4328        }
4329        if (userId == UserHandle.getUserId(callingUid)) return;
4330        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4331            if (requireFullPermission) {
4332                mContext.enforceCallingOrSelfPermission(
4333                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4334            } else {
4335                try {
4336                    mContext.enforceCallingOrSelfPermission(
4337                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4338                } catch (SecurityException se) {
4339                    mContext.enforceCallingOrSelfPermission(
4340                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4341                }
4342            }
4343        }
4344    }
4345
4346    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4347        if (callingUid == Process.SHELL_UID) {
4348            if (userHandle >= 0
4349                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4350                throw new SecurityException("Shell does not have permission to access user "
4351                        + userHandle);
4352            } else if (userHandle < 0) {
4353                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4354                        + Debug.getCallers(3));
4355            }
4356        }
4357    }
4358
4359    private BasePermission findPermissionTreeLP(String permName) {
4360        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4361            if (permName.startsWith(bp.name) &&
4362                    permName.length() > bp.name.length() &&
4363                    permName.charAt(bp.name.length()) == '.') {
4364                return bp;
4365            }
4366        }
4367        return null;
4368    }
4369
4370    private BasePermission checkPermissionTreeLP(String permName) {
4371        if (permName != null) {
4372            BasePermission bp = findPermissionTreeLP(permName);
4373            if (bp != null) {
4374                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4375                    return bp;
4376                }
4377                throw new SecurityException("Calling uid "
4378                        + Binder.getCallingUid()
4379                        + " is not allowed to add to permission tree "
4380                        + bp.name + " owned by uid " + bp.uid);
4381            }
4382        }
4383        throw new SecurityException("No permission tree found for " + permName);
4384    }
4385
4386    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4387        if (s1 == null) {
4388            return s2 == null;
4389        }
4390        if (s2 == null) {
4391            return false;
4392        }
4393        if (s1.getClass() != s2.getClass()) {
4394            return false;
4395        }
4396        return s1.equals(s2);
4397    }
4398
4399    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4400        if (pi1.icon != pi2.icon) return false;
4401        if (pi1.logo != pi2.logo) return false;
4402        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4403        if (!compareStrings(pi1.name, pi2.name)) return false;
4404        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4405        // We'll take care of setting this one.
4406        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4407        // These are not currently stored in settings.
4408        //if (!compareStrings(pi1.group, pi2.group)) return false;
4409        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4410        //if (pi1.labelRes != pi2.labelRes) return false;
4411        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4412        return true;
4413    }
4414
4415    int permissionInfoFootprint(PermissionInfo info) {
4416        int size = info.name.length();
4417        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4418        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4419        return size;
4420    }
4421
4422    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4423        int size = 0;
4424        for (BasePermission perm : mSettings.mPermissions.values()) {
4425            if (perm.uid == tree.uid) {
4426                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4427            }
4428        }
4429        return size;
4430    }
4431
4432    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4433        // We calculate the max size of permissions defined by this uid and throw
4434        // if that plus the size of 'info' would exceed our stated maximum.
4435        if (tree.uid != Process.SYSTEM_UID) {
4436            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4437            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4438                throw new SecurityException("Permission tree size cap exceeded");
4439            }
4440        }
4441    }
4442
4443    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4444        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4445            throw new SecurityException("Label must be specified in permission");
4446        }
4447        BasePermission tree = checkPermissionTreeLP(info.name);
4448        BasePermission bp = mSettings.mPermissions.get(info.name);
4449        boolean added = bp == null;
4450        boolean changed = true;
4451        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4452        if (added) {
4453            enforcePermissionCapLocked(info, tree);
4454            bp = new BasePermission(info.name, tree.sourcePackage,
4455                    BasePermission.TYPE_DYNAMIC);
4456        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4457            throw new SecurityException(
4458                    "Not allowed to modify non-dynamic permission "
4459                    + info.name);
4460        } else {
4461            if (bp.protectionLevel == fixedLevel
4462                    && bp.perm.owner.equals(tree.perm.owner)
4463                    && bp.uid == tree.uid
4464                    && comparePermissionInfos(bp.perm.info, info)) {
4465                changed = false;
4466            }
4467        }
4468        bp.protectionLevel = fixedLevel;
4469        info = new PermissionInfo(info);
4470        info.protectionLevel = fixedLevel;
4471        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4472        bp.perm.info.packageName = tree.perm.info.packageName;
4473        bp.uid = tree.uid;
4474        if (added) {
4475            mSettings.mPermissions.put(info.name, bp);
4476        }
4477        if (changed) {
4478            if (!async) {
4479                mSettings.writeLPr();
4480            } else {
4481                scheduleWriteSettingsLocked();
4482            }
4483        }
4484        return added;
4485    }
4486
4487    @Override
4488    public boolean addPermission(PermissionInfo info) {
4489        synchronized (mPackages) {
4490            return addPermissionLocked(info, false);
4491        }
4492    }
4493
4494    @Override
4495    public boolean addPermissionAsync(PermissionInfo info) {
4496        synchronized (mPackages) {
4497            return addPermissionLocked(info, true);
4498        }
4499    }
4500
4501    @Override
4502    public void removePermission(String name) {
4503        synchronized (mPackages) {
4504            checkPermissionTreeLP(name);
4505            BasePermission bp = mSettings.mPermissions.get(name);
4506            if (bp != null) {
4507                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4508                    throw new SecurityException(
4509                            "Not allowed to modify non-dynamic permission "
4510                            + name);
4511                }
4512                mSettings.mPermissions.remove(name);
4513                mSettings.writeLPr();
4514            }
4515        }
4516    }
4517
4518    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4519            BasePermission bp) {
4520        int index = pkg.requestedPermissions.indexOf(bp.name);
4521        if (index == -1) {
4522            throw new SecurityException("Package " + pkg.packageName
4523                    + " has not requested permission " + bp.name);
4524        }
4525        if (!bp.isRuntime() && !bp.isDevelopment()) {
4526            throw new SecurityException("Permission " + bp.name
4527                    + " is not a changeable permission type");
4528        }
4529    }
4530
4531    @Override
4532    public void grantRuntimePermission(String packageName, String name, final int userId) {
4533        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4534    }
4535
4536    private void grantRuntimePermission(String packageName, String name, final int userId,
4537            boolean overridePolicy) {
4538        if (!sUserManager.exists(userId)) {
4539            Log.e(TAG, "No such user:" + userId);
4540            return;
4541        }
4542
4543        mContext.enforceCallingOrSelfPermission(
4544                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4545                "grantRuntimePermission");
4546
4547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4548                true /* requireFullPermission */, true /* checkShell */,
4549                "grantRuntimePermission");
4550
4551        final int uid;
4552        final SettingBase sb;
4553
4554        synchronized (mPackages) {
4555            final PackageParser.Package pkg = mPackages.get(packageName);
4556            if (pkg == null) {
4557                throw new IllegalArgumentException("Unknown package: " + packageName);
4558            }
4559
4560            final BasePermission bp = mSettings.mPermissions.get(name);
4561            if (bp == null) {
4562                throw new IllegalArgumentException("Unknown permission: " + name);
4563            }
4564
4565            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4566
4567            // If a permission review is required for legacy apps we represent
4568            // their permissions as always granted runtime ones since we need
4569            // to keep the review required permission flag per user while an
4570            // install permission's state is shared across all users.
4571            if (mPermissionReviewRequired
4572                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4573                    && bp.isRuntime()) {
4574                return;
4575            }
4576
4577            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4578            sb = (SettingBase) pkg.mExtras;
4579            if (sb == null) {
4580                throw new IllegalArgumentException("Unknown package: " + packageName);
4581            }
4582
4583            final PermissionsState permissionsState = sb.getPermissionsState();
4584
4585            final int flags = permissionsState.getPermissionFlags(name, userId);
4586            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4587                throw new SecurityException("Cannot grant system fixed permission "
4588                        + name + " for package " + packageName);
4589            }
4590            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4591                throw new SecurityException("Cannot grant policy fixed permission "
4592                        + name + " for package " + packageName);
4593            }
4594
4595            if (bp.isDevelopment()) {
4596                // Development permissions must be handled specially, since they are not
4597                // normal runtime permissions.  For now they apply to all users.
4598                if (permissionsState.grantInstallPermission(bp) !=
4599                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4600                    scheduleWriteSettingsLocked();
4601                }
4602                return;
4603            }
4604
4605            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4606                throw new SecurityException("Cannot grant non-ephemeral permission"
4607                        + name + " for package " + packageName);
4608            }
4609
4610            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4611                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4612                return;
4613            }
4614
4615            final int result = permissionsState.grantRuntimePermission(bp, userId);
4616            switch (result) {
4617                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4618                    return;
4619                }
4620
4621                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4622                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4623                    mHandler.post(new Runnable() {
4624                        @Override
4625                        public void run() {
4626                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4627                        }
4628                    });
4629                }
4630                break;
4631            }
4632
4633            if (bp.isRuntime()) {
4634                logPermissionGranted(mContext, name, packageName);
4635            }
4636
4637            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4638
4639            // Not critical if that is lost - app has to request again.
4640            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4641        }
4642
4643        // Only need to do this if user is initialized. Otherwise it's a new user
4644        // and there are no processes running as the user yet and there's no need
4645        // to make an expensive call to remount processes for the changed permissions.
4646        if (READ_EXTERNAL_STORAGE.equals(name)
4647                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4648            final long token = Binder.clearCallingIdentity();
4649            try {
4650                if (sUserManager.isInitialized(userId)) {
4651                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4652                            StorageManagerInternal.class);
4653                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4654                }
4655            } finally {
4656                Binder.restoreCallingIdentity(token);
4657            }
4658        }
4659    }
4660
4661    @Override
4662    public void revokeRuntimePermission(String packageName, String name, int userId) {
4663        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4664    }
4665
4666    private void revokeRuntimePermission(String packageName, String name, int userId,
4667            boolean overridePolicy) {
4668        if (!sUserManager.exists(userId)) {
4669            Log.e(TAG, "No such user:" + userId);
4670            return;
4671        }
4672
4673        mContext.enforceCallingOrSelfPermission(
4674                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4675                "revokeRuntimePermission");
4676
4677        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4678                true /* requireFullPermission */, true /* checkShell */,
4679                "revokeRuntimePermission");
4680
4681        final int appId;
4682
4683        synchronized (mPackages) {
4684            final PackageParser.Package pkg = mPackages.get(packageName);
4685            if (pkg == null) {
4686                throw new IllegalArgumentException("Unknown package: " + packageName);
4687            }
4688
4689            final BasePermission bp = mSettings.mPermissions.get(name);
4690            if (bp == null) {
4691                throw new IllegalArgumentException("Unknown permission: " + name);
4692            }
4693
4694            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4695
4696            // If a permission review is required for legacy apps we represent
4697            // their permissions as always granted runtime ones since we need
4698            // to keep the review required permission flag per user while an
4699            // install permission's state is shared across all users.
4700            if (mPermissionReviewRequired
4701                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4702                    && bp.isRuntime()) {
4703                return;
4704            }
4705
4706            SettingBase sb = (SettingBase) pkg.mExtras;
4707            if (sb == null) {
4708                throw new IllegalArgumentException("Unknown package: " + packageName);
4709            }
4710
4711            final PermissionsState permissionsState = sb.getPermissionsState();
4712
4713            final int flags = permissionsState.getPermissionFlags(name, userId);
4714            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4715                throw new SecurityException("Cannot revoke system fixed permission "
4716                        + name + " for package " + packageName);
4717            }
4718            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4719                throw new SecurityException("Cannot revoke policy fixed permission "
4720                        + name + " for package " + packageName);
4721            }
4722
4723            if (bp.isDevelopment()) {
4724                // Development permissions must be handled specially, since they are not
4725                // normal runtime permissions.  For now they apply to all users.
4726                if (permissionsState.revokeInstallPermission(bp) !=
4727                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4728                    scheduleWriteSettingsLocked();
4729                }
4730                return;
4731            }
4732
4733            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4734                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4735                return;
4736            }
4737
4738            if (bp.isRuntime()) {
4739                logPermissionRevoked(mContext, name, packageName);
4740            }
4741
4742            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4743
4744            // Critical, after this call app should never have the permission.
4745            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4746
4747            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4748        }
4749
4750        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4751    }
4752
4753    /**
4754     * Get the first event id for the permission.
4755     *
4756     * <p>There are four events for each permission: <ul>
4757     *     <li>Request permission: first id + 0</li>
4758     *     <li>Grant permission: first id + 1</li>
4759     *     <li>Request for permission denied: first id + 2</li>
4760     *     <li>Revoke permission: first id + 3</li>
4761     * </ul></p>
4762     *
4763     * @param name name of the permission
4764     *
4765     * @return The first event id for the permission
4766     */
4767    private static int getBaseEventId(@NonNull String name) {
4768        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4769
4770        if (eventIdIndex == -1) {
4771            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4772                    || "user".equals(Build.TYPE)) {
4773                Log.i(TAG, "Unknown permission " + name);
4774
4775                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4776            } else {
4777                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4778                //
4779                // Also update
4780                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4781                // - metrics_constants.proto
4782                throw new IllegalStateException("Unknown permission " + name);
4783            }
4784        }
4785
4786        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4787    }
4788
4789    /**
4790     * Log that a permission was revoked.
4791     *
4792     * @param context Context of the caller
4793     * @param name name of the permission
4794     * @param packageName package permission if for
4795     */
4796    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4797            @NonNull String packageName) {
4798        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4799    }
4800
4801    /**
4802     * Log that a permission request was granted.
4803     *
4804     * @param context Context of the caller
4805     * @param name name of the permission
4806     * @param packageName package permission if for
4807     */
4808    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4809            @NonNull String packageName) {
4810        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4811    }
4812
4813    @Override
4814    public void resetRuntimePermissions() {
4815        mContext.enforceCallingOrSelfPermission(
4816                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4817                "revokeRuntimePermission");
4818
4819        int callingUid = Binder.getCallingUid();
4820        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4821            mContext.enforceCallingOrSelfPermission(
4822                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4823                    "resetRuntimePermissions");
4824        }
4825
4826        synchronized (mPackages) {
4827            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4828            for (int userId : UserManagerService.getInstance().getUserIds()) {
4829                final int packageCount = mPackages.size();
4830                for (int i = 0; i < packageCount; i++) {
4831                    PackageParser.Package pkg = mPackages.valueAt(i);
4832                    if (!(pkg.mExtras instanceof PackageSetting)) {
4833                        continue;
4834                    }
4835                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4836                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4837                }
4838            }
4839        }
4840    }
4841
4842    @Override
4843    public int getPermissionFlags(String name, String packageName, int userId) {
4844        if (!sUserManager.exists(userId)) {
4845            return 0;
4846        }
4847
4848        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4849
4850        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4851                true /* requireFullPermission */, false /* checkShell */,
4852                "getPermissionFlags");
4853
4854        synchronized (mPackages) {
4855            final PackageParser.Package pkg = mPackages.get(packageName);
4856            if (pkg == null) {
4857                return 0;
4858            }
4859
4860            final BasePermission bp = mSettings.mPermissions.get(name);
4861            if (bp == null) {
4862                return 0;
4863            }
4864
4865            SettingBase sb = (SettingBase) pkg.mExtras;
4866            if (sb == null) {
4867                return 0;
4868            }
4869
4870            PermissionsState permissionsState = sb.getPermissionsState();
4871            return permissionsState.getPermissionFlags(name, userId);
4872        }
4873    }
4874
4875    @Override
4876    public void updatePermissionFlags(String name, String packageName, int flagMask,
4877            int flagValues, int userId) {
4878        if (!sUserManager.exists(userId)) {
4879            return;
4880        }
4881
4882        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4883
4884        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4885                true /* requireFullPermission */, true /* checkShell */,
4886                "updatePermissionFlags");
4887
4888        // Only the system can change these flags and nothing else.
4889        if (getCallingUid() != Process.SYSTEM_UID) {
4890            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4891            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4892            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4893            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4894            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4895        }
4896
4897        synchronized (mPackages) {
4898            final PackageParser.Package pkg = mPackages.get(packageName);
4899            if (pkg == null) {
4900                throw new IllegalArgumentException("Unknown package: " + packageName);
4901            }
4902
4903            final BasePermission bp = mSettings.mPermissions.get(name);
4904            if (bp == null) {
4905                throw new IllegalArgumentException("Unknown permission: " + name);
4906            }
4907
4908            SettingBase sb = (SettingBase) pkg.mExtras;
4909            if (sb == null) {
4910                throw new IllegalArgumentException("Unknown package: " + packageName);
4911            }
4912
4913            PermissionsState permissionsState = sb.getPermissionsState();
4914
4915            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4916
4917            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4918                // Install and runtime permissions are stored in different places,
4919                // so figure out what permission changed and persist the change.
4920                if (permissionsState.getInstallPermissionState(name) != null) {
4921                    scheduleWriteSettingsLocked();
4922                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4923                        || hadState) {
4924                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4925                }
4926            }
4927        }
4928    }
4929
4930    /**
4931     * Update the permission flags for all packages and runtime permissions of a user in order
4932     * to allow device or profile owner to remove POLICY_FIXED.
4933     */
4934    @Override
4935    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4936        if (!sUserManager.exists(userId)) {
4937            return;
4938        }
4939
4940        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4941
4942        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4943                true /* requireFullPermission */, true /* checkShell */,
4944                "updatePermissionFlagsForAllApps");
4945
4946        // Only the system can change system fixed flags.
4947        if (getCallingUid() != Process.SYSTEM_UID) {
4948            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4949            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4950        }
4951
4952        synchronized (mPackages) {
4953            boolean changed = false;
4954            final int packageCount = mPackages.size();
4955            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4956                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4957                SettingBase sb = (SettingBase) pkg.mExtras;
4958                if (sb == null) {
4959                    continue;
4960                }
4961                PermissionsState permissionsState = sb.getPermissionsState();
4962                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4963                        userId, flagMask, flagValues);
4964            }
4965            if (changed) {
4966                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4967            }
4968        }
4969    }
4970
4971    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4972        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4973                != PackageManager.PERMISSION_GRANTED
4974            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4975                != PackageManager.PERMISSION_GRANTED) {
4976            throw new SecurityException(message + " requires "
4977                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4978                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4979        }
4980    }
4981
4982    @Override
4983    public boolean shouldShowRequestPermissionRationale(String permissionName,
4984            String packageName, int userId) {
4985        if (UserHandle.getCallingUserId() != userId) {
4986            mContext.enforceCallingPermission(
4987                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4988                    "canShowRequestPermissionRationale for user " + userId);
4989        }
4990
4991        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4992        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4993            return false;
4994        }
4995
4996        if (checkPermission(permissionName, packageName, userId)
4997                == PackageManager.PERMISSION_GRANTED) {
4998            return false;
4999        }
5000
5001        final int flags;
5002
5003        final long identity = Binder.clearCallingIdentity();
5004        try {
5005            flags = getPermissionFlags(permissionName,
5006                    packageName, userId);
5007        } finally {
5008            Binder.restoreCallingIdentity(identity);
5009        }
5010
5011        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5012                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5013                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5014
5015        if ((flags & fixedFlags) != 0) {
5016            return false;
5017        }
5018
5019        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5020    }
5021
5022    @Override
5023    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5024        mContext.enforceCallingOrSelfPermission(
5025                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5026                "addOnPermissionsChangeListener");
5027
5028        synchronized (mPackages) {
5029            mOnPermissionChangeListeners.addListenerLocked(listener);
5030        }
5031    }
5032
5033    @Override
5034    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5035        synchronized (mPackages) {
5036            mOnPermissionChangeListeners.removeListenerLocked(listener);
5037        }
5038    }
5039
5040    @Override
5041    public boolean isProtectedBroadcast(String actionName) {
5042        synchronized (mPackages) {
5043            if (mProtectedBroadcasts.contains(actionName)) {
5044                return true;
5045            } else if (actionName != null) {
5046                // TODO: remove these terrible hacks
5047                if (actionName.startsWith("android.net.netmon.lingerExpired")
5048                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5049                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5050                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5051                    return true;
5052                }
5053            }
5054        }
5055        return false;
5056    }
5057
5058    @Override
5059    public int checkSignatures(String pkg1, String pkg2) {
5060        synchronized (mPackages) {
5061            final PackageParser.Package p1 = mPackages.get(pkg1);
5062            final PackageParser.Package p2 = mPackages.get(pkg2);
5063            if (p1 == null || p1.mExtras == null
5064                    || p2 == null || p2.mExtras == null) {
5065                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5066            }
5067            return compareSignatures(p1.mSignatures, p2.mSignatures);
5068        }
5069    }
5070
5071    @Override
5072    public int checkUidSignatures(int uid1, int uid2) {
5073        // Map to base uids.
5074        uid1 = UserHandle.getAppId(uid1);
5075        uid2 = UserHandle.getAppId(uid2);
5076        // reader
5077        synchronized (mPackages) {
5078            Signature[] s1;
5079            Signature[] s2;
5080            Object obj = mSettings.getUserIdLPr(uid1);
5081            if (obj != null) {
5082                if (obj instanceof SharedUserSetting) {
5083                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5084                } else if (obj instanceof PackageSetting) {
5085                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5086                } else {
5087                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5088                }
5089            } else {
5090                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5091            }
5092            obj = mSettings.getUserIdLPr(uid2);
5093            if (obj != null) {
5094                if (obj instanceof SharedUserSetting) {
5095                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5096                } else if (obj instanceof PackageSetting) {
5097                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5098                } else {
5099                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5100                }
5101            } else {
5102                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5103            }
5104            return compareSignatures(s1, s2);
5105        }
5106    }
5107
5108    /**
5109     * This method should typically only be used when granting or revoking
5110     * permissions, since the app may immediately restart after this call.
5111     * <p>
5112     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5113     * guard your work against the app being relaunched.
5114     */
5115    private void killUid(int appId, int userId, String reason) {
5116        final long identity = Binder.clearCallingIdentity();
5117        try {
5118            IActivityManager am = ActivityManager.getService();
5119            if (am != null) {
5120                try {
5121                    am.killUid(appId, userId, reason);
5122                } catch (RemoteException e) {
5123                    /* ignore - same process */
5124                }
5125            }
5126        } finally {
5127            Binder.restoreCallingIdentity(identity);
5128        }
5129    }
5130
5131    /**
5132     * Compares two sets of signatures. Returns:
5133     * <br />
5134     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5135     * <br />
5136     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5137     * <br />
5138     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5139     * <br />
5140     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5141     * <br />
5142     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5143     */
5144    static int compareSignatures(Signature[] s1, Signature[] s2) {
5145        if (s1 == null) {
5146            return s2 == null
5147                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5148                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5149        }
5150
5151        if (s2 == null) {
5152            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5153        }
5154
5155        if (s1.length != s2.length) {
5156            return PackageManager.SIGNATURE_NO_MATCH;
5157        }
5158
5159        // Since both signature sets are of size 1, we can compare without HashSets.
5160        if (s1.length == 1) {
5161            return s1[0].equals(s2[0]) ?
5162                    PackageManager.SIGNATURE_MATCH :
5163                    PackageManager.SIGNATURE_NO_MATCH;
5164        }
5165
5166        ArraySet<Signature> set1 = new ArraySet<Signature>();
5167        for (Signature sig : s1) {
5168            set1.add(sig);
5169        }
5170        ArraySet<Signature> set2 = new ArraySet<Signature>();
5171        for (Signature sig : s2) {
5172            set2.add(sig);
5173        }
5174        // Make sure s2 contains all signatures in s1.
5175        if (set1.equals(set2)) {
5176            return PackageManager.SIGNATURE_MATCH;
5177        }
5178        return PackageManager.SIGNATURE_NO_MATCH;
5179    }
5180
5181    /**
5182     * If the database version for this type of package (internal storage or
5183     * external storage) is less than the version where package signatures
5184     * were updated, return true.
5185     */
5186    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5187        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5188        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5189    }
5190
5191    /**
5192     * Used for backward compatibility to make sure any packages with
5193     * certificate chains get upgraded to the new style. {@code existingSigs}
5194     * will be in the old format (since they were stored on disk from before the
5195     * system upgrade) and {@code scannedSigs} will be in the newer format.
5196     */
5197    private int compareSignaturesCompat(PackageSignatures existingSigs,
5198            PackageParser.Package scannedPkg) {
5199        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5200            return PackageManager.SIGNATURE_NO_MATCH;
5201        }
5202
5203        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5204        for (Signature sig : existingSigs.mSignatures) {
5205            existingSet.add(sig);
5206        }
5207        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5208        for (Signature sig : scannedPkg.mSignatures) {
5209            try {
5210                Signature[] chainSignatures = sig.getChainSignatures();
5211                for (Signature chainSig : chainSignatures) {
5212                    scannedCompatSet.add(chainSig);
5213                }
5214            } catch (CertificateEncodingException e) {
5215                scannedCompatSet.add(sig);
5216            }
5217        }
5218        /*
5219         * Make sure the expanded scanned set contains all signatures in the
5220         * existing one.
5221         */
5222        if (scannedCompatSet.equals(existingSet)) {
5223            // Migrate the old signatures to the new scheme.
5224            existingSigs.assignSignatures(scannedPkg.mSignatures);
5225            // The new KeySets will be re-added later in the scanning process.
5226            synchronized (mPackages) {
5227                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5228            }
5229            return PackageManager.SIGNATURE_MATCH;
5230        }
5231        return PackageManager.SIGNATURE_NO_MATCH;
5232    }
5233
5234    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5235        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5236        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5237    }
5238
5239    private int compareSignaturesRecover(PackageSignatures existingSigs,
5240            PackageParser.Package scannedPkg) {
5241        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5242            return PackageManager.SIGNATURE_NO_MATCH;
5243        }
5244
5245        String msg = null;
5246        try {
5247            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5248                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5249                        + scannedPkg.packageName);
5250                return PackageManager.SIGNATURE_MATCH;
5251            }
5252        } catch (CertificateException e) {
5253            msg = e.getMessage();
5254        }
5255
5256        logCriticalInfo(Log.INFO,
5257                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5258        return PackageManager.SIGNATURE_NO_MATCH;
5259    }
5260
5261    @Override
5262    public List<String> getAllPackages() {
5263        synchronized (mPackages) {
5264            return new ArrayList<String>(mPackages.keySet());
5265        }
5266    }
5267
5268    @Override
5269    public String[] getPackagesForUid(int uid) {
5270        final int userId = UserHandle.getUserId(uid);
5271        uid = UserHandle.getAppId(uid);
5272        // reader
5273        synchronized (mPackages) {
5274            Object obj = mSettings.getUserIdLPr(uid);
5275            if (obj instanceof SharedUserSetting) {
5276                final SharedUserSetting sus = (SharedUserSetting) obj;
5277                final int N = sus.packages.size();
5278                String[] res = new String[N];
5279                final Iterator<PackageSetting> it = sus.packages.iterator();
5280                int i = 0;
5281                while (it.hasNext()) {
5282                    PackageSetting ps = it.next();
5283                    if (ps.getInstalled(userId)) {
5284                        res[i++] = ps.name;
5285                    } else {
5286                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5287                    }
5288                }
5289                return res;
5290            } else if (obj instanceof PackageSetting) {
5291                final PackageSetting ps = (PackageSetting) obj;
5292                if (ps.getInstalled(userId)) {
5293                    return new String[]{ps.name};
5294                }
5295            }
5296        }
5297        return null;
5298    }
5299
5300    @Override
5301    public String getNameForUid(int uid) {
5302        // reader
5303        synchronized (mPackages) {
5304            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5305            if (obj instanceof SharedUserSetting) {
5306                final SharedUserSetting sus = (SharedUserSetting) obj;
5307                return sus.name + ":" + sus.userId;
5308            } else if (obj instanceof PackageSetting) {
5309                final PackageSetting ps = (PackageSetting) obj;
5310                return ps.name;
5311            }
5312        }
5313        return null;
5314    }
5315
5316    @Override
5317    public int getUidForSharedUser(String sharedUserName) {
5318        if(sharedUserName == null) {
5319            return -1;
5320        }
5321        // reader
5322        synchronized (mPackages) {
5323            SharedUserSetting suid;
5324            try {
5325                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5326                if (suid != null) {
5327                    return suid.userId;
5328                }
5329            } catch (PackageManagerException ignore) {
5330                // can't happen, but, still need to catch it
5331            }
5332            return -1;
5333        }
5334    }
5335
5336    @Override
5337    public int getFlagsForUid(int uid) {
5338        synchronized (mPackages) {
5339            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5340            if (obj instanceof SharedUserSetting) {
5341                final SharedUserSetting sus = (SharedUserSetting) obj;
5342                return sus.pkgFlags;
5343            } else if (obj instanceof PackageSetting) {
5344                final PackageSetting ps = (PackageSetting) obj;
5345                return ps.pkgFlags;
5346            }
5347        }
5348        return 0;
5349    }
5350
5351    @Override
5352    public int getPrivateFlagsForUid(int uid) {
5353        synchronized (mPackages) {
5354            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5355            if (obj instanceof SharedUserSetting) {
5356                final SharedUserSetting sus = (SharedUserSetting) obj;
5357                return sus.pkgPrivateFlags;
5358            } else if (obj instanceof PackageSetting) {
5359                final PackageSetting ps = (PackageSetting) obj;
5360                return ps.pkgPrivateFlags;
5361            }
5362        }
5363        return 0;
5364    }
5365
5366    @Override
5367    public boolean isUidPrivileged(int uid) {
5368        uid = UserHandle.getAppId(uid);
5369        // reader
5370        synchronized (mPackages) {
5371            Object obj = mSettings.getUserIdLPr(uid);
5372            if (obj instanceof SharedUserSetting) {
5373                final SharedUserSetting sus = (SharedUserSetting) obj;
5374                final Iterator<PackageSetting> it = sus.packages.iterator();
5375                while (it.hasNext()) {
5376                    if (it.next().isPrivileged()) {
5377                        return true;
5378                    }
5379                }
5380            } else if (obj instanceof PackageSetting) {
5381                final PackageSetting ps = (PackageSetting) obj;
5382                return ps.isPrivileged();
5383            }
5384        }
5385        return false;
5386    }
5387
5388    @Override
5389    public String[] getAppOpPermissionPackages(String permissionName) {
5390        synchronized (mPackages) {
5391            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5392            if (pkgs == null) {
5393                return null;
5394            }
5395            return pkgs.toArray(new String[pkgs.size()]);
5396        }
5397    }
5398
5399    @Override
5400    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5401            int flags, int userId) {
5402        try {
5403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5404
5405            if (!sUserManager.exists(userId)) return null;
5406            flags = updateFlagsForResolve(flags, userId, intent);
5407            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5408                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5409
5410            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5411            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5412                    flags, userId);
5413            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5414
5415            final ResolveInfo bestChoice =
5416                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5417            return bestChoice;
5418        } finally {
5419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5420        }
5421    }
5422
5423    @Override
5424    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5425        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5426            throw new SecurityException(
5427                    "findPersistentPreferredActivity can only be run by the system");
5428        }
5429        if (!sUserManager.exists(userId)) {
5430            return null;
5431        }
5432        intent = updateIntentForResolve(intent);
5433        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5434        final int flags = updateFlagsForResolve(0, userId, intent);
5435        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5436                userId);
5437        synchronized (mPackages) {
5438            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5439                    userId);
5440        }
5441    }
5442
5443    @Override
5444    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5445            IntentFilter filter, int match, ComponentName activity) {
5446        final int userId = UserHandle.getCallingUserId();
5447        if (DEBUG_PREFERRED) {
5448            Log.v(TAG, "setLastChosenActivity intent=" + intent
5449                + " resolvedType=" + resolvedType
5450                + " flags=" + flags
5451                + " filter=" + filter
5452                + " match=" + match
5453                + " activity=" + activity);
5454            filter.dump(new PrintStreamPrinter(System.out), "    ");
5455        }
5456        intent.setComponent(null);
5457        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5458                userId);
5459        // Find any earlier preferred or last chosen entries and nuke them
5460        findPreferredActivity(intent, resolvedType,
5461                flags, query, 0, false, true, false, userId);
5462        // Add the new activity as the last chosen for this filter
5463        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5464                "Setting last chosen");
5465    }
5466
5467    @Override
5468    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5469        final int userId = UserHandle.getCallingUserId();
5470        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5471        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5472                userId);
5473        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5474                false, false, false, userId);
5475    }
5476
5477    private boolean isEphemeralDisabled() {
5478        // ephemeral apps have been disabled across the board
5479        if (DISABLE_EPHEMERAL_APPS) {
5480            return true;
5481        }
5482        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5483        if (!mSystemReady) {
5484            return true;
5485        }
5486        // we can't get a content resolver until the system is ready; these checks must happen last
5487        final ContentResolver resolver = mContext.getContentResolver();
5488        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5489            return true;
5490        }
5491        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5492    }
5493
5494    private boolean isEphemeralAllowed(
5495            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5496            boolean skipPackageCheck) {
5497        // Short circuit and return early if possible.
5498        if (isEphemeralDisabled()) {
5499            return false;
5500        }
5501        final int callingUser = UserHandle.getCallingUserId();
5502        if (callingUser != UserHandle.USER_SYSTEM) {
5503            return false;
5504        }
5505        if (mEphemeralResolverConnection == null) {
5506            return false;
5507        }
5508        if (mEphemeralInstallerComponent == null) {
5509            return false;
5510        }
5511        if (intent.getComponent() != null) {
5512            return false;
5513        }
5514        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5515            return false;
5516        }
5517        if (!skipPackageCheck && intent.getPackage() != null) {
5518            return false;
5519        }
5520        final boolean isWebUri = hasWebURI(intent);
5521        if (!isWebUri || intent.getData().getHost() == null) {
5522            return false;
5523        }
5524        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5525        synchronized (mPackages) {
5526            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5527            for (int n = 0; n < count; n++) {
5528                ResolveInfo info = resolvedActivities.get(n);
5529                String packageName = info.activityInfo.packageName;
5530                PackageSetting ps = mSettings.mPackages.get(packageName);
5531                if (ps != null) {
5532                    // Try to get the status from User settings first
5533                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5534                    int status = (int) (packedStatus >> 32);
5535                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5536                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5537                        if (DEBUG_EPHEMERAL) {
5538                            Slog.v(TAG, "DENY ephemeral apps;"
5539                                + " pkg: " + packageName + ", status: " + status);
5540                        }
5541                        return false;
5542                    }
5543                }
5544            }
5545        }
5546        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5547        return true;
5548    }
5549
5550    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5551            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5552            int userId) {
5553        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5554                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5555                        callingPackage, userId));
5556        mHandler.sendMessage(msg);
5557    }
5558
5559    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5560            int flags, List<ResolveInfo> query, int userId) {
5561        if (query != null) {
5562            final int N = query.size();
5563            if (N == 1) {
5564                return query.get(0);
5565            } else if (N > 1) {
5566                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5567                // If there is more than one activity with the same priority,
5568                // then let the user decide between them.
5569                ResolveInfo r0 = query.get(0);
5570                ResolveInfo r1 = query.get(1);
5571                if (DEBUG_INTENT_MATCHING || debug) {
5572                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5573                            + r1.activityInfo.name + "=" + r1.priority);
5574                }
5575                // If the first activity has a higher priority, or a different
5576                // default, then it is always desirable to pick it.
5577                if (r0.priority != r1.priority
5578                        || r0.preferredOrder != r1.preferredOrder
5579                        || r0.isDefault != r1.isDefault) {
5580                    return query.get(0);
5581                }
5582                // If we have saved a preference for a preferred activity for
5583                // this Intent, use that.
5584                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5585                        flags, query, r0.priority, true, false, debug, userId);
5586                if (ri != null) {
5587                    return ri;
5588                }
5589                ri = new ResolveInfo(mResolveInfo);
5590                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5591                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5592                // If all of the options come from the same package, show the application's
5593                // label and icon instead of the generic resolver's.
5594                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5595                // and then throw away the ResolveInfo itself, meaning that the caller loses
5596                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5597                // a fallback for this case; we only set the target package's resources on
5598                // the ResolveInfo, not the ActivityInfo.
5599                final String intentPackage = intent.getPackage();
5600                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5601                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5602                    ri.resolvePackageName = intentPackage;
5603                    if (userNeedsBadging(userId)) {
5604                        ri.noResourceId = true;
5605                    } else {
5606                        ri.icon = appi.icon;
5607                    }
5608                    ri.iconResourceId = appi.icon;
5609                    ri.labelRes = appi.labelRes;
5610                }
5611                ri.activityInfo.applicationInfo = new ApplicationInfo(
5612                        ri.activityInfo.applicationInfo);
5613                if (userId != 0) {
5614                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5615                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5616                }
5617                // Make sure that the resolver is displayable in car mode
5618                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5619                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5620                return ri;
5621            }
5622        }
5623        return null;
5624    }
5625
5626    /**
5627     * Return true if the given list is not empty and all of its contents have
5628     * an activityInfo with the given package name.
5629     */
5630    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5631        if (ArrayUtils.isEmpty(list)) {
5632            return false;
5633        }
5634        for (int i = 0, N = list.size(); i < N; i++) {
5635            final ResolveInfo ri = list.get(i);
5636            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5637            if (ai == null || !packageName.equals(ai.packageName)) {
5638                return false;
5639            }
5640        }
5641        return true;
5642    }
5643
5644    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5645            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5646        final int N = query.size();
5647        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5648                .get(userId);
5649        // Get the list of persistent preferred activities that handle the intent
5650        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5651        List<PersistentPreferredActivity> pprefs = ppir != null
5652                ? ppir.queryIntent(intent, resolvedType,
5653                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5654                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5655                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5656                : null;
5657        if (pprefs != null && pprefs.size() > 0) {
5658            final int M = pprefs.size();
5659            for (int i=0; i<M; i++) {
5660                final PersistentPreferredActivity ppa = pprefs.get(i);
5661                if (DEBUG_PREFERRED || debug) {
5662                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5663                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5664                            + "\n  component=" + ppa.mComponent);
5665                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5666                }
5667                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5668                        flags | MATCH_DISABLED_COMPONENTS, userId);
5669                if (DEBUG_PREFERRED || debug) {
5670                    Slog.v(TAG, "Found persistent preferred activity:");
5671                    if (ai != null) {
5672                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5673                    } else {
5674                        Slog.v(TAG, "  null");
5675                    }
5676                }
5677                if (ai == null) {
5678                    // This previously registered persistent preferred activity
5679                    // component is no longer known. Ignore it and do NOT remove it.
5680                    continue;
5681                }
5682                for (int j=0; j<N; j++) {
5683                    final ResolveInfo ri = query.get(j);
5684                    if (!ri.activityInfo.applicationInfo.packageName
5685                            .equals(ai.applicationInfo.packageName)) {
5686                        continue;
5687                    }
5688                    if (!ri.activityInfo.name.equals(ai.name)) {
5689                        continue;
5690                    }
5691                    //  Found a persistent preference that can handle the intent.
5692                    if (DEBUG_PREFERRED || debug) {
5693                        Slog.v(TAG, "Returning persistent preferred activity: " +
5694                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5695                    }
5696                    return ri;
5697                }
5698            }
5699        }
5700        return null;
5701    }
5702
5703    // TODO: handle preferred activities missing while user has amnesia
5704    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5705            List<ResolveInfo> query, int priority, boolean always,
5706            boolean removeMatches, boolean debug, int userId) {
5707        if (!sUserManager.exists(userId)) return null;
5708        flags = updateFlagsForResolve(flags, userId, intent);
5709        intent = updateIntentForResolve(intent);
5710        // writer
5711        synchronized (mPackages) {
5712            // Try to find a matching persistent preferred activity.
5713            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5714                    debug, userId);
5715
5716            // If a persistent preferred activity matched, use it.
5717            if (pri != null) {
5718                return pri;
5719            }
5720
5721            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5722            // Get the list of preferred activities that handle the intent
5723            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5724            List<PreferredActivity> prefs = pir != null
5725                    ? pir.queryIntent(intent, resolvedType,
5726                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5727                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5728                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5729                    : null;
5730            if (prefs != null && prefs.size() > 0) {
5731                boolean changed = false;
5732                try {
5733                    // First figure out how good the original match set is.
5734                    // We will only allow preferred activities that came
5735                    // from the same match quality.
5736                    int match = 0;
5737
5738                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5739
5740                    final int N = query.size();
5741                    for (int j=0; j<N; j++) {
5742                        final ResolveInfo ri = query.get(j);
5743                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5744                                + ": 0x" + Integer.toHexString(match));
5745                        if (ri.match > match) {
5746                            match = ri.match;
5747                        }
5748                    }
5749
5750                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5751                            + Integer.toHexString(match));
5752
5753                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5754                    final int M = prefs.size();
5755                    for (int i=0; i<M; i++) {
5756                        final PreferredActivity pa = prefs.get(i);
5757                        if (DEBUG_PREFERRED || debug) {
5758                            Slog.v(TAG, "Checking PreferredActivity ds="
5759                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5760                                    + "\n  component=" + pa.mPref.mComponent);
5761                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5762                        }
5763                        if (pa.mPref.mMatch != match) {
5764                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5765                                    + Integer.toHexString(pa.mPref.mMatch));
5766                            continue;
5767                        }
5768                        // If it's not an "always" type preferred activity and that's what we're
5769                        // looking for, skip it.
5770                        if (always && !pa.mPref.mAlways) {
5771                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5772                            continue;
5773                        }
5774                        final ActivityInfo ai = getActivityInfo(
5775                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5776                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5777                                userId);
5778                        if (DEBUG_PREFERRED || debug) {
5779                            Slog.v(TAG, "Found preferred activity:");
5780                            if (ai != null) {
5781                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5782                            } else {
5783                                Slog.v(TAG, "  null");
5784                            }
5785                        }
5786                        if (ai == null) {
5787                            // This previously registered preferred activity
5788                            // component is no longer known.  Most likely an update
5789                            // to the app was installed and in the new version this
5790                            // component no longer exists.  Clean it up by removing
5791                            // it from the preferred activities list, and skip it.
5792                            Slog.w(TAG, "Removing dangling preferred activity: "
5793                                    + pa.mPref.mComponent);
5794                            pir.removeFilter(pa);
5795                            changed = true;
5796                            continue;
5797                        }
5798                        for (int j=0; j<N; j++) {
5799                            final ResolveInfo ri = query.get(j);
5800                            if (!ri.activityInfo.applicationInfo.packageName
5801                                    .equals(ai.applicationInfo.packageName)) {
5802                                continue;
5803                            }
5804                            if (!ri.activityInfo.name.equals(ai.name)) {
5805                                continue;
5806                            }
5807
5808                            if (removeMatches) {
5809                                pir.removeFilter(pa);
5810                                changed = true;
5811                                if (DEBUG_PREFERRED) {
5812                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5813                                }
5814                                break;
5815                            }
5816
5817                            // Okay we found a previously set preferred or last chosen app.
5818                            // If the result set is different from when this
5819                            // was created, we need to clear it and re-ask the
5820                            // user their preference, if we're looking for an "always" type entry.
5821                            if (always && !pa.mPref.sameSet(query)) {
5822                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5823                                        + intent + " type " + resolvedType);
5824                                if (DEBUG_PREFERRED) {
5825                                    Slog.v(TAG, "Removing preferred activity since set changed "
5826                                            + pa.mPref.mComponent);
5827                                }
5828                                pir.removeFilter(pa);
5829                                // Re-add the filter as a "last chosen" entry (!always)
5830                                PreferredActivity lastChosen = new PreferredActivity(
5831                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5832                                pir.addFilter(lastChosen);
5833                                changed = true;
5834                                return null;
5835                            }
5836
5837                            // Yay! Either the set matched or we're looking for the last chosen
5838                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5839                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5840                            return ri;
5841                        }
5842                    }
5843                } finally {
5844                    if (changed) {
5845                        if (DEBUG_PREFERRED) {
5846                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5847                        }
5848                        scheduleWritePackageRestrictionsLocked(userId);
5849                    }
5850                }
5851            }
5852        }
5853        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5854        return null;
5855    }
5856
5857    /*
5858     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5859     */
5860    @Override
5861    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5862            int targetUserId) {
5863        mContext.enforceCallingOrSelfPermission(
5864                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5865        List<CrossProfileIntentFilter> matches =
5866                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5867        if (matches != null) {
5868            int size = matches.size();
5869            for (int i = 0; i < size; i++) {
5870                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5871            }
5872        }
5873        if (hasWebURI(intent)) {
5874            // cross-profile app linking works only towards the parent.
5875            final UserInfo parent = getProfileParent(sourceUserId);
5876            synchronized(mPackages) {
5877                int flags = updateFlagsForResolve(0, parent.id, intent);
5878                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5879                        intent, resolvedType, flags, sourceUserId, parent.id);
5880                return xpDomainInfo != null;
5881            }
5882        }
5883        return false;
5884    }
5885
5886    private UserInfo getProfileParent(int userId) {
5887        final long identity = Binder.clearCallingIdentity();
5888        try {
5889            return sUserManager.getProfileParent(userId);
5890        } finally {
5891            Binder.restoreCallingIdentity(identity);
5892        }
5893    }
5894
5895    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5896            String resolvedType, int userId) {
5897        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5898        if (resolver != null) {
5899            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5900                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5901        }
5902        return null;
5903    }
5904
5905    @Override
5906    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5907            String resolvedType, int flags, int userId) {
5908        try {
5909            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5910
5911            return new ParceledListSlice<>(
5912                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5913        } finally {
5914            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5915        }
5916    }
5917
5918    /**
5919     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5920     * ephemeral, returns {@code null}.
5921     */
5922    private String getEphemeralPackageName(int callingUid) {
5923        final int appId = UserHandle.getAppId(callingUid);
5924        synchronized (mPackages) {
5925            final Object obj = mSettings.getUserIdLPr(appId);
5926            if (obj instanceof PackageSetting) {
5927                final PackageSetting ps = (PackageSetting) obj;
5928                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5929            }
5930        }
5931        return null;
5932    }
5933
5934    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5935            String resolvedType, int flags, int userId) {
5936        if (!sUserManager.exists(userId)) return Collections.emptyList();
5937        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5938        flags = updateFlagsForResolve(flags, userId, intent);
5939        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5940                false /* requireFullPermission */, false /* checkShell */,
5941                "query intent activities");
5942        ComponentName comp = intent.getComponent();
5943        if (comp == null) {
5944            if (intent.getSelector() != null) {
5945                intent = intent.getSelector();
5946                comp = intent.getComponent();
5947            }
5948        }
5949
5950        if (comp != null) {
5951            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5952            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5953            if (ai != null) {
5954                // When specifying an explicit component, we prevent the activity from being
5955                // used when either 1) the calling package is normal and the activity is within
5956                // an ephemeral application or 2) the calling package is ephemeral and the
5957                // activity is not visible to ephemeral applications.
5958                boolean matchEphemeral =
5959                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5960                boolean ephemeralVisibleOnly =
5961                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5962                boolean blockResolution =
5963                        (!matchEphemeral && ephemeralPkgName == null
5964                                && (ai.applicationInfo.privateFlags
5965                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5966                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5967                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5968                if (!blockResolution) {
5969                    final ResolveInfo ri = new ResolveInfo();
5970                    ri.activityInfo = ai;
5971                    list.add(ri);
5972                }
5973            }
5974            return list;
5975        }
5976
5977        // reader
5978        boolean sortResult = false;
5979        boolean addEphemeral = false;
5980        List<ResolveInfo> result;
5981        final String pkgName = intent.getPackage();
5982        synchronized (mPackages) {
5983            if (pkgName == null) {
5984                List<CrossProfileIntentFilter> matchingFilters =
5985                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5986                // Check for results that need to skip the current profile.
5987                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5988                        resolvedType, flags, userId);
5989                if (xpResolveInfo != null) {
5990                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5991                    xpResult.add(xpResolveInfo);
5992                    return filterForEphemeral(
5993                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5994                }
5995
5996                // Check for results in the current profile.
5997                result = filterIfNotSystemUser(mActivities.queryIntent(
5998                        intent, resolvedType, flags, userId), userId);
5999                addEphemeral =
6000                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6001
6002                // Check for cross profile results.
6003                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6004                xpResolveInfo = queryCrossProfileIntents(
6005                        matchingFilters, intent, resolvedType, flags, userId,
6006                        hasNonNegativePriorityResult);
6007                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6008                    boolean isVisibleToUser = filterIfNotSystemUser(
6009                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6010                    if (isVisibleToUser) {
6011                        result.add(xpResolveInfo);
6012                        sortResult = true;
6013                    }
6014                }
6015                if (hasWebURI(intent)) {
6016                    CrossProfileDomainInfo xpDomainInfo = null;
6017                    final UserInfo parent = getProfileParent(userId);
6018                    if (parent != null) {
6019                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6020                                flags, userId, parent.id);
6021                    }
6022                    if (xpDomainInfo != null) {
6023                        if (xpResolveInfo != null) {
6024                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6025                            // in the result.
6026                            result.remove(xpResolveInfo);
6027                        }
6028                        if (result.size() == 0 && !addEphemeral) {
6029                            // No result in current profile, but found candidate in parent user.
6030                            // And we are not going to add emphemeral app, so we can return the
6031                            // result straight away.
6032                            result.add(xpDomainInfo.resolveInfo);
6033                            return filterForEphemeral(result, ephemeralPkgName);
6034                        }
6035                    } else if (result.size() <= 1 && !addEphemeral) {
6036                        // No result in parent user and <= 1 result in current profile, and we
6037                        // are not going to add emphemeral app, so we can return the result without
6038                        // further processing.
6039                        return filterForEphemeral(result, ephemeralPkgName);
6040                    }
6041                    // We have more than one candidate (combining results from current and parent
6042                    // profile), so we need filtering and sorting.
6043                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6044                            intent, flags, result, xpDomainInfo, userId);
6045                    sortResult = true;
6046                }
6047            } else {
6048                final PackageParser.Package pkg = mPackages.get(pkgName);
6049                if (pkg != null) {
6050                    result = filterForEphemeral(filterIfNotSystemUser(
6051                            mActivities.queryIntentForPackage(
6052                                    intent, resolvedType, flags, pkg.activities, userId),
6053                            userId), ephemeralPkgName);
6054                } else {
6055                    // the caller wants to resolve for a particular package; however, there
6056                    // were no installed results, so, try to find an ephemeral result
6057                    addEphemeral = isEphemeralAllowed(
6058                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6059                    result = new ArrayList<ResolveInfo>();
6060                }
6061            }
6062        }
6063        if (addEphemeral) {
6064            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6065            final EphemeralRequest requestObject = new EphemeralRequest(
6066                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6067                    null /*launchIntent*/, null /*callingPackage*/, userId);
6068            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6069                    mContext, mEphemeralResolverConnection, requestObject);
6070            if (intentInfo != null) {
6071                if (DEBUG_EPHEMERAL) {
6072                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6073                }
6074                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6075                ephemeralInstaller.ephemeralResponse = intentInfo;
6076                // make sure this resolver is the default
6077                ephemeralInstaller.isDefault = true;
6078                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6079                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6080                // add a non-generic filter
6081                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6082                ephemeralInstaller.filter.addDataPath(
6083                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6084                result.add(ephemeralInstaller);
6085            }
6086            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6087        }
6088        if (sortResult) {
6089            Collections.sort(result, mResolvePrioritySorter);
6090        }
6091        return filterForEphemeral(result, ephemeralPkgName);
6092    }
6093
6094    private static class CrossProfileDomainInfo {
6095        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6096        ResolveInfo resolveInfo;
6097        /* Best domain verification status of the activities found in the other profile */
6098        int bestDomainVerificationStatus;
6099    }
6100
6101    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6102            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6103        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6104                sourceUserId)) {
6105            return null;
6106        }
6107        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6108                resolvedType, flags, parentUserId);
6109
6110        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6111            return null;
6112        }
6113        CrossProfileDomainInfo result = null;
6114        int size = resultTargetUser.size();
6115        for (int i = 0; i < size; i++) {
6116            ResolveInfo riTargetUser = resultTargetUser.get(i);
6117            // Intent filter verification is only for filters that specify a host. So don't return
6118            // those that handle all web uris.
6119            if (riTargetUser.handleAllWebDataURI) {
6120                continue;
6121            }
6122            String packageName = riTargetUser.activityInfo.packageName;
6123            PackageSetting ps = mSettings.mPackages.get(packageName);
6124            if (ps == null) {
6125                continue;
6126            }
6127            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6128            int status = (int)(verificationState >> 32);
6129            if (result == null) {
6130                result = new CrossProfileDomainInfo();
6131                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6132                        sourceUserId, parentUserId);
6133                result.bestDomainVerificationStatus = status;
6134            } else {
6135                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6136                        result.bestDomainVerificationStatus);
6137            }
6138        }
6139        // Don't consider matches with status NEVER across profiles.
6140        if (result != null && result.bestDomainVerificationStatus
6141                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6142            return null;
6143        }
6144        return result;
6145    }
6146
6147    /**
6148     * Verification statuses are ordered from the worse to the best, except for
6149     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6150     */
6151    private int bestDomainVerificationStatus(int status1, int status2) {
6152        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6153            return status2;
6154        }
6155        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6156            return status1;
6157        }
6158        return (int) MathUtils.max(status1, status2);
6159    }
6160
6161    private boolean isUserEnabled(int userId) {
6162        long callingId = Binder.clearCallingIdentity();
6163        try {
6164            UserInfo userInfo = sUserManager.getUserInfo(userId);
6165            return userInfo != null && userInfo.isEnabled();
6166        } finally {
6167            Binder.restoreCallingIdentity(callingId);
6168        }
6169    }
6170
6171    /**
6172     * Filter out activities with systemUserOnly flag set, when current user is not System.
6173     *
6174     * @return filtered list
6175     */
6176    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6177        if (userId == UserHandle.USER_SYSTEM) {
6178            return resolveInfos;
6179        }
6180        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6181            ResolveInfo info = resolveInfos.get(i);
6182            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6183                resolveInfos.remove(i);
6184            }
6185        }
6186        return resolveInfos;
6187    }
6188
6189    /**
6190     * Filters out ephemeral activities.
6191     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6192     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6193     *
6194     * @param resolveInfos The pre-filtered list of resolved activities
6195     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6196     *          is performed.
6197     * @return A filtered list of resolved activities.
6198     */
6199    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6200            String ephemeralPkgName) {
6201        if (ephemeralPkgName == null) {
6202            return resolveInfos;
6203        }
6204        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6205            ResolveInfo info = resolveInfos.get(i);
6206            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
6207            // allow activities that are defined in the provided package
6208            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6209                continue;
6210            }
6211            // allow activities that have been explicitly exposed to ephemeral apps
6212            if (!isEphemeralApp
6213                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6214                continue;
6215            }
6216            resolveInfos.remove(i);
6217        }
6218        return resolveInfos;
6219    }
6220
6221    /**
6222     * @param resolveInfos list of resolve infos in descending priority order
6223     * @return if the list contains a resolve info with non-negative priority
6224     */
6225    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6226        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6227    }
6228
6229    private static boolean hasWebURI(Intent intent) {
6230        if (intent.getData() == null) {
6231            return false;
6232        }
6233        final String scheme = intent.getScheme();
6234        if (TextUtils.isEmpty(scheme)) {
6235            return false;
6236        }
6237        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6238    }
6239
6240    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6241            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6242            int userId) {
6243        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6244
6245        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6246            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6247                    candidates.size());
6248        }
6249
6250        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6251        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6252        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6253        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6254        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6255        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6256
6257        synchronized (mPackages) {
6258            final int count = candidates.size();
6259            // First, try to use linked apps. Partition the candidates into four lists:
6260            // one for the final results, one for the "do not use ever", one for "undefined status"
6261            // and finally one for "browser app type".
6262            for (int n=0; n<count; n++) {
6263                ResolveInfo info = candidates.get(n);
6264                String packageName = info.activityInfo.packageName;
6265                PackageSetting ps = mSettings.mPackages.get(packageName);
6266                if (ps != null) {
6267                    // Add to the special match all list (Browser use case)
6268                    if (info.handleAllWebDataURI) {
6269                        matchAllList.add(info);
6270                        continue;
6271                    }
6272                    // Try to get the status from User settings first
6273                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6274                    int status = (int)(packedStatus >> 32);
6275                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6276                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6277                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6278                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6279                                    + " : linkgen=" + linkGeneration);
6280                        }
6281                        // Use link-enabled generation as preferredOrder, i.e.
6282                        // prefer newly-enabled over earlier-enabled.
6283                        info.preferredOrder = linkGeneration;
6284                        alwaysList.add(info);
6285                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6286                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6287                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6288                        }
6289                        neverList.add(info);
6290                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6291                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6292                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6293                        }
6294                        alwaysAskList.add(info);
6295                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6296                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6297                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6298                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6299                        }
6300                        undefinedList.add(info);
6301                    }
6302                }
6303            }
6304
6305            // We'll want to include browser possibilities in a few cases
6306            boolean includeBrowser = false;
6307
6308            // First try to add the "always" resolution(s) for the current user, if any
6309            if (alwaysList.size() > 0) {
6310                result.addAll(alwaysList);
6311            } else {
6312                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6313                result.addAll(undefinedList);
6314                // Maybe add one for the other profile.
6315                if (xpDomainInfo != null && (
6316                        xpDomainInfo.bestDomainVerificationStatus
6317                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6318                    result.add(xpDomainInfo.resolveInfo);
6319                }
6320                includeBrowser = true;
6321            }
6322
6323            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6324            // If there were 'always' entries their preferred order has been set, so we also
6325            // back that off to make the alternatives equivalent
6326            if (alwaysAskList.size() > 0) {
6327                for (ResolveInfo i : result) {
6328                    i.preferredOrder = 0;
6329                }
6330                result.addAll(alwaysAskList);
6331                includeBrowser = true;
6332            }
6333
6334            if (includeBrowser) {
6335                // Also add browsers (all of them or only the default one)
6336                if (DEBUG_DOMAIN_VERIFICATION) {
6337                    Slog.v(TAG, "   ...including browsers in candidate set");
6338                }
6339                if ((matchFlags & MATCH_ALL) != 0) {
6340                    result.addAll(matchAllList);
6341                } else {
6342                    // Browser/generic handling case.  If there's a default browser, go straight
6343                    // to that (but only if there is no other higher-priority match).
6344                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6345                    int maxMatchPrio = 0;
6346                    ResolveInfo defaultBrowserMatch = null;
6347                    final int numCandidates = matchAllList.size();
6348                    for (int n = 0; n < numCandidates; n++) {
6349                        ResolveInfo info = matchAllList.get(n);
6350                        // track the highest overall match priority...
6351                        if (info.priority > maxMatchPrio) {
6352                            maxMatchPrio = info.priority;
6353                        }
6354                        // ...and the highest-priority default browser match
6355                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6356                            if (defaultBrowserMatch == null
6357                                    || (defaultBrowserMatch.priority < info.priority)) {
6358                                if (debug) {
6359                                    Slog.v(TAG, "Considering default browser match " + info);
6360                                }
6361                                defaultBrowserMatch = info;
6362                            }
6363                        }
6364                    }
6365                    if (defaultBrowserMatch != null
6366                            && defaultBrowserMatch.priority >= maxMatchPrio
6367                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6368                    {
6369                        if (debug) {
6370                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6371                        }
6372                        result.add(defaultBrowserMatch);
6373                    } else {
6374                        result.addAll(matchAllList);
6375                    }
6376                }
6377
6378                // If there is nothing selected, add all candidates and remove the ones that the user
6379                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6380                if (result.size() == 0) {
6381                    result.addAll(candidates);
6382                    result.removeAll(neverList);
6383                }
6384            }
6385        }
6386        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6387            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6388                    result.size());
6389            for (ResolveInfo info : result) {
6390                Slog.v(TAG, "  + " + info.activityInfo);
6391            }
6392        }
6393        return result;
6394    }
6395
6396    // Returns a packed value as a long:
6397    //
6398    // high 'int'-sized word: link status: undefined/ask/never/always.
6399    // low 'int'-sized word: relative priority among 'always' results.
6400    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6401        long result = ps.getDomainVerificationStatusForUser(userId);
6402        // if none available, get the master status
6403        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6404            if (ps.getIntentFilterVerificationInfo() != null) {
6405                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6406            }
6407        }
6408        return result;
6409    }
6410
6411    private ResolveInfo querySkipCurrentProfileIntents(
6412            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6413            int flags, int sourceUserId) {
6414        if (matchingFilters != null) {
6415            int size = matchingFilters.size();
6416            for (int i = 0; i < size; i ++) {
6417                CrossProfileIntentFilter filter = matchingFilters.get(i);
6418                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6419                    // Checking if there are activities in the target user that can handle the
6420                    // intent.
6421                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6422                            resolvedType, flags, sourceUserId);
6423                    if (resolveInfo != null) {
6424                        return resolveInfo;
6425                    }
6426                }
6427            }
6428        }
6429        return null;
6430    }
6431
6432    // Return matching ResolveInfo in target user if any.
6433    private ResolveInfo queryCrossProfileIntents(
6434            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6435            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6436        if (matchingFilters != null) {
6437            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6438            // match the same intent. For performance reasons, it is better not to
6439            // run queryIntent twice for the same userId
6440            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6441            int size = matchingFilters.size();
6442            for (int i = 0; i < size; i++) {
6443                CrossProfileIntentFilter filter = matchingFilters.get(i);
6444                int targetUserId = filter.getTargetUserId();
6445                boolean skipCurrentProfile =
6446                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6447                boolean skipCurrentProfileIfNoMatchFound =
6448                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6449                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6450                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6451                    // Checking if there are activities in the target user that can handle the
6452                    // intent.
6453                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6454                            resolvedType, flags, sourceUserId);
6455                    if (resolveInfo != null) return resolveInfo;
6456                    alreadyTriedUserIds.put(targetUserId, true);
6457                }
6458            }
6459        }
6460        return null;
6461    }
6462
6463    /**
6464     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6465     * will forward the intent to the filter's target user.
6466     * Otherwise, returns null.
6467     */
6468    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6469            String resolvedType, int flags, int sourceUserId) {
6470        int targetUserId = filter.getTargetUserId();
6471        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6472                resolvedType, flags, targetUserId);
6473        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6474            // If all the matches in the target profile are suspended, return null.
6475            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6476                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6477                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6478                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6479                            targetUserId);
6480                }
6481            }
6482        }
6483        return null;
6484    }
6485
6486    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6487            int sourceUserId, int targetUserId) {
6488        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6489        long ident = Binder.clearCallingIdentity();
6490        boolean targetIsProfile;
6491        try {
6492            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6493        } finally {
6494            Binder.restoreCallingIdentity(ident);
6495        }
6496        String className;
6497        if (targetIsProfile) {
6498            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6499        } else {
6500            className = FORWARD_INTENT_TO_PARENT;
6501        }
6502        ComponentName forwardingActivityComponentName = new ComponentName(
6503                mAndroidApplication.packageName, className);
6504        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6505                sourceUserId);
6506        if (!targetIsProfile) {
6507            forwardingActivityInfo.showUserIcon = targetUserId;
6508            forwardingResolveInfo.noResourceId = true;
6509        }
6510        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6511        forwardingResolveInfo.priority = 0;
6512        forwardingResolveInfo.preferredOrder = 0;
6513        forwardingResolveInfo.match = 0;
6514        forwardingResolveInfo.isDefault = true;
6515        forwardingResolveInfo.filter = filter;
6516        forwardingResolveInfo.targetUserId = targetUserId;
6517        return forwardingResolveInfo;
6518    }
6519
6520    @Override
6521    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6522            Intent[] specifics, String[] specificTypes, Intent intent,
6523            String resolvedType, int flags, int userId) {
6524        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6525                specificTypes, intent, resolvedType, flags, userId));
6526    }
6527
6528    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6529            Intent[] specifics, String[] specificTypes, Intent intent,
6530            String resolvedType, int flags, int userId) {
6531        if (!sUserManager.exists(userId)) return Collections.emptyList();
6532        flags = updateFlagsForResolve(flags, userId, intent);
6533        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6534                false /* requireFullPermission */, false /* checkShell */,
6535                "query intent activity options");
6536        final String resultsAction = intent.getAction();
6537
6538        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6539                | PackageManager.GET_RESOLVED_FILTER, userId);
6540
6541        if (DEBUG_INTENT_MATCHING) {
6542            Log.v(TAG, "Query " + intent + ": " + results);
6543        }
6544
6545        int specificsPos = 0;
6546        int N;
6547
6548        // todo: note that the algorithm used here is O(N^2).  This
6549        // isn't a problem in our current environment, but if we start running
6550        // into situations where we have more than 5 or 10 matches then this
6551        // should probably be changed to something smarter...
6552
6553        // First we go through and resolve each of the specific items
6554        // that were supplied, taking care of removing any corresponding
6555        // duplicate items in the generic resolve list.
6556        if (specifics != null) {
6557            for (int i=0; i<specifics.length; i++) {
6558                final Intent sintent = specifics[i];
6559                if (sintent == null) {
6560                    continue;
6561                }
6562
6563                if (DEBUG_INTENT_MATCHING) {
6564                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6565                }
6566
6567                String action = sintent.getAction();
6568                if (resultsAction != null && resultsAction.equals(action)) {
6569                    // If this action was explicitly requested, then don't
6570                    // remove things that have it.
6571                    action = null;
6572                }
6573
6574                ResolveInfo ri = null;
6575                ActivityInfo ai = null;
6576
6577                ComponentName comp = sintent.getComponent();
6578                if (comp == null) {
6579                    ri = resolveIntent(
6580                        sintent,
6581                        specificTypes != null ? specificTypes[i] : null,
6582                            flags, userId);
6583                    if (ri == null) {
6584                        continue;
6585                    }
6586                    if (ri == mResolveInfo) {
6587                        // ACK!  Must do something better with this.
6588                    }
6589                    ai = ri.activityInfo;
6590                    comp = new ComponentName(ai.applicationInfo.packageName,
6591                            ai.name);
6592                } else {
6593                    ai = getActivityInfo(comp, flags, userId);
6594                    if (ai == null) {
6595                        continue;
6596                    }
6597                }
6598
6599                // Look for any generic query activities that are duplicates
6600                // of this specific one, and remove them from the results.
6601                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6602                N = results.size();
6603                int j;
6604                for (j=specificsPos; j<N; j++) {
6605                    ResolveInfo sri = results.get(j);
6606                    if ((sri.activityInfo.name.equals(comp.getClassName())
6607                            && sri.activityInfo.applicationInfo.packageName.equals(
6608                                    comp.getPackageName()))
6609                        || (action != null && sri.filter.matchAction(action))) {
6610                        results.remove(j);
6611                        if (DEBUG_INTENT_MATCHING) Log.v(
6612                            TAG, "Removing duplicate item from " + j
6613                            + " due to specific " + specificsPos);
6614                        if (ri == null) {
6615                            ri = sri;
6616                        }
6617                        j--;
6618                        N--;
6619                    }
6620                }
6621
6622                // Add this specific item to its proper place.
6623                if (ri == null) {
6624                    ri = new ResolveInfo();
6625                    ri.activityInfo = ai;
6626                }
6627                results.add(specificsPos, ri);
6628                ri.specificIndex = i;
6629                specificsPos++;
6630            }
6631        }
6632
6633        // Now we go through the remaining generic results and remove any
6634        // duplicate actions that are found here.
6635        N = results.size();
6636        for (int i=specificsPos; i<N-1; i++) {
6637            final ResolveInfo rii = results.get(i);
6638            if (rii.filter == null) {
6639                continue;
6640            }
6641
6642            // Iterate over all of the actions of this result's intent
6643            // filter...  typically this should be just one.
6644            final Iterator<String> it = rii.filter.actionsIterator();
6645            if (it == null) {
6646                continue;
6647            }
6648            while (it.hasNext()) {
6649                final String action = it.next();
6650                if (resultsAction != null && resultsAction.equals(action)) {
6651                    // If this action was explicitly requested, then don't
6652                    // remove things that have it.
6653                    continue;
6654                }
6655                for (int j=i+1; j<N; j++) {
6656                    final ResolveInfo rij = results.get(j);
6657                    if (rij.filter != null && rij.filter.hasAction(action)) {
6658                        results.remove(j);
6659                        if (DEBUG_INTENT_MATCHING) Log.v(
6660                            TAG, "Removing duplicate item from " + j
6661                            + " due to action " + action + " at " + i);
6662                        j--;
6663                        N--;
6664                    }
6665                }
6666            }
6667
6668            // If the caller didn't request filter information, drop it now
6669            // so we don't have to marshall/unmarshall it.
6670            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6671                rii.filter = null;
6672            }
6673        }
6674
6675        // Filter out the caller activity if so requested.
6676        if (caller != null) {
6677            N = results.size();
6678            for (int i=0; i<N; i++) {
6679                ActivityInfo ainfo = results.get(i).activityInfo;
6680                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6681                        && caller.getClassName().equals(ainfo.name)) {
6682                    results.remove(i);
6683                    break;
6684                }
6685            }
6686        }
6687
6688        // If the caller didn't request filter information,
6689        // drop them now so we don't have to
6690        // marshall/unmarshall it.
6691        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6692            N = results.size();
6693            for (int i=0; i<N; i++) {
6694                results.get(i).filter = null;
6695            }
6696        }
6697
6698        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6699        return results;
6700    }
6701
6702    @Override
6703    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6704            String resolvedType, int flags, int userId) {
6705        return new ParceledListSlice<>(
6706                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6707    }
6708
6709    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6710            String resolvedType, int flags, int userId) {
6711        if (!sUserManager.exists(userId)) return Collections.emptyList();
6712        flags = updateFlagsForResolve(flags, userId, intent);
6713        ComponentName comp = intent.getComponent();
6714        if (comp == null) {
6715            if (intent.getSelector() != null) {
6716                intent = intent.getSelector();
6717                comp = intent.getComponent();
6718            }
6719        }
6720        if (comp != null) {
6721            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6722            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6723            if (ai != null) {
6724                ResolveInfo ri = new ResolveInfo();
6725                ri.activityInfo = ai;
6726                list.add(ri);
6727            }
6728            return list;
6729        }
6730
6731        // reader
6732        synchronized (mPackages) {
6733            String pkgName = intent.getPackage();
6734            if (pkgName == null) {
6735                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6736            }
6737            final PackageParser.Package pkg = mPackages.get(pkgName);
6738            if (pkg != null) {
6739                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6740                        userId);
6741            }
6742            return Collections.emptyList();
6743        }
6744    }
6745
6746    @Override
6747    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6748        if (!sUserManager.exists(userId)) return null;
6749        flags = updateFlagsForResolve(flags, userId, intent);
6750        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6751        if (query != null) {
6752            if (query.size() >= 1) {
6753                // If there is more than one service with the same priority,
6754                // just arbitrarily pick the first one.
6755                return query.get(0);
6756            }
6757        }
6758        return null;
6759    }
6760
6761    @Override
6762    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6763            String resolvedType, int flags, int userId) {
6764        return new ParceledListSlice<>(
6765                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6766    }
6767
6768    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6769            String resolvedType, int flags, int userId) {
6770        if (!sUserManager.exists(userId)) return Collections.emptyList();
6771        flags = updateFlagsForResolve(flags, userId, intent);
6772        ComponentName comp = intent.getComponent();
6773        if (comp == null) {
6774            if (intent.getSelector() != null) {
6775                intent = intent.getSelector();
6776                comp = intent.getComponent();
6777            }
6778        }
6779        if (comp != null) {
6780            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6781            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6782            if (si != null) {
6783                final ResolveInfo ri = new ResolveInfo();
6784                ri.serviceInfo = si;
6785                list.add(ri);
6786            }
6787            return list;
6788        }
6789
6790        // reader
6791        synchronized (mPackages) {
6792            String pkgName = intent.getPackage();
6793            if (pkgName == null) {
6794                return mServices.queryIntent(intent, resolvedType, flags, userId);
6795            }
6796            final PackageParser.Package pkg = mPackages.get(pkgName);
6797            if (pkg != null) {
6798                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6799                        userId);
6800            }
6801            return Collections.emptyList();
6802        }
6803    }
6804
6805    @Override
6806    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6807            String resolvedType, int flags, int userId) {
6808        return new ParceledListSlice<>(
6809                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6810    }
6811
6812    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6813            Intent intent, String resolvedType, int flags, int userId) {
6814        if (!sUserManager.exists(userId)) return Collections.emptyList();
6815        flags = updateFlagsForResolve(flags, userId, intent);
6816        ComponentName comp = intent.getComponent();
6817        if (comp == null) {
6818            if (intent.getSelector() != null) {
6819                intent = intent.getSelector();
6820                comp = intent.getComponent();
6821            }
6822        }
6823        if (comp != null) {
6824            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6825            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6826            if (pi != null) {
6827                final ResolveInfo ri = new ResolveInfo();
6828                ri.providerInfo = pi;
6829                list.add(ri);
6830            }
6831            return list;
6832        }
6833
6834        // reader
6835        synchronized (mPackages) {
6836            String pkgName = intent.getPackage();
6837            if (pkgName == null) {
6838                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6839            }
6840            final PackageParser.Package pkg = mPackages.get(pkgName);
6841            if (pkg != null) {
6842                return mProviders.queryIntentForPackage(
6843                        intent, resolvedType, flags, pkg.providers, userId);
6844            }
6845            return Collections.emptyList();
6846        }
6847    }
6848
6849    @Override
6850    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6851        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6852        flags = updateFlagsForPackage(flags, userId, null);
6853        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6854        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6855                true /* requireFullPermission */, false /* checkShell */,
6856                "get installed packages");
6857
6858        // writer
6859        synchronized (mPackages) {
6860            ArrayList<PackageInfo> list;
6861            if (listUninstalled) {
6862                list = new ArrayList<>(mSettings.mPackages.size());
6863                for (PackageSetting ps : mSettings.mPackages.values()) {
6864                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6865                        continue;
6866                    }
6867                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6868                    if (pi != null) {
6869                        list.add(pi);
6870                    }
6871                }
6872            } else {
6873                list = new ArrayList<>(mPackages.size());
6874                for (PackageParser.Package p : mPackages.values()) {
6875                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6876                            Binder.getCallingUid(), userId)) {
6877                        continue;
6878                    }
6879                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6880                            p.mExtras, flags, userId);
6881                    if (pi != null) {
6882                        list.add(pi);
6883                    }
6884                }
6885            }
6886
6887            return new ParceledListSlice<>(list);
6888        }
6889    }
6890
6891    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6892            String[] permissions, boolean[] tmp, int flags, int userId) {
6893        int numMatch = 0;
6894        final PermissionsState permissionsState = ps.getPermissionsState();
6895        for (int i=0; i<permissions.length; i++) {
6896            final String permission = permissions[i];
6897            if (permissionsState.hasPermission(permission, userId)) {
6898                tmp[i] = true;
6899                numMatch++;
6900            } else {
6901                tmp[i] = false;
6902            }
6903        }
6904        if (numMatch == 0) {
6905            return;
6906        }
6907        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6908
6909        // The above might return null in cases of uninstalled apps or install-state
6910        // skew across users/profiles.
6911        if (pi != null) {
6912            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6913                if (numMatch == permissions.length) {
6914                    pi.requestedPermissions = permissions;
6915                } else {
6916                    pi.requestedPermissions = new String[numMatch];
6917                    numMatch = 0;
6918                    for (int i=0; i<permissions.length; i++) {
6919                        if (tmp[i]) {
6920                            pi.requestedPermissions[numMatch] = permissions[i];
6921                            numMatch++;
6922                        }
6923                    }
6924                }
6925            }
6926            list.add(pi);
6927        }
6928    }
6929
6930    @Override
6931    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6932            String[] permissions, int flags, int userId) {
6933        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6934        flags = updateFlagsForPackage(flags, userId, permissions);
6935        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6936                true /* requireFullPermission */, false /* checkShell */,
6937                "get packages holding permissions");
6938        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6939
6940        // writer
6941        synchronized (mPackages) {
6942            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6943            boolean[] tmpBools = new boolean[permissions.length];
6944            if (listUninstalled) {
6945                for (PackageSetting ps : mSettings.mPackages.values()) {
6946                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6947                            userId);
6948                }
6949            } else {
6950                for (PackageParser.Package pkg : mPackages.values()) {
6951                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6952                    if (ps != null) {
6953                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6954                                userId);
6955                    }
6956                }
6957            }
6958
6959            return new ParceledListSlice<PackageInfo>(list);
6960        }
6961    }
6962
6963    @Override
6964    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6965        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6966        flags = updateFlagsForApplication(flags, userId, null);
6967        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6968
6969        // writer
6970        synchronized (mPackages) {
6971            ArrayList<ApplicationInfo> list;
6972            if (listUninstalled) {
6973                list = new ArrayList<>(mSettings.mPackages.size());
6974                for (PackageSetting ps : mSettings.mPackages.values()) {
6975                    ApplicationInfo ai;
6976                    int effectiveFlags = flags;
6977                    if (ps.isSystem()) {
6978                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6979                    }
6980                    if (ps.pkg != null) {
6981                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6982                            continue;
6983                        }
6984                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6985                                ps.readUserState(userId), userId);
6986                        if (ai != null) {
6987                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
6988                        }
6989                    } else {
6990                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
6991                        // and already converts to externally visible package name
6992                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
6993                                Binder.getCallingUid(), effectiveFlags, userId);
6994                    }
6995                    if (ai != null) {
6996                        list.add(ai);
6997                    }
6998                }
6999            } else {
7000                list = new ArrayList<>(mPackages.size());
7001                for (PackageParser.Package p : mPackages.values()) {
7002                    if (p.mExtras != null) {
7003                        PackageSetting ps = (PackageSetting) p.mExtras;
7004                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7005                            continue;
7006                        }
7007                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7008                                ps.readUserState(userId), userId);
7009                        if (ai != null) {
7010                            ai.packageName = resolveExternalPackageNameLPr(p);
7011                            list.add(ai);
7012                        }
7013                    }
7014                }
7015            }
7016
7017            return new ParceledListSlice<>(list);
7018        }
7019    }
7020
7021    @Override
7022    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
7023        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7024            return null;
7025        }
7026
7027        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
7028                "getEphemeralApplications");
7029        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7030                true /* requireFullPermission */, false /* checkShell */,
7031                "getEphemeralApplications");
7032        synchronized (mPackages) {
7033            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
7034                    .getEphemeralApplicationsLPw(userId);
7035            if (ephemeralApps != null) {
7036                return new ParceledListSlice<>(ephemeralApps);
7037            }
7038        }
7039        return null;
7040    }
7041
7042    @Override
7043    public boolean isEphemeralApplication(String packageName, int userId) {
7044        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7045                true /* requireFullPermission */, false /* checkShell */,
7046                "isEphemeral");
7047        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7048            return false;
7049        }
7050
7051        if (!isCallerSameApp(packageName)) {
7052            return false;
7053        }
7054        synchronized (mPackages) {
7055            PackageParser.Package pkg = mPackages.get(packageName);
7056            if (pkg != null) {
7057                return pkg.applicationInfo.isEphemeralApp();
7058            }
7059        }
7060        return false;
7061    }
7062
7063    @Override
7064    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
7065        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7066            return null;
7067        }
7068
7069        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7070                true /* requireFullPermission */, false /* checkShell */,
7071                "getCookie");
7072        if (!isCallerSameApp(packageName)) {
7073            return null;
7074        }
7075        synchronized (mPackages) {
7076            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
7077                    packageName, userId);
7078        }
7079    }
7080
7081    @Override
7082    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
7083        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7084            return true;
7085        }
7086
7087        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7088                true /* requireFullPermission */, true /* checkShell */,
7089                "setCookie");
7090        if (!isCallerSameApp(packageName)) {
7091            return false;
7092        }
7093        synchronized (mPackages) {
7094            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
7095                    packageName, cookie, userId);
7096        }
7097    }
7098
7099    @Override
7100    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
7101        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7102            return null;
7103        }
7104
7105        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
7106                "getEphemeralApplicationIcon");
7107
7108        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7109                true /* requireFullPermission */, false /* checkShell */,
7110                "getEphemeralApplicationIcon");
7111        synchronized (mPackages) {
7112            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
7113                    packageName, userId);
7114        }
7115    }
7116
7117    private boolean isCallerSameApp(String packageName) {
7118        PackageParser.Package pkg = mPackages.get(packageName);
7119        return pkg != null
7120                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7121    }
7122
7123    @Override
7124    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7125        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7126    }
7127
7128    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7129        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7130
7131        // reader
7132        synchronized (mPackages) {
7133            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7134            final int userId = UserHandle.getCallingUserId();
7135            while (i.hasNext()) {
7136                final PackageParser.Package p = i.next();
7137                if (p.applicationInfo == null) continue;
7138
7139                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7140                        && !p.applicationInfo.isDirectBootAware();
7141                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7142                        && p.applicationInfo.isDirectBootAware();
7143
7144                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7145                        && (!mSafeMode || isSystemApp(p))
7146                        && (matchesUnaware || matchesAware)) {
7147                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7148                    if (ps != null) {
7149                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7150                                ps.readUserState(userId), userId);
7151                        if (ai != null) {
7152                            finalList.add(ai);
7153                        }
7154                    }
7155                }
7156            }
7157        }
7158
7159        return finalList;
7160    }
7161
7162    @Override
7163    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7164        if (!sUserManager.exists(userId)) return null;
7165        flags = updateFlagsForComponent(flags, userId, name);
7166        // reader
7167        synchronized (mPackages) {
7168            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7169            PackageSetting ps = provider != null
7170                    ? mSettings.mPackages.get(provider.owner.packageName)
7171                    : null;
7172            return ps != null
7173                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7174                    ? PackageParser.generateProviderInfo(provider, flags,
7175                            ps.readUserState(userId), userId)
7176                    : null;
7177        }
7178    }
7179
7180    /**
7181     * @deprecated
7182     */
7183    @Deprecated
7184    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7185        // reader
7186        synchronized (mPackages) {
7187            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7188                    .entrySet().iterator();
7189            final int userId = UserHandle.getCallingUserId();
7190            while (i.hasNext()) {
7191                Map.Entry<String, PackageParser.Provider> entry = i.next();
7192                PackageParser.Provider p = entry.getValue();
7193                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7194
7195                if (ps != null && p.syncable
7196                        && (!mSafeMode || (p.info.applicationInfo.flags
7197                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7198                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7199                            ps.readUserState(userId), userId);
7200                    if (info != null) {
7201                        outNames.add(entry.getKey());
7202                        outInfo.add(info);
7203                    }
7204                }
7205            }
7206        }
7207    }
7208
7209    @Override
7210    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7211            int uid, int flags) {
7212        final int userId = processName != null ? UserHandle.getUserId(uid)
7213                : UserHandle.getCallingUserId();
7214        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7215        flags = updateFlagsForComponent(flags, userId, processName);
7216
7217        ArrayList<ProviderInfo> finalList = null;
7218        // reader
7219        synchronized (mPackages) {
7220            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7221            while (i.hasNext()) {
7222                final PackageParser.Provider p = i.next();
7223                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7224                if (ps != null && p.info.authority != null
7225                        && (processName == null
7226                                || (p.info.processName.equals(processName)
7227                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7228                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7229                    if (finalList == null) {
7230                        finalList = new ArrayList<ProviderInfo>(3);
7231                    }
7232                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7233                            ps.readUserState(userId), userId);
7234                    if (info != null) {
7235                        finalList.add(info);
7236                    }
7237                }
7238            }
7239        }
7240
7241        if (finalList != null) {
7242            Collections.sort(finalList, mProviderInitOrderSorter);
7243            return new ParceledListSlice<ProviderInfo>(finalList);
7244        }
7245
7246        return ParceledListSlice.emptyList();
7247    }
7248
7249    @Override
7250    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7251        // reader
7252        synchronized (mPackages) {
7253            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7254            return PackageParser.generateInstrumentationInfo(i, flags);
7255        }
7256    }
7257
7258    @Override
7259    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7260            String targetPackage, int flags) {
7261        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7262    }
7263
7264    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7265            int flags) {
7266        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7267
7268        // reader
7269        synchronized (mPackages) {
7270            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7271            while (i.hasNext()) {
7272                final PackageParser.Instrumentation p = i.next();
7273                if (targetPackage == null
7274                        || targetPackage.equals(p.info.targetPackage)) {
7275                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7276                            flags);
7277                    if (ii != null) {
7278                        finalList.add(ii);
7279                    }
7280                }
7281            }
7282        }
7283
7284        return finalList;
7285    }
7286
7287    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7288        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7289        if (overlays == null) {
7290            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7291            return;
7292        }
7293        for (PackageParser.Package opkg : overlays.values()) {
7294            // Not much to do if idmap fails: we already logged the error
7295            // and we certainly don't want to abort installation of pkg simply
7296            // because an overlay didn't fit properly. For these reasons,
7297            // ignore the return value of createIdmapForPackagePairLI.
7298            createIdmapForPackagePairLI(pkg, opkg);
7299        }
7300    }
7301
7302    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7303            PackageParser.Package opkg) {
7304        if (!opkg.mTrustedOverlay) {
7305            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7306                    opkg.baseCodePath + ": overlay not trusted");
7307            return false;
7308        }
7309        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7310        if (overlaySet == null) {
7311            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7312                    opkg.baseCodePath + " but target package has no known overlays");
7313            return false;
7314        }
7315        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7316        // TODO: generate idmap for split APKs
7317        try {
7318            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7319        } catch (InstallerException e) {
7320            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7321                    + opkg.baseCodePath);
7322            return false;
7323        }
7324        PackageParser.Package[] overlayArray =
7325            overlaySet.values().toArray(new PackageParser.Package[0]);
7326        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7327            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7328                return p1.mOverlayPriority - p2.mOverlayPriority;
7329            }
7330        };
7331        Arrays.sort(overlayArray, cmp);
7332
7333        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7334        int i = 0;
7335        for (PackageParser.Package p : overlayArray) {
7336            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7337        }
7338        return true;
7339    }
7340
7341    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7342        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7343        try {
7344            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7345        } finally {
7346            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7347        }
7348    }
7349
7350    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7351        final File[] files = dir.listFiles();
7352        if (ArrayUtils.isEmpty(files)) {
7353            Log.d(TAG, "No files in app dir " + dir);
7354            return;
7355        }
7356
7357        if (DEBUG_PACKAGE_SCANNING) {
7358            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7359                    + " flags=0x" + Integer.toHexString(parseFlags));
7360        }
7361        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7362                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7363
7364        // Submit files for parsing in parallel
7365        int fileCount = 0;
7366        for (File file : files) {
7367            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7368                    && !PackageInstallerService.isStageName(file.getName());
7369            if (!isPackage) {
7370                // Ignore entries which are not packages
7371                continue;
7372            }
7373            parallelPackageParser.submit(file, parseFlags);
7374            fileCount++;
7375        }
7376
7377        // Process results one by one
7378        for (; fileCount > 0; fileCount--) {
7379            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7380            Throwable throwable = parseResult.throwable;
7381            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7382
7383            if (throwable == null) {
7384                // Static shared libraries have synthetic package names
7385                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7386                    renameStaticSharedLibraryPackage(parseResult.pkg);
7387                }
7388                try {
7389                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7390                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7391                                currentTime, null);
7392                    }
7393                } catch (PackageManagerException e) {
7394                    errorCode = e.error;
7395                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7396                }
7397            } else if (throwable instanceof PackageParser.PackageParserException) {
7398                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7399                        throwable;
7400                errorCode = e.error;
7401                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7402            } else {
7403                throw new IllegalStateException("Unexpected exception occurred while parsing "
7404                        + parseResult.scanFile, throwable);
7405            }
7406
7407            // Delete invalid userdata apps
7408            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7409                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7410                logCriticalInfo(Log.WARN,
7411                        "Deleting invalid package at " + parseResult.scanFile);
7412                removeCodePathLI(parseResult.scanFile);
7413            }
7414        }
7415        parallelPackageParser.close();
7416    }
7417
7418    private static File getSettingsProblemFile() {
7419        File dataDir = Environment.getDataDirectory();
7420        File systemDir = new File(dataDir, "system");
7421        File fname = new File(systemDir, "uiderrors.txt");
7422        return fname;
7423    }
7424
7425    static void reportSettingsProblem(int priority, String msg) {
7426        logCriticalInfo(priority, msg);
7427    }
7428
7429    static void logCriticalInfo(int priority, String msg) {
7430        Slog.println(priority, TAG, msg);
7431        EventLogTags.writePmCriticalInfo(msg);
7432        try {
7433            File fname = getSettingsProblemFile();
7434            FileOutputStream out = new FileOutputStream(fname, true);
7435            PrintWriter pw = new FastPrintWriter(out);
7436            SimpleDateFormat formatter = new SimpleDateFormat();
7437            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7438            pw.println(dateString + ": " + msg);
7439            pw.close();
7440            FileUtils.setPermissions(
7441                    fname.toString(),
7442                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7443                    -1, -1);
7444        } catch (java.io.IOException e) {
7445        }
7446    }
7447
7448    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7449        if (srcFile.isDirectory()) {
7450            final File baseFile = new File(pkg.baseCodePath);
7451            long maxModifiedTime = baseFile.lastModified();
7452            if (pkg.splitCodePaths != null) {
7453                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7454                    final File splitFile = new File(pkg.splitCodePaths[i]);
7455                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7456                }
7457            }
7458            return maxModifiedTime;
7459        }
7460        return srcFile.lastModified();
7461    }
7462
7463    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7464            final int policyFlags) throws PackageManagerException {
7465        // When upgrading from pre-N MR1, verify the package time stamp using the package
7466        // directory and not the APK file.
7467        final long lastModifiedTime = mIsPreNMR1Upgrade
7468                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7469        if (ps != null
7470                && ps.codePath.equals(srcFile)
7471                && ps.timeStamp == lastModifiedTime
7472                && !isCompatSignatureUpdateNeeded(pkg)
7473                && !isRecoverSignatureUpdateNeeded(pkg)) {
7474            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7475            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7476            ArraySet<PublicKey> signingKs;
7477            synchronized (mPackages) {
7478                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7479            }
7480            if (ps.signatures.mSignatures != null
7481                    && ps.signatures.mSignatures.length != 0
7482                    && signingKs != null) {
7483                // Optimization: reuse the existing cached certificates
7484                // if the package appears to be unchanged.
7485                pkg.mSignatures = ps.signatures.mSignatures;
7486                pkg.mSigningKeys = signingKs;
7487                return;
7488            }
7489
7490            Slog.w(TAG, "PackageSetting for " + ps.name
7491                    + " is missing signatures.  Collecting certs again to recover them.");
7492        } else {
7493            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7494        }
7495
7496        try {
7497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7498            PackageParser.collectCertificates(pkg, policyFlags);
7499        } catch (PackageParserException e) {
7500            throw PackageManagerException.from(e);
7501        } finally {
7502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7503        }
7504    }
7505
7506    /**
7507     *  Traces a package scan.
7508     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7509     */
7510    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7511            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7512        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7513        try {
7514            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7515        } finally {
7516            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7517        }
7518    }
7519
7520    /**
7521     *  Scans a package and returns the newly parsed package.
7522     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7523     */
7524    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7525            long currentTime, UserHandle user) throws PackageManagerException {
7526        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7527        PackageParser pp = new PackageParser();
7528        pp.setSeparateProcesses(mSeparateProcesses);
7529        pp.setOnlyCoreApps(mOnlyCore);
7530        pp.setDisplayMetrics(mMetrics);
7531
7532        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7533            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7534        }
7535
7536        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7537        final PackageParser.Package pkg;
7538        try {
7539            pkg = pp.parsePackage(scanFile, parseFlags);
7540        } catch (PackageParserException e) {
7541            throw PackageManagerException.from(e);
7542        } finally {
7543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7544        }
7545
7546        // Static shared libraries have synthetic package names
7547        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7548            renameStaticSharedLibraryPackage(pkg);
7549        }
7550
7551        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7552    }
7553
7554    /**
7555     *  Scans a package and returns the newly parsed package.
7556     *  @throws PackageManagerException on a parse error.
7557     */
7558    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7559            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7560            throws PackageManagerException {
7561        // If the package has children and this is the first dive in the function
7562        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7563        // packages (parent and children) would be successfully scanned before the
7564        // actual scan since scanning mutates internal state and we want to atomically
7565        // install the package and its children.
7566        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7567            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7568                scanFlags |= SCAN_CHECK_ONLY;
7569            }
7570        } else {
7571            scanFlags &= ~SCAN_CHECK_ONLY;
7572        }
7573
7574        // Scan the parent
7575        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7576                scanFlags, currentTime, user);
7577
7578        // Scan the children
7579        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7580        for (int i = 0; i < childCount; i++) {
7581            PackageParser.Package childPackage = pkg.childPackages.get(i);
7582            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7583                    currentTime, user);
7584        }
7585
7586
7587        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7588            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7589        }
7590
7591        return scannedPkg;
7592    }
7593
7594    /**
7595     *  Scans a package and returns the newly parsed package.
7596     *  @throws PackageManagerException on a parse error.
7597     */
7598    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7599            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7600            throws PackageManagerException {
7601        PackageSetting ps = null;
7602        PackageSetting updatedPkg;
7603        // reader
7604        synchronized (mPackages) {
7605            // Look to see if we already know about this package.
7606            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7607            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7608                // This package has been renamed to its original name.  Let's
7609                // use that.
7610                ps = mSettings.getPackageLPr(oldName);
7611            }
7612            // If there was no original package, see one for the real package name.
7613            if (ps == null) {
7614                ps = mSettings.getPackageLPr(pkg.packageName);
7615            }
7616            // Check to see if this package could be hiding/updating a system
7617            // package.  Must look for it either under the original or real
7618            // package name depending on our state.
7619            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7620            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7621
7622            // If this is a package we don't know about on the system partition, we
7623            // may need to remove disabled child packages on the system partition
7624            // or may need to not add child packages if the parent apk is updated
7625            // on the data partition and no longer defines this child package.
7626            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7627                // If this is a parent package for an updated system app and this system
7628                // app got an OTA update which no longer defines some of the child packages
7629                // we have to prune them from the disabled system packages.
7630                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7631                if (disabledPs != null) {
7632                    final int scannedChildCount = (pkg.childPackages != null)
7633                            ? pkg.childPackages.size() : 0;
7634                    final int disabledChildCount = disabledPs.childPackageNames != null
7635                            ? disabledPs.childPackageNames.size() : 0;
7636                    for (int i = 0; i < disabledChildCount; i++) {
7637                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7638                        boolean disabledPackageAvailable = false;
7639                        for (int j = 0; j < scannedChildCount; j++) {
7640                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7641                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7642                                disabledPackageAvailable = true;
7643                                break;
7644                            }
7645                         }
7646                         if (!disabledPackageAvailable) {
7647                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7648                         }
7649                    }
7650                }
7651            }
7652        }
7653
7654        boolean updatedPkgBetter = false;
7655        // First check if this is a system package that may involve an update
7656        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7657            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7658            // it needs to drop FLAG_PRIVILEGED.
7659            if (locationIsPrivileged(scanFile)) {
7660                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7661            } else {
7662                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7663            }
7664
7665            if (ps != null && !ps.codePath.equals(scanFile)) {
7666                // The path has changed from what was last scanned...  check the
7667                // version of the new path against what we have stored to determine
7668                // what to do.
7669                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7670                if (pkg.mVersionCode <= ps.versionCode) {
7671                    // The system package has been updated and the code path does not match
7672                    // Ignore entry. Skip it.
7673                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7674                            + " ignored: updated version " + ps.versionCode
7675                            + " better than this " + pkg.mVersionCode);
7676                    if (!updatedPkg.codePath.equals(scanFile)) {
7677                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7678                                + ps.name + " changing from " + updatedPkg.codePathString
7679                                + " to " + scanFile);
7680                        updatedPkg.codePath = scanFile;
7681                        updatedPkg.codePathString = scanFile.toString();
7682                        updatedPkg.resourcePath = scanFile;
7683                        updatedPkg.resourcePathString = scanFile.toString();
7684                    }
7685                    updatedPkg.pkg = pkg;
7686                    updatedPkg.versionCode = pkg.mVersionCode;
7687
7688                    // Update the disabled system child packages to point to the package too.
7689                    final int childCount = updatedPkg.childPackageNames != null
7690                            ? updatedPkg.childPackageNames.size() : 0;
7691                    for (int i = 0; i < childCount; i++) {
7692                        String childPackageName = updatedPkg.childPackageNames.get(i);
7693                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7694                                childPackageName);
7695                        if (updatedChildPkg != null) {
7696                            updatedChildPkg.pkg = pkg;
7697                            updatedChildPkg.versionCode = pkg.mVersionCode;
7698                        }
7699                    }
7700
7701                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7702                            + scanFile + " ignored: updated version " + ps.versionCode
7703                            + " better than this " + pkg.mVersionCode);
7704                } else {
7705                    // The current app on the system partition is better than
7706                    // what we have updated to on the data partition; switch
7707                    // back to the system partition version.
7708                    // At this point, its safely assumed that package installation for
7709                    // apps in system partition will go through. If not there won't be a working
7710                    // version of the app
7711                    // writer
7712                    synchronized (mPackages) {
7713                        // Just remove the loaded entries from package lists.
7714                        mPackages.remove(ps.name);
7715                    }
7716
7717                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7718                            + " reverting from " + ps.codePathString
7719                            + ": new version " + pkg.mVersionCode
7720                            + " better than installed " + ps.versionCode);
7721
7722                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7723                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7724                    synchronized (mInstallLock) {
7725                        args.cleanUpResourcesLI();
7726                    }
7727                    synchronized (mPackages) {
7728                        mSettings.enableSystemPackageLPw(ps.name);
7729                    }
7730                    updatedPkgBetter = true;
7731                }
7732            }
7733        }
7734
7735        if (updatedPkg != null) {
7736            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7737            // initially
7738            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7739
7740            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7741            // flag set initially
7742            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7743                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7744            }
7745        }
7746
7747        // Verify certificates against what was last scanned
7748        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7749
7750        /*
7751         * A new system app appeared, but we already had a non-system one of the
7752         * same name installed earlier.
7753         */
7754        boolean shouldHideSystemApp = false;
7755        if (updatedPkg == null && ps != null
7756                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7757            /*
7758             * Check to make sure the signatures match first. If they don't,
7759             * wipe the installed application and its data.
7760             */
7761            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7762                    != PackageManager.SIGNATURE_MATCH) {
7763                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7764                        + " signatures don't match existing userdata copy; removing");
7765                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7766                        "scanPackageInternalLI")) {
7767                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7768                }
7769                ps = null;
7770            } else {
7771                /*
7772                 * If the newly-added system app is an older version than the
7773                 * already installed version, hide it. It will be scanned later
7774                 * and re-added like an update.
7775                 */
7776                if (pkg.mVersionCode <= ps.versionCode) {
7777                    shouldHideSystemApp = true;
7778                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7779                            + " but new version " + pkg.mVersionCode + " better than installed "
7780                            + ps.versionCode + "; hiding system");
7781                } else {
7782                    /*
7783                     * The newly found system app is a newer version that the
7784                     * one previously installed. Simply remove the
7785                     * already-installed application and replace it with our own
7786                     * while keeping the application data.
7787                     */
7788                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7789                            + " reverting from " + ps.codePathString + ": new version "
7790                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7791                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7792                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7793                    synchronized (mInstallLock) {
7794                        args.cleanUpResourcesLI();
7795                    }
7796                }
7797            }
7798        }
7799
7800        // The apk is forward locked (not public) if its code and resources
7801        // are kept in different files. (except for app in either system or
7802        // vendor path).
7803        // TODO grab this value from PackageSettings
7804        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7805            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7806                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7807            }
7808        }
7809
7810        // TODO: extend to support forward-locked splits
7811        String resourcePath = null;
7812        String baseResourcePath = null;
7813        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7814            if (ps != null && ps.resourcePathString != null) {
7815                resourcePath = ps.resourcePathString;
7816                baseResourcePath = ps.resourcePathString;
7817            } else {
7818                // Should not happen at all. Just log an error.
7819                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7820            }
7821        } else {
7822            resourcePath = pkg.codePath;
7823            baseResourcePath = pkg.baseCodePath;
7824        }
7825
7826        // Set application objects path explicitly.
7827        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7828        pkg.setApplicationInfoCodePath(pkg.codePath);
7829        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7830        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7831        pkg.setApplicationInfoResourcePath(resourcePath);
7832        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7833        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7834
7835        // Note that we invoke the following method only if we are about to unpack an application
7836        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7837                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7838
7839        /*
7840         * If the system app should be overridden by a previously installed
7841         * data, hide the system app now and let the /data/app scan pick it up
7842         * again.
7843         */
7844        if (shouldHideSystemApp) {
7845            synchronized (mPackages) {
7846                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7847            }
7848        }
7849
7850        return scannedPkg;
7851    }
7852
7853    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7854        // Derive the new package synthetic package name
7855        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7856                + pkg.staticSharedLibVersion);
7857    }
7858
7859    private static String fixProcessName(String defProcessName,
7860            String processName) {
7861        if (processName == null) {
7862            return defProcessName;
7863        }
7864        return processName;
7865    }
7866
7867    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7868            throws PackageManagerException {
7869        if (pkgSetting.signatures.mSignatures != null) {
7870            // Already existing package. Make sure signatures match
7871            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7872                    == PackageManager.SIGNATURE_MATCH;
7873            if (!match) {
7874                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7875                        == PackageManager.SIGNATURE_MATCH;
7876            }
7877            if (!match) {
7878                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7879                        == PackageManager.SIGNATURE_MATCH;
7880            }
7881            if (!match) {
7882                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7883                        + pkg.packageName + " signatures do not match the "
7884                        + "previously installed version; ignoring!");
7885            }
7886        }
7887
7888        // Check for shared user signatures
7889        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7890            // Already existing package. Make sure signatures match
7891            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7892                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7893            if (!match) {
7894                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7895                        == PackageManager.SIGNATURE_MATCH;
7896            }
7897            if (!match) {
7898                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7899                        == PackageManager.SIGNATURE_MATCH;
7900            }
7901            if (!match) {
7902                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7903                        "Package " + pkg.packageName
7904                        + " has no signatures that match those in shared user "
7905                        + pkgSetting.sharedUser.name + "; ignoring!");
7906            }
7907        }
7908    }
7909
7910    /**
7911     * Enforces that only the system UID or root's UID can call a method exposed
7912     * via Binder.
7913     *
7914     * @param message used as message if SecurityException is thrown
7915     * @throws SecurityException if the caller is not system or root
7916     */
7917    private static final void enforceSystemOrRoot(String message) {
7918        final int uid = Binder.getCallingUid();
7919        if (uid != Process.SYSTEM_UID && uid != 0) {
7920            throw new SecurityException(message);
7921        }
7922    }
7923
7924    @Override
7925    public void performFstrimIfNeeded() {
7926        enforceSystemOrRoot("Only the system can request fstrim");
7927
7928        // Before everything else, see whether we need to fstrim.
7929        try {
7930            IStorageManager sm = PackageHelper.getStorageManager();
7931            if (sm != null) {
7932                boolean doTrim = false;
7933                final long interval = android.provider.Settings.Global.getLong(
7934                        mContext.getContentResolver(),
7935                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7936                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7937                if (interval > 0) {
7938                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7939                    if (timeSinceLast > interval) {
7940                        doTrim = true;
7941                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7942                                + "; running immediately");
7943                    }
7944                }
7945                if (doTrim) {
7946                    final boolean dexOptDialogShown;
7947                    synchronized (mPackages) {
7948                        dexOptDialogShown = mDexOptDialogShown;
7949                    }
7950                    if (!isFirstBoot() && dexOptDialogShown) {
7951                        try {
7952                            ActivityManager.getService().showBootMessage(
7953                                    mContext.getResources().getString(
7954                                            R.string.android_upgrading_fstrim), true);
7955                        } catch (RemoteException e) {
7956                        }
7957                    }
7958                    sm.runMaintenance();
7959                }
7960            } else {
7961                Slog.e(TAG, "storageManager service unavailable!");
7962            }
7963        } catch (RemoteException e) {
7964            // Can't happen; StorageManagerService is local
7965        }
7966    }
7967
7968    @Override
7969    public void updatePackagesIfNeeded() {
7970        enforceSystemOrRoot("Only the system can request package update");
7971
7972        // We need to re-extract after an OTA.
7973        boolean causeUpgrade = isUpgrade();
7974
7975        // First boot or factory reset.
7976        // Note: we also handle devices that are upgrading to N right now as if it is their
7977        //       first boot, as they do not have profile data.
7978        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7979
7980        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7981        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7982
7983        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7984            return;
7985        }
7986
7987        List<PackageParser.Package> pkgs;
7988        synchronized (mPackages) {
7989            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7990        }
7991
7992        final long startTime = System.nanoTime();
7993        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7994                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7995
7996        final int elapsedTimeSeconds =
7997                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7998
7999        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8000        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8001        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8002        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8003        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8004    }
8005
8006    /**
8007     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8008     * containing statistics about the invocation. The array consists of three elements,
8009     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8010     * and {@code numberOfPackagesFailed}.
8011     */
8012    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8013            String compilerFilter) {
8014
8015        int numberOfPackagesVisited = 0;
8016        int numberOfPackagesOptimized = 0;
8017        int numberOfPackagesSkipped = 0;
8018        int numberOfPackagesFailed = 0;
8019        final int numberOfPackagesToDexopt = pkgs.size();
8020
8021        for (PackageParser.Package pkg : pkgs) {
8022            numberOfPackagesVisited++;
8023
8024            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8025                if (DEBUG_DEXOPT) {
8026                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8027                }
8028                numberOfPackagesSkipped++;
8029                continue;
8030            }
8031
8032            if (DEBUG_DEXOPT) {
8033                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8034                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8035            }
8036
8037            if (showDialog) {
8038                try {
8039                    ActivityManager.getService().showBootMessage(
8040                            mContext.getResources().getString(R.string.android_upgrading_apk,
8041                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8042                } catch (RemoteException e) {
8043                }
8044                synchronized (mPackages) {
8045                    mDexOptDialogShown = true;
8046                }
8047            }
8048
8049            // If the OTA updates a system app which was previously preopted to a non-preopted state
8050            // the app might end up being verified at runtime. That's because by default the apps
8051            // are verify-profile but for preopted apps there's no profile.
8052            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8053            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8054            // filter (by default interpret-only).
8055            // Note that at this stage unused apps are already filtered.
8056            if (isSystemApp(pkg) &&
8057                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8058                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8059                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8060            }
8061
8062            // checkProfiles is false to avoid merging profiles during boot which
8063            // might interfere with background compilation (b/28612421).
8064            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8065            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8066            // trade-off worth doing to save boot time work.
8067            int dexOptStatus = performDexOptTraced(pkg.packageName,
8068                    false /* checkProfiles */,
8069                    compilerFilter,
8070                    false /* force */);
8071            switch (dexOptStatus) {
8072                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8073                    numberOfPackagesOptimized++;
8074                    break;
8075                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8076                    numberOfPackagesSkipped++;
8077                    break;
8078                case PackageDexOptimizer.DEX_OPT_FAILED:
8079                    numberOfPackagesFailed++;
8080                    break;
8081                default:
8082                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8083                    break;
8084            }
8085        }
8086
8087        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8088                numberOfPackagesFailed };
8089    }
8090
8091    @Override
8092    public void notifyPackageUse(String packageName, int reason) {
8093        synchronized (mPackages) {
8094            PackageParser.Package p = mPackages.get(packageName);
8095            if (p == null) {
8096                return;
8097            }
8098            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8099        }
8100    }
8101
8102    @Override
8103    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8104        int userId = UserHandle.getCallingUserId();
8105        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8106        if (ai == null) {
8107            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8108                + loadingPackageName + ", user=" + userId);
8109            return;
8110        }
8111        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8112    }
8113
8114    // TODO: this is not used nor needed. Delete it.
8115    @Override
8116    public boolean performDexOptIfNeeded(String packageName) {
8117        int dexOptStatus = performDexOptTraced(packageName,
8118                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8119        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8120    }
8121
8122    @Override
8123    public boolean performDexOpt(String packageName,
8124            boolean checkProfiles, int compileReason, boolean force) {
8125        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8126                getCompilerFilterForReason(compileReason), force);
8127        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8128    }
8129
8130    @Override
8131    public boolean performDexOptMode(String packageName,
8132            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8133        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8134                targetCompilerFilter, force);
8135        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8136    }
8137
8138    private int performDexOptTraced(String packageName,
8139                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8140        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8141        try {
8142            return performDexOptInternal(packageName, checkProfiles,
8143                    targetCompilerFilter, force);
8144        } finally {
8145            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8146        }
8147    }
8148
8149    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8150    // if the package can now be considered up to date for the given filter.
8151    private int performDexOptInternal(String packageName,
8152                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8153        PackageParser.Package p;
8154        synchronized (mPackages) {
8155            p = mPackages.get(packageName);
8156            if (p == null) {
8157                // Package could not be found. Report failure.
8158                return PackageDexOptimizer.DEX_OPT_FAILED;
8159            }
8160            mPackageUsage.maybeWriteAsync(mPackages);
8161            mCompilerStats.maybeWriteAsync();
8162        }
8163        long callingId = Binder.clearCallingIdentity();
8164        try {
8165            synchronized (mInstallLock) {
8166                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8167                        targetCompilerFilter, force);
8168            }
8169        } finally {
8170            Binder.restoreCallingIdentity(callingId);
8171        }
8172    }
8173
8174    public ArraySet<String> getOptimizablePackages() {
8175        ArraySet<String> pkgs = new ArraySet<String>();
8176        synchronized (mPackages) {
8177            for (PackageParser.Package p : mPackages.values()) {
8178                if (PackageDexOptimizer.canOptimizePackage(p)) {
8179                    pkgs.add(p.packageName);
8180                }
8181            }
8182        }
8183        return pkgs;
8184    }
8185
8186    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8187            boolean checkProfiles, String targetCompilerFilter,
8188            boolean force) {
8189        // Select the dex optimizer based on the force parameter.
8190        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8191        //       allocate an object here.
8192        PackageDexOptimizer pdo = force
8193                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8194                : mPackageDexOptimizer;
8195
8196        // Optimize all dependencies first. Note: we ignore the return value and march on
8197        // on errors.
8198        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8199        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8200        if (!deps.isEmpty()) {
8201            for (PackageParser.Package depPackage : deps) {
8202                // TODO: Analyze and investigate if we (should) profile libraries.
8203                // Currently this will do a full compilation of the library by default.
8204                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8205                        false /* checkProfiles */,
8206                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8207                        getOrCreateCompilerPackageStats(depPackage));
8208            }
8209        }
8210        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8211                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8212    }
8213
8214    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8215        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8216                || p.usesStaticLibraries != null) {
8217            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8218            Set<String> collectedNames = new HashSet<>();
8219            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8220
8221            retValue.remove(p);
8222
8223            return retValue;
8224        } else {
8225            return Collections.emptyList();
8226        }
8227    }
8228
8229    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8230            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8231        if (!collectedNames.contains(p.packageName)) {
8232            collectedNames.add(p.packageName);
8233            collected.add(p);
8234
8235            if (p.usesLibraries != null) {
8236                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8237                        null, collected, collectedNames);
8238            }
8239            if (p.usesOptionalLibraries != null) {
8240                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8241                        null, collected, collectedNames);
8242            }
8243            if (p.usesStaticLibraries != null) {
8244                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8245                        p.usesStaticLibrariesVersions, collected, collectedNames);
8246            }
8247        }
8248    }
8249
8250    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8251            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8252        final int libNameCount = libs.size();
8253        for (int i = 0; i < libNameCount; i++) {
8254            String libName = libs.get(i);
8255            int version = (versions != null && versions.length == libNameCount)
8256                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8257            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8258            if (libPkg != null) {
8259                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8260            }
8261        }
8262    }
8263
8264    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8265        synchronized (mPackages) {
8266            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8267            if (libEntry != null) {
8268                return mPackages.get(libEntry.apk);
8269            }
8270            return null;
8271        }
8272    }
8273
8274    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8275        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8276        if (versionedLib == null) {
8277            return null;
8278        }
8279        return versionedLib.get(version);
8280    }
8281
8282    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8283        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8284                pkg.staticSharedLibName);
8285        if (versionedLib == null) {
8286            return null;
8287        }
8288        int previousLibVersion = -1;
8289        final int versionCount = versionedLib.size();
8290        for (int i = 0; i < versionCount; i++) {
8291            final int libVersion = versionedLib.keyAt(i);
8292            if (libVersion < pkg.staticSharedLibVersion) {
8293                previousLibVersion = Math.max(previousLibVersion, libVersion);
8294            }
8295        }
8296        if (previousLibVersion >= 0) {
8297            return versionedLib.get(previousLibVersion);
8298        }
8299        return null;
8300    }
8301
8302    public void shutdown() {
8303        mPackageUsage.writeNow(mPackages);
8304        mCompilerStats.writeNow();
8305    }
8306
8307    @Override
8308    public void dumpProfiles(String packageName) {
8309        PackageParser.Package pkg;
8310        synchronized (mPackages) {
8311            pkg = mPackages.get(packageName);
8312            if (pkg == null) {
8313                throw new IllegalArgumentException("Unknown package: " + packageName);
8314            }
8315        }
8316        /* Only the shell, root, or the app user should be able to dump profiles. */
8317        int callingUid = Binder.getCallingUid();
8318        if (callingUid != Process.SHELL_UID &&
8319            callingUid != Process.ROOT_UID &&
8320            callingUid != pkg.applicationInfo.uid) {
8321            throw new SecurityException("dumpProfiles");
8322        }
8323
8324        synchronized (mInstallLock) {
8325            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8326            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8327            try {
8328                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8329                String codePaths = TextUtils.join(";", allCodePaths);
8330                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8331            } catch (InstallerException e) {
8332                Slog.w(TAG, "Failed to dump profiles", e);
8333            }
8334            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8335        }
8336    }
8337
8338    @Override
8339    public void forceDexOpt(String packageName) {
8340        enforceSystemOrRoot("forceDexOpt");
8341
8342        PackageParser.Package pkg;
8343        synchronized (mPackages) {
8344            pkg = mPackages.get(packageName);
8345            if (pkg == null) {
8346                throw new IllegalArgumentException("Unknown package: " + packageName);
8347            }
8348        }
8349
8350        synchronized (mInstallLock) {
8351            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8352
8353            // Whoever is calling forceDexOpt wants a fully compiled package.
8354            // Don't use profiles since that may cause compilation to be skipped.
8355            final int res = performDexOptInternalWithDependenciesLI(pkg,
8356                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8357                    true /* force */);
8358
8359            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8360            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8361                throw new IllegalStateException("Failed to dexopt: " + res);
8362            }
8363        }
8364    }
8365
8366    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8367        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8368            Slog.w(TAG, "Unable to update from " + oldPkg.name
8369                    + " to " + newPkg.packageName
8370                    + ": old package not in system partition");
8371            return false;
8372        } else if (mPackages.get(oldPkg.name) != null) {
8373            Slog.w(TAG, "Unable to update from " + oldPkg.name
8374                    + " to " + newPkg.packageName
8375                    + ": old package still exists");
8376            return false;
8377        }
8378        return true;
8379    }
8380
8381    void removeCodePathLI(File codePath) {
8382        if (codePath.isDirectory()) {
8383            try {
8384                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8385            } catch (InstallerException e) {
8386                Slog.w(TAG, "Failed to remove code path", e);
8387            }
8388        } else {
8389            codePath.delete();
8390        }
8391    }
8392
8393    private int[] resolveUserIds(int userId) {
8394        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8395    }
8396
8397    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8398        if (pkg == null) {
8399            Slog.wtf(TAG, "Package was null!", new Throwable());
8400            return;
8401        }
8402        clearAppDataLeafLIF(pkg, userId, flags);
8403        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8404        for (int i = 0; i < childCount; i++) {
8405            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8406        }
8407    }
8408
8409    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8410        final PackageSetting ps;
8411        synchronized (mPackages) {
8412            ps = mSettings.mPackages.get(pkg.packageName);
8413        }
8414        for (int realUserId : resolveUserIds(userId)) {
8415            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8416            try {
8417                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8418                        ceDataInode);
8419            } catch (InstallerException e) {
8420                Slog.w(TAG, String.valueOf(e));
8421            }
8422        }
8423    }
8424
8425    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8426        if (pkg == null) {
8427            Slog.wtf(TAG, "Package was null!", new Throwable());
8428            return;
8429        }
8430        destroyAppDataLeafLIF(pkg, userId, flags);
8431        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8432        for (int i = 0; i < childCount; i++) {
8433            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8434        }
8435    }
8436
8437    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8438        final PackageSetting ps;
8439        synchronized (mPackages) {
8440            ps = mSettings.mPackages.get(pkg.packageName);
8441        }
8442        for (int realUserId : resolveUserIds(userId)) {
8443            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8444            try {
8445                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8446                        ceDataInode);
8447            } catch (InstallerException e) {
8448                Slog.w(TAG, String.valueOf(e));
8449            }
8450        }
8451    }
8452
8453    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8454        if (pkg == null) {
8455            Slog.wtf(TAG, "Package was null!", new Throwable());
8456            return;
8457        }
8458        destroyAppProfilesLeafLIF(pkg);
8459        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8460        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8461        for (int i = 0; i < childCount; i++) {
8462            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8463            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8464                    true /* removeBaseMarker */);
8465        }
8466    }
8467
8468    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8469            boolean removeBaseMarker) {
8470        if (pkg.isForwardLocked()) {
8471            return;
8472        }
8473
8474        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8475            try {
8476                path = PackageManagerServiceUtils.realpath(new File(path));
8477            } catch (IOException e) {
8478                // TODO: Should we return early here ?
8479                Slog.w(TAG, "Failed to get canonical path", e);
8480                continue;
8481            }
8482
8483            final String useMarker = path.replace('/', '@');
8484            for (int realUserId : resolveUserIds(userId)) {
8485                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8486                if (removeBaseMarker) {
8487                    File foreignUseMark = new File(profileDir, useMarker);
8488                    if (foreignUseMark.exists()) {
8489                        if (!foreignUseMark.delete()) {
8490                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8491                                    + pkg.packageName);
8492                        }
8493                    }
8494                }
8495
8496                File[] markers = profileDir.listFiles();
8497                if (markers != null) {
8498                    final String searchString = "@" + pkg.packageName + "@";
8499                    // We also delete all markers that contain the package name we're
8500                    // uninstalling. These are associated with secondary dex-files belonging
8501                    // to the package. Reconstructing the path of these dex files is messy
8502                    // in general.
8503                    for (File marker : markers) {
8504                        if (marker.getName().indexOf(searchString) > 0) {
8505                            if (!marker.delete()) {
8506                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8507                                    + pkg.packageName);
8508                            }
8509                        }
8510                    }
8511                }
8512            }
8513        }
8514    }
8515
8516    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8517        try {
8518            mInstaller.destroyAppProfiles(pkg.packageName);
8519        } catch (InstallerException e) {
8520            Slog.w(TAG, String.valueOf(e));
8521        }
8522    }
8523
8524    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8525        if (pkg == null) {
8526            Slog.wtf(TAG, "Package was null!", new Throwable());
8527            return;
8528        }
8529        clearAppProfilesLeafLIF(pkg);
8530        // We don't remove the base foreign use marker when clearing profiles because
8531        // we will rename it when the app is updated. Unlike the actual profile contents,
8532        // the foreign use marker is good across installs.
8533        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8534        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8535        for (int i = 0; i < childCount; i++) {
8536            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8537        }
8538    }
8539
8540    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8541        try {
8542            mInstaller.clearAppProfiles(pkg.packageName);
8543        } catch (InstallerException e) {
8544            Slog.w(TAG, String.valueOf(e));
8545        }
8546    }
8547
8548    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8549            long lastUpdateTime) {
8550        // Set parent install/update time
8551        PackageSetting ps = (PackageSetting) pkg.mExtras;
8552        if (ps != null) {
8553            ps.firstInstallTime = firstInstallTime;
8554            ps.lastUpdateTime = lastUpdateTime;
8555        }
8556        // Set children install/update time
8557        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8558        for (int i = 0; i < childCount; i++) {
8559            PackageParser.Package childPkg = pkg.childPackages.get(i);
8560            ps = (PackageSetting) childPkg.mExtras;
8561            if (ps != null) {
8562                ps.firstInstallTime = firstInstallTime;
8563                ps.lastUpdateTime = lastUpdateTime;
8564            }
8565        }
8566    }
8567
8568    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8569            PackageParser.Package changingLib) {
8570        if (file.path != null) {
8571            usesLibraryFiles.add(file.path);
8572            return;
8573        }
8574        PackageParser.Package p = mPackages.get(file.apk);
8575        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8576            // If we are doing this while in the middle of updating a library apk,
8577            // then we need to make sure to use that new apk for determining the
8578            // dependencies here.  (We haven't yet finished committing the new apk
8579            // to the package manager state.)
8580            if (p == null || p.packageName.equals(changingLib.packageName)) {
8581                p = changingLib;
8582            }
8583        }
8584        if (p != null) {
8585            usesLibraryFiles.addAll(p.getAllCodePaths());
8586        }
8587    }
8588
8589    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8590            PackageParser.Package changingLib) throws PackageManagerException {
8591        if (pkg == null) {
8592            return;
8593        }
8594        ArraySet<String> usesLibraryFiles = null;
8595        if (pkg.usesLibraries != null) {
8596            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8597                    null, null, pkg.packageName, changingLib, true, null);
8598        }
8599        if (pkg.usesStaticLibraries != null) {
8600            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8601                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8602                    pkg.packageName, changingLib, true, usesLibraryFiles);
8603        }
8604        if (pkg.usesOptionalLibraries != null) {
8605            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8606                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8607        }
8608        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8609            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8610        } else {
8611            pkg.usesLibraryFiles = null;
8612        }
8613    }
8614
8615    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8616            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8617            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8618            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8619            throws PackageManagerException {
8620        final int libCount = requestedLibraries.size();
8621        for (int i = 0; i < libCount; i++) {
8622            final String libName = requestedLibraries.get(i);
8623            final int libVersion = requiredVersions != null ? requiredVersions[i]
8624                    : SharedLibraryInfo.VERSION_UNDEFINED;
8625            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8626            if (libEntry == null) {
8627                if (required) {
8628                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8629                            "Package " + packageName + " requires unavailable shared library "
8630                                    + libName + "; failing!");
8631                } else {
8632                    Slog.w(TAG, "Package " + packageName
8633                            + " desires unavailable shared library "
8634                            + libName + "; ignoring!");
8635                }
8636            } else {
8637                if (requiredVersions != null && requiredCertDigests != null) {
8638                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8639                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8640                            "Package " + packageName + " requires unavailable static shared"
8641                                    + " library " + libName + " version "
8642                                    + libEntry.info.getVersion() + "; failing!");
8643                    }
8644
8645                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8646                    if (libPkg == null) {
8647                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8648                                "Package " + packageName + " requires unavailable static shared"
8649                                        + " library; failing!");
8650                    }
8651
8652                    String expectedCertDigest = requiredCertDigests[i];
8653                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8654                                libPkg.mSignatures[0]);
8655                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8656                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8657                                "Package " + packageName + " requires differently signed" +
8658                                        " static shared library; failing!");
8659                    }
8660                }
8661
8662                if (outUsedLibraries == null) {
8663                    outUsedLibraries = new ArraySet<>();
8664                }
8665                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8666            }
8667        }
8668        return outUsedLibraries;
8669    }
8670
8671    private static boolean hasString(List<String> list, List<String> which) {
8672        if (list == null) {
8673            return false;
8674        }
8675        for (int i=list.size()-1; i>=0; i--) {
8676            for (int j=which.size()-1; j>=0; j--) {
8677                if (which.get(j).equals(list.get(i))) {
8678                    return true;
8679                }
8680            }
8681        }
8682        return false;
8683    }
8684
8685    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8686            PackageParser.Package changingPkg) {
8687        ArrayList<PackageParser.Package> res = null;
8688        for (PackageParser.Package pkg : mPackages.values()) {
8689            if (changingPkg != null
8690                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8691                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8692                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8693                            changingPkg.staticSharedLibName)) {
8694                return null;
8695            }
8696            if (res == null) {
8697                res = new ArrayList<>();
8698            }
8699            res.add(pkg);
8700            try {
8701                updateSharedLibrariesLPr(pkg, changingPkg);
8702            } catch (PackageManagerException e) {
8703                // If a system app update or an app and a required lib missing we
8704                // delete the package and for updated system apps keep the data as
8705                // it is better for the user to reinstall than to be in an limbo
8706                // state. Also libs disappearing under an app should never happen
8707                // - just in case.
8708                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8709                    final int flags = pkg.isUpdatedSystemApp()
8710                            ? PackageManager.DELETE_KEEP_DATA : 0;
8711                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8712                            flags , null, true, null);
8713                }
8714                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8715            }
8716        }
8717        return res;
8718    }
8719
8720    /**
8721     * Derive the value of the {@code cpuAbiOverride} based on the provided
8722     * value and an optional stored value from the package settings.
8723     */
8724    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8725        String cpuAbiOverride = null;
8726
8727        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8728            cpuAbiOverride = null;
8729        } else if (abiOverride != null) {
8730            cpuAbiOverride = abiOverride;
8731        } else if (settings != null) {
8732            cpuAbiOverride = settings.cpuAbiOverrideString;
8733        }
8734
8735        return cpuAbiOverride;
8736    }
8737
8738    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8739            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8740                    throws PackageManagerException {
8741        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8742        // If the package has children and this is the first dive in the function
8743        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8744        // whether all packages (parent and children) would be successfully scanned
8745        // before the actual scan since scanning mutates internal state and we want
8746        // to atomically install the package and its children.
8747        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8748            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8749                scanFlags |= SCAN_CHECK_ONLY;
8750            }
8751        } else {
8752            scanFlags &= ~SCAN_CHECK_ONLY;
8753        }
8754
8755        final PackageParser.Package scannedPkg;
8756        try {
8757            // Scan the parent
8758            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8759            // Scan the children
8760            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8761            for (int i = 0; i < childCount; i++) {
8762                PackageParser.Package childPkg = pkg.childPackages.get(i);
8763                scanPackageLI(childPkg, policyFlags,
8764                        scanFlags, currentTime, user);
8765            }
8766        } finally {
8767            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8768        }
8769
8770        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8771            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8772        }
8773
8774        return scannedPkg;
8775    }
8776
8777    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8778            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8779        boolean success = false;
8780        try {
8781            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8782                    currentTime, user);
8783            success = true;
8784            return res;
8785        } finally {
8786            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8787                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8788                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8789                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8790                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8791            }
8792        }
8793    }
8794
8795    /**
8796     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8797     */
8798    private static boolean apkHasCode(String fileName) {
8799        StrictJarFile jarFile = null;
8800        try {
8801            jarFile = new StrictJarFile(fileName,
8802                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8803            return jarFile.findEntry("classes.dex") != null;
8804        } catch (IOException ignore) {
8805        } finally {
8806            try {
8807                if (jarFile != null) {
8808                    jarFile.close();
8809                }
8810            } catch (IOException ignore) {}
8811        }
8812        return false;
8813    }
8814
8815    /**
8816     * Enforces code policy for the package. This ensures that if an APK has
8817     * declared hasCode="true" in its manifest that the APK actually contains
8818     * code.
8819     *
8820     * @throws PackageManagerException If bytecode could not be found when it should exist
8821     */
8822    private static void assertCodePolicy(PackageParser.Package pkg)
8823            throws PackageManagerException {
8824        final boolean shouldHaveCode =
8825                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8826        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8827            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8828                    "Package " + pkg.baseCodePath + " code is missing");
8829        }
8830
8831        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8832            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8833                final boolean splitShouldHaveCode =
8834                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8835                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8836                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8837                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8838                }
8839            }
8840        }
8841    }
8842
8843    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8844            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8845                    throws PackageManagerException {
8846        if (DEBUG_PACKAGE_SCANNING) {
8847            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8848                Log.d(TAG, "Scanning package " + pkg.packageName);
8849        }
8850
8851        applyPolicy(pkg, policyFlags);
8852
8853        assertPackageIsValid(pkg, policyFlags, scanFlags);
8854
8855        // Initialize package source and resource directories
8856        final File scanFile = new File(pkg.codePath);
8857        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8858        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8859
8860        SharedUserSetting suid = null;
8861        PackageSetting pkgSetting = null;
8862
8863        // Getting the package setting may have a side-effect, so if we
8864        // are only checking if scan would succeed, stash a copy of the
8865        // old setting to restore at the end.
8866        PackageSetting nonMutatedPs = null;
8867
8868        // We keep references to the derived CPU Abis from settings in oder to reuse
8869        // them in the case where we're not upgrading or booting for the first time.
8870        String primaryCpuAbiFromSettings = null;
8871        String secondaryCpuAbiFromSettings = null;
8872
8873        // writer
8874        synchronized (mPackages) {
8875            if (pkg.mSharedUserId != null) {
8876                // SIDE EFFECTS; may potentially allocate a new shared user
8877                suid = mSettings.getSharedUserLPw(
8878                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8879                if (DEBUG_PACKAGE_SCANNING) {
8880                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8881                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8882                                + "): packages=" + suid.packages);
8883                }
8884            }
8885
8886            // Check if we are renaming from an original package name.
8887            PackageSetting origPackage = null;
8888            String realName = null;
8889            if (pkg.mOriginalPackages != null) {
8890                // This package may need to be renamed to a previously
8891                // installed name.  Let's check on that...
8892                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8893                if (pkg.mOriginalPackages.contains(renamed)) {
8894                    // This package had originally been installed as the
8895                    // original name, and we have already taken care of
8896                    // transitioning to the new one.  Just update the new
8897                    // one to continue using the old name.
8898                    realName = pkg.mRealPackage;
8899                    if (!pkg.packageName.equals(renamed)) {
8900                        // Callers into this function may have already taken
8901                        // care of renaming the package; only do it here if
8902                        // it is not already done.
8903                        pkg.setPackageName(renamed);
8904                    }
8905                } else {
8906                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8907                        if ((origPackage = mSettings.getPackageLPr(
8908                                pkg.mOriginalPackages.get(i))) != null) {
8909                            // We do have the package already installed under its
8910                            // original name...  should we use it?
8911                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8912                                // New package is not compatible with original.
8913                                origPackage = null;
8914                                continue;
8915                            } else if (origPackage.sharedUser != null) {
8916                                // Make sure uid is compatible between packages.
8917                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8918                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8919                                            + " to " + pkg.packageName + ": old uid "
8920                                            + origPackage.sharedUser.name
8921                                            + " differs from " + pkg.mSharedUserId);
8922                                    origPackage = null;
8923                                    continue;
8924                                }
8925                                // TODO: Add case when shared user id is added [b/28144775]
8926                            } else {
8927                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8928                                        + pkg.packageName + " to old name " + origPackage.name);
8929                            }
8930                            break;
8931                        }
8932                    }
8933                }
8934            }
8935
8936            if (mTransferedPackages.contains(pkg.packageName)) {
8937                Slog.w(TAG, "Package " + pkg.packageName
8938                        + " was transferred to another, but its .apk remains");
8939            }
8940
8941            // See comments in nonMutatedPs declaration
8942            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8943                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8944                if (foundPs != null) {
8945                    nonMutatedPs = new PackageSetting(foundPs);
8946                }
8947            }
8948
8949            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8950                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8951                if (foundPs != null) {
8952                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8953                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8954                }
8955            }
8956
8957            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8958            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8959                PackageManagerService.reportSettingsProblem(Log.WARN,
8960                        "Package " + pkg.packageName + " shared user changed from "
8961                                + (pkgSetting.sharedUser != null
8962                                        ? pkgSetting.sharedUser.name : "<nothing>")
8963                                + " to "
8964                                + (suid != null ? suid.name : "<nothing>")
8965                                + "; replacing with new");
8966                pkgSetting = null;
8967            }
8968            final PackageSetting oldPkgSetting =
8969                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8970            final PackageSetting disabledPkgSetting =
8971                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8972
8973            String[] usesStaticLibraries = null;
8974            if (pkg.usesStaticLibraries != null) {
8975                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
8976                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
8977            }
8978
8979            if (pkgSetting == null) {
8980                final String parentPackageName = (pkg.parentPackage != null)
8981                        ? pkg.parentPackage.packageName : null;
8982
8983                // REMOVE SharedUserSetting from method; update in a separate call
8984                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8985                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8986                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8987                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8988                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8989                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8990                        UserManagerService.getInstance(), usesStaticLibraries,
8991                        pkg.usesStaticLibrariesVersions);
8992                // SIDE EFFECTS; updates system state; move elsewhere
8993                if (origPackage != null) {
8994                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8995                }
8996                mSettings.addUserToSettingLPw(pkgSetting);
8997            } else {
8998                // REMOVE SharedUserSetting from method; update in a separate call.
8999                //
9000                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9001                // secondaryCpuAbi are not known at this point so we always update them
9002                // to null here, only to reset them at a later point.
9003                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9004                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9005                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9006                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9007                        UserManagerService.getInstance(), usesStaticLibraries,
9008                        pkg.usesStaticLibrariesVersions);
9009            }
9010            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9011            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9012
9013            // SIDE EFFECTS; modifies system state; move elsewhere
9014            if (pkgSetting.origPackage != null) {
9015                // If we are first transitioning from an original package,
9016                // fix up the new package's name now.  We need to do this after
9017                // looking up the package under its new name, so getPackageLP
9018                // can take care of fiddling things correctly.
9019                pkg.setPackageName(origPackage.name);
9020
9021                // File a report about this.
9022                String msg = "New package " + pkgSetting.realName
9023                        + " renamed to replace old package " + pkgSetting.name;
9024                reportSettingsProblem(Log.WARN, msg);
9025
9026                // Make a note of it.
9027                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9028                    mTransferedPackages.add(origPackage.name);
9029                }
9030
9031                // No longer need to retain this.
9032                pkgSetting.origPackage = null;
9033            }
9034
9035            // SIDE EFFECTS; modifies system state; move elsewhere
9036            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9037                // Make a note of it.
9038                mTransferedPackages.add(pkg.packageName);
9039            }
9040
9041            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9042                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9043            }
9044
9045            if ((scanFlags & SCAN_BOOTING) == 0
9046                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9047                // Check all shared libraries and map to their actual file path.
9048                // We only do this here for apps not on a system dir, because those
9049                // are the only ones that can fail an install due to this.  We
9050                // will take care of the system apps by updating all of their
9051                // library paths after the scan is done. Also during the initial
9052                // scan don't update any libs as we do this wholesale after all
9053                // apps are scanned to avoid dependency based scanning.
9054                updateSharedLibrariesLPr(pkg, null);
9055            }
9056
9057            if (mFoundPolicyFile) {
9058                SELinuxMMAC.assignSeinfoValue(pkg);
9059            }
9060
9061            pkg.applicationInfo.uid = pkgSetting.appId;
9062            pkg.mExtras = pkgSetting;
9063
9064
9065            // Static shared libs have same package with different versions where
9066            // we internally use a synthetic package name to allow multiple versions
9067            // of the same package, therefore we need to compare signatures against
9068            // the package setting for the latest library version.
9069            PackageSetting signatureCheckPs = pkgSetting;
9070            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9071                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9072                if (libraryEntry != null) {
9073                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9074                }
9075            }
9076
9077            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9078                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9079                    // We just determined the app is signed correctly, so bring
9080                    // over the latest parsed certs.
9081                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9082                } else {
9083                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9084                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9085                                "Package " + pkg.packageName + " upgrade keys do not match the "
9086                                + "previously installed version");
9087                    } else {
9088                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9089                        String msg = "System package " + pkg.packageName
9090                                + " signature changed; retaining data.";
9091                        reportSettingsProblem(Log.WARN, msg);
9092                    }
9093                }
9094            } else {
9095                try {
9096                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9097                    verifySignaturesLP(signatureCheckPs, pkg);
9098                    // We just determined the app is signed correctly, so bring
9099                    // over the latest parsed certs.
9100                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9101                } catch (PackageManagerException e) {
9102                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9103                        throw e;
9104                    }
9105                    // The signature has changed, but this package is in the system
9106                    // image...  let's recover!
9107                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9108                    // However...  if this package is part of a shared user, but it
9109                    // doesn't match the signature of the shared user, let's fail.
9110                    // What this means is that you can't change the signatures
9111                    // associated with an overall shared user, which doesn't seem all
9112                    // that unreasonable.
9113                    if (signatureCheckPs.sharedUser != null) {
9114                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9115                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9116                            throw new PackageManagerException(
9117                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9118                                    "Signature mismatch for shared user: "
9119                                            + pkgSetting.sharedUser);
9120                        }
9121                    }
9122                    // File a report about this.
9123                    String msg = "System package " + pkg.packageName
9124                            + " signature changed; retaining data.";
9125                    reportSettingsProblem(Log.WARN, msg);
9126                }
9127            }
9128
9129            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9130                // This package wants to adopt ownership of permissions from
9131                // another package.
9132                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9133                    final String origName = pkg.mAdoptPermissions.get(i);
9134                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9135                    if (orig != null) {
9136                        if (verifyPackageUpdateLPr(orig, pkg)) {
9137                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9138                                    + pkg.packageName);
9139                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9140                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9141                        }
9142                    }
9143                }
9144            }
9145        }
9146
9147        pkg.applicationInfo.processName = fixProcessName(
9148                pkg.applicationInfo.packageName,
9149                pkg.applicationInfo.processName);
9150
9151        if (pkg != mPlatformPackage) {
9152            // Get all of our default paths setup
9153            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9154        }
9155
9156        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9157
9158        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9159            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9160                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9161                derivePackageAbi(
9162                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9163                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9164
9165                // Some system apps still use directory structure for native libraries
9166                // in which case we might end up not detecting abi solely based on apk
9167                // structure. Try to detect abi based on directory structure.
9168                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9169                        pkg.applicationInfo.primaryCpuAbi == null) {
9170                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9171                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9172                }
9173            } else {
9174                // This is not a first boot or an upgrade, don't bother deriving the
9175                // ABI during the scan. Instead, trust the value that was stored in the
9176                // package setting.
9177                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9178                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9179
9180                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9181
9182                if (DEBUG_ABI_SELECTION) {
9183                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9184                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9185                        pkg.applicationInfo.secondaryCpuAbi);
9186                }
9187            }
9188        } else {
9189            if ((scanFlags & SCAN_MOVE) != 0) {
9190                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9191                // but we already have this packages package info in the PackageSetting. We just
9192                // use that and derive the native library path based on the new codepath.
9193                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9194                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9195            }
9196
9197            // Set native library paths again. For moves, the path will be updated based on the
9198            // ABIs we've determined above. For non-moves, the path will be updated based on the
9199            // ABIs we determined during compilation, but the path will depend on the final
9200            // package path (after the rename away from the stage path).
9201            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9202        }
9203
9204        // This is a special case for the "system" package, where the ABI is
9205        // dictated by the zygote configuration (and init.rc). We should keep track
9206        // of this ABI so that we can deal with "normal" applications that run under
9207        // the same UID correctly.
9208        if (mPlatformPackage == pkg) {
9209            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9210                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9211        }
9212
9213        // If there's a mismatch between the abi-override in the package setting
9214        // and the abiOverride specified for the install. Warn about this because we
9215        // would've already compiled the app without taking the package setting into
9216        // account.
9217        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9218            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9219                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9220                        " for package " + pkg.packageName);
9221            }
9222        }
9223
9224        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9225        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9226        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9227
9228        // Copy the derived override back to the parsed package, so that we can
9229        // update the package settings accordingly.
9230        pkg.cpuAbiOverride = cpuAbiOverride;
9231
9232        if (DEBUG_ABI_SELECTION) {
9233            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9234                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9235                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9236        }
9237
9238        // Push the derived path down into PackageSettings so we know what to
9239        // clean up at uninstall time.
9240        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9241
9242        if (DEBUG_ABI_SELECTION) {
9243            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9244                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9245                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9246        }
9247
9248        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9249        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9250            // We don't do this here during boot because we can do it all
9251            // at once after scanning all existing packages.
9252            //
9253            // We also do this *before* we perform dexopt on this package, so that
9254            // we can avoid redundant dexopts, and also to make sure we've got the
9255            // code and package path correct.
9256            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9257        }
9258
9259        if (mFactoryTest && pkg.requestedPermissions.contains(
9260                android.Manifest.permission.FACTORY_TEST)) {
9261            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9262        }
9263
9264        if (isSystemApp(pkg)) {
9265            pkgSetting.isOrphaned = true;
9266        }
9267
9268        // Take care of first install / last update times.
9269        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9270        if (currentTime != 0) {
9271            if (pkgSetting.firstInstallTime == 0) {
9272                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9273            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9274                pkgSetting.lastUpdateTime = currentTime;
9275            }
9276        } else if (pkgSetting.firstInstallTime == 0) {
9277            // We need *something*.  Take time time stamp of the file.
9278            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9279        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9280            if (scanFileTime != pkgSetting.timeStamp) {
9281                // A package on the system image has changed; consider this
9282                // to be an update.
9283                pkgSetting.lastUpdateTime = scanFileTime;
9284            }
9285        }
9286        pkgSetting.setTimeStamp(scanFileTime);
9287
9288        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9289            if (nonMutatedPs != null) {
9290                synchronized (mPackages) {
9291                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9292                }
9293            }
9294        } else {
9295            // Modify state for the given package setting
9296            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9297                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9298            if (isEphemeral(pkg)) {
9299                final int userId = user == null ? 0 : user.getIdentifier();
9300                mEphemeralApplicationRegistry.addEphemeralAppLPw(userId, pkgSetting.appId);
9301            }
9302        }
9303        return pkg;
9304    }
9305
9306    /**
9307     * Applies policy to the parsed package based upon the given policy flags.
9308     * Ensures the package is in a good state.
9309     * <p>
9310     * Implementation detail: This method must NOT have any side effect. It would
9311     * ideally be static, but, it requires locks to read system state.
9312     */
9313    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9314        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9315            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9316            if (pkg.applicationInfo.isDirectBootAware()) {
9317                // we're direct boot aware; set for all components
9318                for (PackageParser.Service s : pkg.services) {
9319                    s.info.encryptionAware = s.info.directBootAware = true;
9320                }
9321                for (PackageParser.Provider p : pkg.providers) {
9322                    p.info.encryptionAware = p.info.directBootAware = true;
9323                }
9324                for (PackageParser.Activity a : pkg.activities) {
9325                    a.info.encryptionAware = a.info.directBootAware = true;
9326                }
9327                for (PackageParser.Activity r : pkg.receivers) {
9328                    r.info.encryptionAware = r.info.directBootAware = true;
9329                }
9330            }
9331        } else {
9332            // Only allow system apps to be flagged as core apps.
9333            pkg.coreApp = false;
9334            // clear flags not applicable to regular apps
9335            pkg.applicationInfo.privateFlags &=
9336                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9337            pkg.applicationInfo.privateFlags &=
9338                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9339        }
9340        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9341
9342        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9343            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9344        }
9345
9346        if (!isSystemApp(pkg)) {
9347            // Only system apps can use these features.
9348            pkg.mOriginalPackages = null;
9349            pkg.mRealPackage = null;
9350            pkg.mAdoptPermissions = null;
9351        }
9352    }
9353
9354    /**
9355     * Asserts the parsed package is valid according to the given policy. If the
9356     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9357     * <p>
9358     * Implementation detail: This method must NOT have any side effects. It would
9359     * ideally be static, but, it requires locks to read system state.
9360     *
9361     * @throws PackageManagerException If the package fails any of the validation checks
9362     */
9363    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9364            throws PackageManagerException {
9365        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9366            assertCodePolicy(pkg);
9367        }
9368
9369        if (pkg.applicationInfo.getCodePath() == null ||
9370                pkg.applicationInfo.getResourcePath() == null) {
9371            // Bail out. The resource and code paths haven't been set.
9372            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9373                    "Code and resource paths haven't been set correctly");
9374        }
9375
9376        // Make sure we're not adding any bogus keyset info
9377        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9378        ksms.assertScannedPackageValid(pkg);
9379
9380        synchronized (mPackages) {
9381            // The special "android" package can only be defined once
9382            if (pkg.packageName.equals("android")) {
9383                if (mAndroidApplication != null) {
9384                    Slog.w(TAG, "*************************************************");
9385                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9386                    Slog.w(TAG, " codePath=" + pkg.codePath);
9387                    Slog.w(TAG, "*************************************************");
9388                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9389                            "Core android package being redefined.  Skipping.");
9390                }
9391            }
9392
9393            // A package name must be unique; don't allow duplicates
9394            if (mPackages.containsKey(pkg.packageName)) {
9395                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9396                        "Application package " + pkg.packageName
9397                        + " already installed.  Skipping duplicate.");
9398            }
9399
9400            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9401                // Static libs have a synthetic package name containing the version
9402                // but we still want the base name to be unique.
9403                if (mPackages.containsKey(pkg.manifestPackageName)) {
9404                    throw new PackageManagerException(
9405                            "Duplicate static shared lib provider package");
9406                }
9407
9408                // Static shared libraries should have at least O target SDK
9409                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9410                    throw new PackageManagerException(
9411                            "Packages declaring static-shared libs must target O SDK or higher");
9412                }
9413
9414                // Package declaring static a shared lib cannot be ephemeral
9415                if (pkg.applicationInfo.isEphemeralApp()) {
9416                    throw new PackageManagerException(
9417                            "Packages declaring static-shared libs cannot be ephemeral");
9418                }
9419
9420                // Package declaring static a shared lib cannot be renamed since the package
9421                // name is synthetic and apps can't code around package manager internals.
9422                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9423                    throw new PackageManagerException(
9424                            "Packages declaring static-shared libs cannot be renamed");
9425                }
9426
9427                // Package declaring static a shared lib cannot declare child packages
9428                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9429                    throw new PackageManagerException(
9430                            "Packages declaring static-shared libs cannot have child packages");
9431                }
9432
9433                // Package declaring static a shared lib cannot declare dynamic libs
9434                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9435                    throw new PackageManagerException(
9436                            "Packages declaring static-shared libs cannot declare dynamic libs");
9437                }
9438
9439                // Package declaring static a shared lib cannot declare shared users
9440                if (pkg.mSharedUserId != null) {
9441                    throw new PackageManagerException(
9442                            "Packages declaring static-shared libs cannot declare shared users");
9443                }
9444
9445                // Static shared libs cannot declare activities
9446                if (!pkg.activities.isEmpty()) {
9447                    throw new PackageManagerException(
9448                            "Static shared libs cannot declare activities");
9449                }
9450
9451                // Static shared libs cannot declare services
9452                if (!pkg.services.isEmpty()) {
9453                    throw new PackageManagerException(
9454                            "Static shared libs cannot declare services");
9455                }
9456
9457                // Static shared libs cannot declare providers
9458                if (!pkg.providers.isEmpty()) {
9459                    throw new PackageManagerException(
9460                            "Static shared libs cannot declare content providers");
9461                }
9462
9463                // Static shared libs cannot declare receivers
9464                if (!pkg.receivers.isEmpty()) {
9465                    throw new PackageManagerException(
9466                            "Static shared libs cannot declare broadcast receivers");
9467                }
9468
9469                // Static shared libs cannot declare permission groups
9470                if (!pkg.permissionGroups.isEmpty()) {
9471                    throw new PackageManagerException(
9472                            "Static shared libs cannot declare permission groups");
9473                }
9474
9475                // Static shared libs cannot declare permissions
9476                if (!pkg.permissions.isEmpty()) {
9477                    throw new PackageManagerException(
9478                            "Static shared libs cannot declare permissions");
9479                }
9480
9481                // Static shared libs cannot declare protected broadcasts
9482                if (pkg.protectedBroadcasts != null) {
9483                    throw new PackageManagerException(
9484                            "Static shared libs cannot declare protected broadcasts");
9485                }
9486
9487                // Static shared libs cannot be overlay targets
9488                if (pkg.mOverlayTarget != null) {
9489                    throw new PackageManagerException(
9490                            "Static shared libs cannot be overlay targets");
9491                }
9492
9493                // The version codes must be ordered as lib versions
9494                int minVersionCode = Integer.MIN_VALUE;
9495                int maxVersionCode = Integer.MAX_VALUE;
9496
9497                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9498                        pkg.staticSharedLibName);
9499                if (versionedLib != null) {
9500                    final int versionCount = versionedLib.size();
9501                    for (int i = 0; i < versionCount; i++) {
9502                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9503                        // TODO: We will change version code to long, so in the new API it is long
9504                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9505                                .getVersionCode();
9506                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9507                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9508                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9509                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9510                        } else {
9511                            minVersionCode = maxVersionCode = libVersionCode;
9512                            break;
9513                        }
9514                    }
9515                }
9516                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9517                    throw new PackageManagerException("Static shared"
9518                            + " lib version codes must be ordered as lib versions");
9519                }
9520            }
9521
9522            // Only privileged apps and updated privileged apps can add child packages.
9523            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9524                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9525                    throw new PackageManagerException("Only privileged apps can add child "
9526                            + "packages. Ignoring package " + pkg.packageName);
9527                }
9528                final int childCount = pkg.childPackages.size();
9529                for (int i = 0; i < childCount; i++) {
9530                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9531                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9532                            childPkg.packageName)) {
9533                        throw new PackageManagerException("Can't override child of "
9534                                + "another disabled app. Ignoring package " + pkg.packageName);
9535                    }
9536                }
9537            }
9538
9539            // If we're only installing presumed-existing packages, require that the
9540            // scanned APK is both already known and at the path previously established
9541            // for it.  Previously unknown packages we pick up normally, but if we have an
9542            // a priori expectation about this package's install presence, enforce it.
9543            // With a singular exception for new system packages. When an OTA contains
9544            // a new system package, we allow the codepath to change from a system location
9545            // to the user-installed location. If we don't allow this change, any newer,
9546            // user-installed version of the application will be ignored.
9547            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9548                if (mExpectingBetter.containsKey(pkg.packageName)) {
9549                    logCriticalInfo(Log.WARN,
9550                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9551                } else {
9552                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9553                    if (known != null) {
9554                        if (DEBUG_PACKAGE_SCANNING) {
9555                            Log.d(TAG, "Examining " + pkg.codePath
9556                                    + " and requiring known paths " + known.codePathString
9557                                    + " & " + known.resourcePathString);
9558                        }
9559                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9560                                || !pkg.applicationInfo.getResourcePath().equals(
9561                                        known.resourcePathString)) {
9562                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9563                                    "Application package " + pkg.packageName
9564                                    + " found at " + pkg.applicationInfo.getCodePath()
9565                                    + " but expected at " + known.codePathString
9566                                    + "; ignoring.");
9567                        }
9568                    }
9569                }
9570            }
9571
9572            // Verify that this new package doesn't have any content providers
9573            // that conflict with existing packages.  Only do this if the
9574            // package isn't already installed, since we don't want to break
9575            // things that are installed.
9576            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9577                final int N = pkg.providers.size();
9578                int i;
9579                for (i=0; i<N; i++) {
9580                    PackageParser.Provider p = pkg.providers.get(i);
9581                    if (p.info.authority != null) {
9582                        String names[] = p.info.authority.split(";");
9583                        for (int j = 0; j < names.length; j++) {
9584                            if (mProvidersByAuthority.containsKey(names[j])) {
9585                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9586                                final String otherPackageName =
9587                                        ((other != null && other.getComponentName() != null) ?
9588                                                other.getComponentName().getPackageName() : "?");
9589                                throw new PackageManagerException(
9590                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9591                                        "Can't install because provider name " + names[j]
9592                                                + " (in package " + pkg.applicationInfo.packageName
9593                                                + ") is already used by " + otherPackageName);
9594                            }
9595                        }
9596                    }
9597                }
9598            }
9599        }
9600    }
9601
9602    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9603            int type, String declaringPackageName, int declaringVersionCode) {
9604        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9605        if (versionedLib == null) {
9606            versionedLib = new SparseArray<>();
9607            mSharedLibraries.put(name, versionedLib);
9608            if (type == SharedLibraryInfo.TYPE_STATIC) {
9609                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9610            }
9611        } else if (versionedLib.indexOfKey(version) >= 0) {
9612            return false;
9613        }
9614        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9615                version, type, declaringPackageName, declaringVersionCode);
9616        versionedLib.put(version, libEntry);
9617        return true;
9618    }
9619
9620    private boolean removeSharedLibraryLPw(String name, int version) {
9621        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9622        if (versionedLib == null) {
9623            return false;
9624        }
9625        final int libIdx = versionedLib.indexOfKey(version);
9626        if (libIdx < 0) {
9627            return false;
9628        }
9629        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9630        versionedLib.remove(version);
9631        if (versionedLib.size() <= 0) {
9632            mSharedLibraries.remove(name);
9633            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9634                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9635                        .getPackageName());
9636            }
9637        }
9638        return true;
9639    }
9640
9641    /**
9642     * Adds a scanned package to the system. When this method is finished, the package will
9643     * be available for query, resolution, etc...
9644     */
9645    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9646            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9647        final String pkgName = pkg.packageName;
9648        if (mCustomResolverComponentName != null &&
9649                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9650            setUpCustomResolverActivity(pkg);
9651        }
9652
9653        if (pkg.packageName.equals("android")) {
9654            synchronized (mPackages) {
9655                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9656                    // Set up information for our fall-back user intent resolution activity.
9657                    mPlatformPackage = pkg;
9658                    pkg.mVersionCode = mSdkVersion;
9659                    mAndroidApplication = pkg.applicationInfo;
9660
9661                    if (!mResolverReplaced) {
9662                        mResolveActivity.applicationInfo = mAndroidApplication;
9663                        mResolveActivity.name = ResolverActivity.class.getName();
9664                        mResolveActivity.packageName = mAndroidApplication.packageName;
9665                        mResolveActivity.processName = "system:ui";
9666                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9667                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9668                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9669                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9670                        mResolveActivity.exported = true;
9671                        mResolveActivity.enabled = true;
9672                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9673                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9674                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9675                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9676                                | ActivityInfo.CONFIG_ORIENTATION
9677                                | ActivityInfo.CONFIG_KEYBOARD
9678                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9679                        mResolveInfo.activityInfo = mResolveActivity;
9680                        mResolveInfo.priority = 0;
9681                        mResolveInfo.preferredOrder = 0;
9682                        mResolveInfo.match = 0;
9683                        mResolveComponentName = new ComponentName(
9684                                mAndroidApplication.packageName, mResolveActivity.name);
9685                    }
9686                }
9687            }
9688        }
9689
9690        ArrayList<PackageParser.Package> clientLibPkgs = null;
9691        // writer
9692        synchronized (mPackages) {
9693            boolean hasStaticSharedLibs = false;
9694
9695            // Any app can add new static shared libraries
9696            if (pkg.staticSharedLibName != null) {
9697                // Static shared libs don't allow renaming as they have synthetic package
9698                // names to allow install of multiple versions, so use name from manifest.
9699                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9700                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9701                        pkg.manifestPackageName, pkg.mVersionCode)) {
9702                    hasStaticSharedLibs = true;
9703                } else {
9704                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9705                                + pkg.staticSharedLibName + " already exists; skipping");
9706                }
9707                // Static shared libs cannot be updated once installed since they
9708                // use synthetic package name which includes the version code, so
9709                // not need to update other packages's shared lib dependencies.
9710            }
9711
9712            if (!hasStaticSharedLibs
9713                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9714                // Only system apps can add new dynamic shared libraries.
9715                if (pkg.libraryNames != null) {
9716                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9717                        String name = pkg.libraryNames.get(i);
9718                        boolean allowed = false;
9719                        if (pkg.isUpdatedSystemApp()) {
9720                            // New library entries can only be added through the
9721                            // system image.  This is important to get rid of a lot
9722                            // of nasty edge cases: for example if we allowed a non-
9723                            // system update of the app to add a library, then uninstalling
9724                            // the update would make the library go away, and assumptions
9725                            // we made such as through app install filtering would now
9726                            // have allowed apps on the device which aren't compatible
9727                            // with it.  Better to just have the restriction here, be
9728                            // conservative, and create many fewer cases that can negatively
9729                            // impact the user experience.
9730                            final PackageSetting sysPs = mSettings
9731                                    .getDisabledSystemPkgLPr(pkg.packageName);
9732                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9733                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9734                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9735                                        allowed = true;
9736                                        break;
9737                                    }
9738                                }
9739                            }
9740                        } else {
9741                            allowed = true;
9742                        }
9743                        if (allowed) {
9744                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9745                                    SharedLibraryInfo.VERSION_UNDEFINED,
9746                                    SharedLibraryInfo.TYPE_DYNAMIC,
9747                                    pkg.packageName, pkg.mVersionCode)) {
9748                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9749                                        + name + " already exists; skipping");
9750                            }
9751                        } else {
9752                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9753                                    + name + " that is not declared on system image; skipping");
9754                        }
9755                    }
9756
9757                    if ((scanFlags & SCAN_BOOTING) == 0) {
9758                        // If we are not booting, we need to update any applications
9759                        // that are clients of our shared library.  If we are booting,
9760                        // this will all be done once the scan is complete.
9761                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9762                    }
9763                }
9764            }
9765        }
9766
9767        if ((scanFlags & SCAN_BOOTING) != 0) {
9768            // No apps can run during boot scan, so they don't need to be frozen
9769        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9770            // Caller asked to not kill app, so it's probably not frozen
9771        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9772            // Caller asked us to ignore frozen check for some reason; they
9773            // probably didn't know the package name
9774        } else {
9775            // We're doing major surgery on this package, so it better be frozen
9776            // right now to keep it from launching
9777            checkPackageFrozen(pkgName);
9778        }
9779
9780        // Also need to kill any apps that are dependent on the library.
9781        if (clientLibPkgs != null) {
9782            for (int i=0; i<clientLibPkgs.size(); i++) {
9783                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9784                killApplication(clientPkg.applicationInfo.packageName,
9785                        clientPkg.applicationInfo.uid, "update lib");
9786            }
9787        }
9788
9789        // writer
9790        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9791
9792        boolean createIdmapFailed = false;
9793        synchronized (mPackages) {
9794            // We don't expect installation to fail beyond this point
9795
9796            if (pkgSetting.pkg != null) {
9797                // Note that |user| might be null during the initial boot scan. If a codePath
9798                // for an app has changed during a boot scan, it's due to an app update that's
9799                // part of the system partition and marker changes must be applied to all users.
9800                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9801                final int[] userIds = resolveUserIds(userId);
9802                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9803            }
9804
9805            // Add the new setting to mSettings
9806            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9807            // Add the new setting to mPackages
9808            mPackages.put(pkg.applicationInfo.packageName, pkg);
9809            // Make sure we don't accidentally delete its data.
9810            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9811            while (iter.hasNext()) {
9812                PackageCleanItem item = iter.next();
9813                if (pkgName.equals(item.packageName)) {
9814                    iter.remove();
9815                }
9816            }
9817
9818            // Add the package's KeySets to the global KeySetManagerService
9819            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9820            ksms.addScannedPackageLPw(pkg);
9821
9822            int N = pkg.providers.size();
9823            StringBuilder r = null;
9824            int i;
9825            for (i=0; i<N; i++) {
9826                PackageParser.Provider p = pkg.providers.get(i);
9827                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9828                        p.info.processName);
9829                mProviders.addProvider(p);
9830                p.syncable = p.info.isSyncable;
9831                if (p.info.authority != null) {
9832                    String names[] = p.info.authority.split(";");
9833                    p.info.authority = null;
9834                    for (int j = 0; j < names.length; j++) {
9835                        if (j == 1 && p.syncable) {
9836                            // We only want the first authority for a provider to possibly be
9837                            // syncable, so if we already added this provider using a different
9838                            // authority clear the syncable flag. We copy the provider before
9839                            // changing it because the mProviders object contains a reference
9840                            // to a provider that we don't want to change.
9841                            // Only do this for the second authority since the resulting provider
9842                            // object can be the same for all future authorities for this provider.
9843                            p = new PackageParser.Provider(p);
9844                            p.syncable = false;
9845                        }
9846                        if (!mProvidersByAuthority.containsKey(names[j])) {
9847                            mProvidersByAuthority.put(names[j], p);
9848                            if (p.info.authority == null) {
9849                                p.info.authority = names[j];
9850                            } else {
9851                                p.info.authority = p.info.authority + ";" + names[j];
9852                            }
9853                            if (DEBUG_PACKAGE_SCANNING) {
9854                                if (chatty)
9855                                    Log.d(TAG, "Registered content provider: " + names[j]
9856                                            + ", className = " + p.info.name + ", isSyncable = "
9857                                            + p.info.isSyncable);
9858                            }
9859                        } else {
9860                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9861                            Slog.w(TAG, "Skipping provider name " + names[j] +
9862                                    " (in package " + pkg.applicationInfo.packageName +
9863                                    "): name already used by "
9864                                    + ((other != null && other.getComponentName() != null)
9865                                            ? other.getComponentName().getPackageName() : "?"));
9866                        }
9867                    }
9868                }
9869                if (chatty) {
9870                    if (r == null) {
9871                        r = new StringBuilder(256);
9872                    } else {
9873                        r.append(' ');
9874                    }
9875                    r.append(p.info.name);
9876                }
9877            }
9878            if (r != null) {
9879                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9880            }
9881
9882            N = pkg.services.size();
9883            r = null;
9884            for (i=0; i<N; i++) {
9885                PackageParser.Service s = pkg.services.get(i);
9886                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9887                        s.info.processName);
9888                mServices.addService(s);
9889                if (chatty) {
9890                    if (r == null) {
9891                        r = new StringBuilder(256);
9892                    } else {
9893                        r.append(' ');
9894                    }
9895                    r.append(s.info.name);
9896                }
9897            }
9898            if (r != null) {
9899                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9900            }
9901
9902            N = pkg.receivers.size();
9903            r = null;
9904            for (i=0; i<N; i++) {
9905                PackageParser.Activity a = pkg.receivers.get(i);
9906                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9907                        a.info.processName);
9908                mReceivers.addActivity(a, "receiver");
9909                if (chatty) {
9910                    if (r == null) {
9911                        r = new StringBuilder(256);
9912                    } else {
9913                        r.append(' ');
9914                    }
9915                    r.append(a.info.name);
9916                }
9917            }
9918            if (r != null) {
9919                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9920            }
9921
9922            N = pkg.activities.size();
9923            r = null;
9924            for (i=0; i<N; i++) {
9925                PackageParser.Activity a = pkg.activities.get(i);
9926                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9927                        a.info.processName);
9928                mActivities.addActivity(a, "activity");
9929                if (chatty) {
9930                    if (r == null) {
9931                        r = new StringBuilder(256);
9932                    } else {
9933                        r.append(' ');
9934                    }
9935                    r.append(a.info.name);
9936                }
9937            }
9938            if (r != null) {
9939                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9940            }
9941
9942            N = pkg.permissionGroups.size();
9943            r = null;
9944            for (i=0; i<N; i++) {
9945                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9946                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9947                final String curPackageName = cur == null ? null : cur.info.packageName;
9948                // Dont allow ephemeral apps to define new permission groups.
9949                if (pkg.applicationInfo.isEphemeralApp()) {
9950                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9951                            + pg.info.packageName
9952                            + " ignored: ephemeral apps cannot define new permission groups.");
9953                    continue;
9954                }
9955                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9956                if (cur == null || isPackageUpdate) {
9957                    mPermissionGroups.put(pg.info.name, pg);
9958                    if (chatty) {
9959                        if (r == null) {
9960                            r = new StringBuilder(256);
9961                        } else {
9962                            r.append(' ');
9963                        }
9964                        if (isPackageUpdate) {
9965                            r.append("UPD:");
9966                        }
9967                        r.append(pg.info.name);
9968                    }
9969                } else {
9970                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9971                            + pg.info.packageName + " ignored: original from "
9972                            + cur.info.packageName);
9973                    if (chatty) {
9974                        if (r == null) {
9975                            r = new StringBuilder(256);
9976                        } else {
9977                            r.append(' ');
9978                        }
9979                        r.append("DUP:");
9980                        r.append(pg.info.name);
9981                    }
9982                }
9983            }
9984            if (r != null) {
9985                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9986            }
9987
9988            N = pkg.permissions.size();
9989            r = null;
9990            for (i=0; i<N; i++) {
9991                PackageParser.Permission p = pkg.permissions.get(i);
9992
9993                // Dont allow ephemeral apps to define new permissions.
9994                if (pkg.applicationInfo.isEphemeralApp()) {
9995                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9996                            + p.info.packageName
9997                            + " ignored: ephemeral apps cannot define new permissions.");
9998                    continue;
9999                }
10000
10001                // Assume by default that we did not install this permission into the system.
10002                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10003
10004                // Now that permission groups have a special meaning, we ignore permission
10005                // groups for legacy apps to prevent unexpected behavior. In particular,
10006                // permissions for one app being granted to someone just becase they happen
10007                // to be in a group defined by another app (before this had no implications).
10008                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10009                    p.group = mPermissionGroups.get(p.info.group);
10010                    // Warn for a permission in an unknown group.
10011                    if (p.info.group != null && p.group == null) {
10012                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10013                                + p.info.packageName + " in an unknown group " + p.info.group);
10014                    }
10015                }
10016
10017                ArrayMap<String, BasePermission> permissionMap =
10018                        p.tree ? mSettings.mPermissionTrees
10019                                : mSettings.mPermissions;
10020                BasePermission bp = permissionMap.get(p.info.name);
10021
10022                // Allow system apps to redefine non-system permissions
10023                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10024                    final boolean currentOwnerIsSystem = (bp.perm != null
10025                            && isSystemApp(bp.perm.owner));
10026                    if (isSystemApp(p.owner)) {
10027                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10028                            // It's a built-in permission and no owner, take ownership now
10029                            bp.packageSetting = pkgSetting;
10030                            bp.perm = p;
10031                            bp.uid = pkg.applicationInfo.uid;
10032                            bp.sourcePackage = p.info.packageName;
10033                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10034                        } else if (!currentOwnerIsSystem) {
10035                            String msg = "New decl " + p.owner + " of permission  "
10036                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10037                            reportSettingsProblem(Log.WARN, msg);
10038                            bp = null;
10039                        }
10040                    }
10041                }
10042
10043                if (bp == null) {
10044                    bp = new BasePermission(p.info.name, p.info.packageName,
10045                            BasePermission.TYPE_NORMAL);
10046                    permissionMap.put(p.info.name, bp);
10047                }
10048
10049                if (bp.perm == null) {
10050                    if (bp.sourcePackage == null
10051                            || bp.sourcePackage.equals(p.info.packageName)) {
10052                        BasePermission tree = findPermissionTreeLP(p.info.name);
10053                        if (tree == null
10054                                || tree.sourcePackage.equals(p.info.packageName)) {
10055                            bp.packageSetting = pkgSetting;
10056                            bp.perm = p;
10057                            bp.uid = pkg.applicationInfo.uid;
10058                            bp.sourcePackage = p.info.packageName;
10059                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10060                            if (chatty) {
10061                                if (r == null) {
10062                                    r = new StringBuilder(256);
10063                                } else {
10064                                    r.append(' ');
10065                                }
10066                                r.append(p.info.name);
10067                            }
10068                        } else {
10069                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10070                                    + p.info.packageName + " ignored: base tree "
10071                                    + tree.name + " is from package "
10072                                    + tree.sourcePackage);
10073                        }
10074                    } else {
10075                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10076                                + p.info.packageName + " ignored: original from "
10077                                + bp.sourcePackage);
10078                    }
10079                } else if (chatty) {
10080                    if (r == null) {
10081                        r = new StringBuilder(256);
10082                    } else {
10083                        r.append(' ');
10084                    }
10085                    r.append("DUP:");
10086                    r.append(p.info.name);
10087                }
10088                if (bp.perm == p) {
10089                    bp.protectionLevel = p.info.protectionLevel;
10090                }
10091            }
10092
10093            if (r != null) {
10094                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10095            }
10096
10097            N = pkg.instrumentation.size();
10098            r = null;
10099            for (i=0; i<N; i++) {
10100                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10101                a.info.packageName = pkg.applicationInfo.packageName;
10102                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10103                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10104                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10105                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10106                a.info.dataDir = pkg.applicationInfo.dataDir;
10107                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10108                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10109                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10110                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10111                mInstrumentation.put(a.getComponentName(), a);
10112                if (chatty) {
10113                    if (r == null) {
10114                        r = new StringBuilder(256);
10115                    } else {
10116                        r.append(' ');
10117                    }
10118                    r.append(a.info.name);
10119                }
10120            }
10121            if (r != null) {
10122                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10123            }
10124
10125            if (pkg.protectedBroadcasts != null) {
10126                N = pkg.protectedBroadcasts.size();
10127                for (i=0; i<N; i++) {
10128                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10129                }
10130            }
10131
10132            // Create idmap files for pairs of (packages, overlay packages).
10133            // Note: "android", ie framework-res.apk, is handled by native layers.
10134            if (pkg.mOverlayTarget != null) {
10135                // This is an overlay package.
10136                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10137                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10138                        mOverlays.put(pkg.mOverlayTarget,
10139                                new ArrayMap<String, PackageParser.Package>());
10140                    }
10141                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10142                    map.put(pkg.packageName, pkg);
10143                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10144                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10145                        createIdmapFailed = true;
10146                    }
10147                }
10148            } else if (mOverlays.containsKey(pkg.packageName) &&
10149                    !pkg.packageName.equals("android")) {
10150                // This is a regular package, with one or more known overlay packages.
10151                createIdmapsForPackageLI(pkg);
10152            }
10153        }
10154
10155        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10156
10157        if (createIdmapFailed) {
10158            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10159                    "scanPackageLI failed to createIdmap");
10160        }
10161    }
10162
10163    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10164            PackageParser.Package update, int[] userIds) {
10165        if (existing.applicationInfo == null || update.applicationInfo == null) {
10166            // This isn't due to an app installation.
10167            return;
10168        }
10169
10170        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10171        final File newCodePath = new File(update.applicationInfo.getCodePath());
10172
10173        // The codePath hasn't changed, so there's nothing for us to do.
10174        if (Objects.equals(oldCodePath, newCodePath)) {
10175            return;
10176        }
10177
10178        File canonicalNewCodePath;
10179        try {
10180            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10181        } catch (IOException e) {
10182            Slog.w(TAG, "Failed to get canonical path.", e);
10183            return;
10184        }
10185
10186        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10187        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10188        // that the last component of the path (i.e, the name) doesn't need canonicalization
10189        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10190        // but may change in the future. Hopefully this function won't exist at that point.
10191        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10192                oldCodePath.getName());
10193
10194        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10195        // with "@".
10196        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10197        if (!oldMarkerPrefix.endsWith("@")) {
10198            oldMarkerPrefix += "@";
10199        }
10200        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10201        if (!newMarkerPrefix.endsWith("@")) {
10202            newMarkerPrefix += "@";
10203        }
10204
10205        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10206        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10207        for (String updatedPath : updatedPaths) {
10208            String updatedPathName = new File(updatedPath).getName();
10209            markerSuffixes.add(updatedPathName.replace('/', '@'));
10210        }
10211
10212        for (int userId : userIds) {
10213            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10214
10215            for (String markerSuffix : markerSuffixes) {
10216                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10217                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10218                if (oldForeignUseMark.exists()) {
10219                    try {
10220                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10221                                newForeignUseMark.getAbsolutePath());
10222                    } catch (ErrnoException e) {
10223                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10224                        oldForeignUseMark.delete();
10225                    }
10226                }
10227            }
10228        }
10229    }
10230
10231    /**
10232     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10233     * is derived purely on the basis of the contents of {@code scanFile} and
10234     * {@code cpuAbiOverride}.
10235     *
10236     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10237     */
10238    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10239                                 String cpuAbiOverride, boolean extractLibs,
10240                                 File appLib32InstallDir)
10241            throws PackageManagerException {
10242        // Give ourselves some initial paths; we'll come back for another
10243        // pass once we've determined ABI below.
10244        setNativeLibraryPaths(pkg, appLib32InstallDir);
10245
10246        // We would never need to extract libs for forward-locked and external packages,
10247        // since the container service will do it for us. We shouldn't attempt to
10248        // extract libs from system app when it was not updated.
10249        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10250                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10251            extractLibs = false;
10252        }
10253
10254        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10255        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10256
10257        NativeLibraryHelper.Handle handle = null;
10258        try {
10259            handle = NativeLibraryHelper.Handle.create(pkg);
10260            // TODO(multiArch): This can be null for apps that didn't go through the
10261            // usual installation process. We can calculate it again, like we
10262            // do during install time.
10263            //
10264            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10265            // unnecessary.
10266            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10267
10268            // Null out the abis so that they can be recalculated.
10269            pkg.applicationInfo.primaryCpuAbi = null;
10270            pkg.applicationInfo.secondaryCpuAbi = null;
10271            if (isMultiArch(pkg.applicationInfo)) {
10272                // Warn if we've set an abiOverride for multi-lib packages..
10273                // By definition, we need to copy both 32 and 64 bit libraries for
10274                // such packages.
10275                if (pkg.cpuAbiOverride != null
10276                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10277                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10278                }
10279
10280                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10281                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10282                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10283                    if (extractLibs) {
10284                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10285                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10286                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10287                                useIsaSpecificSubdirs);
10288                    } else {
10289                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10290                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10291                    }
10292                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10293                }
10294
10295                maybeThrowExceptionForMultiArchCopy(
10296                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10297
10298                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10299                    if (extractLibs) {
10300                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10301                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10302                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10303                                useIsaSpecificSubdirs);
10304                    } else {
10305                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10306                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10307                    }
10308                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10309                }
10310
10311                maybeThrowExceptionForMultiArchCopy(
10312                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10313
10314                if (abi64 >= 0) {
10315                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10316                }
10317
10318                if (abi32 >= 0) {
10319                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10320                    if (abi64 >= 0) {
10321                        if (pkg.use32bitAbi) {
10322                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10323                            pkg.applicationInfo.primaryCpuAbi = abi;
10324                        } else {
10325                            pkg.applicationInfo.secondaryCpuAbi = abi;
10326                        }
10327                    } else {
10328                        pkg.applicationInfo.primaryCpuAbi = abi;
10329                    }
10330                }
10331
10332            } else {
10333                String[] abiList = (cpuAbiOverride != null) ?
10334                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10335
10336                // Enable gross and lame hacks for apps that are built with old
10337                // SDK tools. We must scan their APKs for renderscript bitcode and
10338                // not launch them if it's present. Don't bother checking on devices
10339                // that don't have 64 bit support.
10340                boolean needsRenderScriptOverride = false;
10341                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10342                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10343                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10344                    needsRenderScriptOverride = true;
10345                }
10346
10347                final int copyRet;
10348                if (extractLibs) {
10349                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10350                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10351                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10352                } else {
10353                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10354                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10355                }
10356                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10357
10358                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10359                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10360                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10361                }
10362
10363                if (copyRet >= 0) {
10364                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10365                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10366                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10367                } else if (needsRenderScriptOverride) {
10368                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10369                }
10370            }
10371        } catch (IOException ioe) {
10372            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10373        } finally {
10374            IoUtils.closeQuietly(handle);
10375        }
10376
10377        // Now that we've calculated the ABIs and determined if it's an internal app,
10378        // we will go ahead and populate the nativeLibraryPath.
10379        setNativeLibraryPaths(pkg, appLib32InstallDir);
10380    }
10381
10382    /**
10383     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10384     * i.e, so that all packages can be run inside a single process if required.
10385     *
10386     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10387     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10388     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10389     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10390     * updating a package that belongs to a shared user.
10391     *
10392     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10393     * adds unnecessary complexity.
10394     */
10395    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10396            PackageParser.Package scannedPackage) {
10397        String requiredInstructionSet = null;
10398        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10399            requiredInstructionSet = VMRuntime.getInstructionSet(
10400                     scannedPackage.applicationInfo.primaryCpuAbi);
10401        }
10402
10403        PackageSetting requirer = null;
10404        for (PackageSetting ps : packagesForUser) {
10405            // If packagesForUser contains scannedPackage, we skip it. This will happen
10406            // when scannedPackage is an update of an existing package. Without this check,
10407            // we will never be able to change the ABI of any package belonging to a shared
10408            // user, even if it's compatible with other packages.
10409            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10410                if (ps.primaryCpuAbiString == null) {
10411                    continue;
10412                }
10413
10414                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10415                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10416                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10417                    // this but there's not much we can do.
10418                    String errorMessage = "Instruction set mismatch, "
10419                            + ((requirer == null) ? "[caller]" : requirer)
10420                            + " requires " + requiredInstructionSet + " whereas " + ps
10421                            + " requires " + instructionSet;
10422                    Slog.w(TAG, errorMessage);
10423                }
10424
10425                if (requiredInstructionSet == null) {
10426                    requiredInstructionSet = instructionSet;
10427                    requirer = ps;
10428                }
10429            }
10430        }
10431
10432        if (requiredInstructionSet != null) {
10433            String adjustedAbi;
10434            if (requirer != null) {
10435                // requirer != null implies that either scannedPackage was null or that scannedPackage
10436                // did not require an ABI, in which case we have to adjust scannedPackage to match
10437                // the ABI of the set (which is the same as requirer's ABI)
10438                adjustedAbi = requirer.primaryCpuAbiString;
10439                if (scannedPackage != null) {
10440                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10441                }
10442            } else {
10443                // requirer == null implies that we're updating all ABIs in the set to
10444                // match scannedPackage.
10445                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10446            }
10447
10448            for (PackageSetting ps : packagesForUser) {
10449                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10450                    if (ps.primaryCpuAbiString != null) {
10451                        continue;
10452                    }
10453
10454                    ps.primaryCpuAbiString = adjustedAbi;
10455                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10456                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10457                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10458                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10459                                + " (requirer="
10460                                + (requirer == null ? "null" : requirer.pkg.packageName)
10461                                + ", scannedPackage="
10462                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10463                                + ")");
10464                        try {
10465                            mInstaller.rmdex(ps.codePathString,
10466                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10467                        } catch (InstallerException ignored) {
10468                        }
10469                    }
10470                }
10471            }
10472        }
10473    }
10474
10475    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10476        synchronized (mPackages) {
10477            mResolverReplaced = true;
10478            // Set up information for custom user intent resolution activity.
10479            mResolveActivity.applicationInfo = pkg.applicationInfo;
10480            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10481            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10482            mResolveActivity.processName = pkg.applicationInfo.packageName;
10483            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10484            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10485                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10486            mResolveActivity.theme = 0;
10487            mResolveActivity.exported = true;
10488            mResolveActivity.enabled = true;
10489            mResolveInfo.activityInfo = mResolveActivity;
10490            mResolveInfo.priority = 0;
10491            mResolveInfo.preferredOrder = 0;
10492            mResolveInfo.match = 0;
10493            mResolveComponentName = mCustomResolverComponentName;
10494            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10495                    mResolveComponentName);
10496        }
10497    }
10498
10499    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10500        if (installerComponent == null) {
10501            if (DEBUG_EPHEMERAL) {
10502                Slog.d(TAG, "Clear ephemeral installer activity");
10503            }
10504            mEphemeralInstallerActivity.applicationInfo = null;
10505            return;
10506        }
10507
10508        if (DEBUG_EPHEMERAL) {
10509            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10510        }
10511        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10512        // Set up information for ephemeral installer activity
10513        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10514        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10515        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10516        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10517        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10518        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10519                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10520        mEphemeralInstallerActivity.theme = 0;
10521        mEphemeralInstallerActivity.exported = true;
10522        mEphemeralInstallerActivity.enabled = true;
10523        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10524        mEphemeralInstallerInfo.priority = 0;
10525        mEphemeralInstallerInfo.preferredOrder = 1;
10526        mEphemeralInstallerInfo.isDefault = true;
10527        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10528                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10529    }
10530
10531    private static String calculateBundledApkRoot(final String codePathString) {
10532        final File codePath = new File(codePathString);
10533        final File codeRoot;
10534        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10535            codeRoot = Environment.getRootDirectory();
10536        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10537            codeRoot = Environment.getOemDirectory();
10538        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10539            codeRoot = Environment.getVendorDirectory();
10540        } else {
10541            // Unrecognized code path; take its top real segment as the apk root:
10542            // e.g. /something/app/blah.apk => /something
10543            try {
10544                File f = codePath.getCanonicalFile();
10545                File parent = f.getParentFile();    // non-null because codePath is a file
10546                File tmp;
10547                while ((tmp = parent.getParentFile()) != null) {
10548                    f = parent;
10549                    parent = tmp;
10550                }
10551                codeRoot = f;
10552                Slog.w(TAG, "Unrecognized code path "
10553                        + codePath + " - using " + codeRoot);
10554            } catch (IOException e) {
10555                // Can't canonicalize the code path -- shenanigans?
10556                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10557                return Environment.getRootDirectory().getPath();
10558            }
10559        }
10560        return codeRoot.getPath();
10561    }
10562
10563    /**
10564     * Derive and set the location of native libraries for the given package,
10565     * which varies depending on where and how the package was installed.
10566     */
10567    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10568        final ApplicationInfo info = pkg.applicationInfo;
10569        final String codePath = pkg.codePath;
10570        final File codeFile = new File(codePath);
10571        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10572        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10573
10574        info.nativeLibraryRootDir = null;
10575        info.nativeLibraryRootRequiresIsa = false;
10576        info.nativeLibraryDir = null;
10577        info.secondaryNativeLibraryDir = null;
10578
10579        if (isApkFile(codeFile)) {
10580            // Monolithic install
10581            if (bundledApp) {
10582                // If "/system/lib64/apkname" exists, assume that is the per-package
10583                // native library directory to use; otherwise use "/system/lib/apkname".
10584                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10585                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10586                        getPrimaryInstructionSet(info));
10587
10588                // This is a bundled system app so choose the path based on the ABI.
10589                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10590                // is just the default path.
10591                final String apkName = deriveCodePathName(codePath);
10592                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10593                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10594                        apkName).getAbsolutePath();
10595
10596                if (info.secondaryCpuAbi != null) {
10597                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10598                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10599                            secondaryLibDir, apkName).getAbsolutePath();
10600                }
10601            } else if (asecApp) {
10602                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10603                        .getAbsolutePath();
10604            } else {
10605                final String apkName = deriveCodePathName(codePath);
10606                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10607                        .getAbsolutePath();
10608            }
10609
10610            info.nativeLibraryRootRequiresIsa = false;
10611            info.nativeLibraryDir = info.nativeLibraryRootDir;
10612        } else {
10613            // Cluster install
10614            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10615            info.nativeLibraryRootRequiresIsa = true;
10616
10617            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10618                    getPrimaryInstructionSet(info)).getAbsolutePath();
10619
10620            if (info.secondaryCpuAbi != null) {
10621                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10622                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10623            }
10624        }
10625    }
10626
10627    /**
10628     * Calculate the abis and roots for a bundled app. These can uniquely
10629     * be determined from the contents of the system partition, i.e whether
10630     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10631     * of this information, and instead assume that the system was built
10632     * sensibly.
10633     */
10634    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10635                                           PackageSetting pkgSetting) {
10636        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10637
10638        // If "/system/lib64/apkname" exists, assume that is the per-package
10639        // native library directory to use; otherwise use "/system/lib/apkname".
10640        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10641        setBundledAppAbi(pkg, apkRoot, apkName);
10642        // pkgSetting might be null during rescan following uninstall of updates
10643        // to a bundled app, so accommodate that possibility.  The settings in
10644        // that case will be established later from the parsed package.
10645        //
10646        // If the settings aren't null, sync them up with what we've just derived.
10647        // note that apkRoot isn't stored in the package settings.
10648        if (pkgSetting != null) {
10649            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10650            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10651        }
10652    }
10653
10654    /**
10655     * Deduces the ABI of a bundled app and sets the relevant fields on the
10656     * parsed pkg object.
10657     *
10658     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10659     *        under which system libraries are installed.
10660     * @param apkName the name of the installed package.
10661     */
10662    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10663        final File codeFile = new File(pkg.codePath);
10664
10665        final boolean has64BitLibs;
10666        final boolean has32BitLibs;
10667        if (isApkFile(codeFile)) {
10668            // Monolithic install
10669            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10670            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10671        } else {
10672            // Cluster install
10673            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10674            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10675                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10676                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10677                has64BitLibs = (new File(rootDir, isa)).exists();
10678            } else {
10679                has64BitLibs = false;
10680            }
10681            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10682                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10683                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10684                has32BitLibs = (new File(rootDir, isa)).exists();
10685            } else {
10686                has32BitLibs = false;
10687            }
10688        }
10689
10690        if (has64BitLibs && !has32BitLibs) {
10691            // The package has 64 bit libs, but not 32 bit libs. Its primary
10692            // ABI should be 64 bit. We can safely assume here that the bundled
10693            // native libraries correspond to the most preferred ABI in the list.
10694
10695            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10696            pkg.applicationInfo.secondaryCpuAbi = null;
10697        } else if (has32BitLibs && !has64BitLibs) {
10698            // The package has 32 bit libs but not 64 bit libs. Its primary
10699            // ABI should be 32 bit.
10700
10701            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10702            pkg.applicationInfo.secondaryCpuAbi = null;
10703        } else if (has32BitLibs && has64BitLibs) {
10704            // The application has both 64 and 32 bit bundled libraries. We check
10705            // here that the app declares multiArch support, and warn if it doesn't.
10706            //
10707            // We will be lenient here and record both ABIs. The primary will be the
10708            // ABI that's higher on the list, i.e, a device that's configured to prefer
10709            // 64 bit apps will see a 64 bit primary ABI,
10710
10711            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10712                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10713            }
10714
10715            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10716                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10717                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10718            } else {
10719                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10720                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10721            }
10722        } else {
10723            pkg.applicationInfo.primaryCpuAbi = null;
10724            pkg.applicationInfo.secondaryCpuAbi = null;
10725        }
10726    }
10727
10728    private void killApplication(String pkgName, int appId, String reason) {
10729        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10730    }
10731
10732    private void killApplication(String pkgName, int appId, int userId, String reason) {
10733        // Request the ActivityManager to kill the process(only for existing packages)
10734        // so that we do not end up in a confused state while the user is still using the older
10735        // version of the application while the new one gets installed.
10736        final long token = Binder.clearCallingIdentity();
10737        try {
10738            IActivityManager am = ActivityManager.getService();
10739            if (am != null) {
10740                try {
10741                    am.killApplication(pkgName, appId, userId, reason);
10742                } catch (RemoteException e) {
10743                }
10744            }
10745        } finally {
10746            Binder.restoreCallingIdentity(token);
10747        }
10748    }
10749
10750    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10751        // Remove the parent package setting
10752        PackageSetting ps = (PackageSetting) pkg.mExtras;
10753        if (ps != null) {
10754            removePackageLI(ps, chatty);
10755        }
10756        // Remove the child package setting
10757        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10758        for (int i = 0; i < childCount; i++) {
10759            PackageParser.Package childPkg = pkg.childPackages.get(i);
10760            ps = (PackageSetting) childPkg.mExtras;
10761            if (ps != null) {
10762                removePackageLI(ps, chatty);
10763            }
10764        }
10765    }
10766
10767    void removePackageLI(PackageSetting ps, boolean chatty) {
10768        if (DEBUG_INSTALL) {
10769            if (chatty)
10770                Log.d(TAG, "Removing package " + ps.name);
10771        }
10772
10773        // writer
10774        synchronized (mPackages) {
10775            mPackages.remove(ps.name);
10776            final PackageParser.Package pkg = ps.pkg;
10777            if (pkg != null) {
10778                cleanPackageDataStructuresLILPw(pkg, chatty);
10779            }
10780        }
10781    }
10782
10783    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10784        if (DEBUG_INSTALL) {
10785            if (chatty)
10786                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10787        }
10788
10789        // writer
10790        synchronized (mPackages) {
10791            // Remove the parent package
10792            mPackages.remove(pkg.applicationInfo.packageName);
10793            cleanPackageDataStructuresLILPw(pkg, chatty);
10794
10795            // Remove the child packages
10796            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10797            for (int i = 0; i < childCount; i++) {
10798                PackageParser.Package childPkg = pkg.childPackages.get(i);
10799                mPackages.remove(childPkg.applicationInfo.packageName);
10800                cleanPackageDataStructuresLILPw(childPkg, chatty);
10801            }
10802        }
10803    }
10804
10805    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10806        int N = pkg.providers.size();
10807        StringBuilder r = null;
10808        int i;
10809        for (i=0; i<N; i++) {
10810            PackageParser.Provider p = pkg.providers.get(i);
10811            mProviders.removeProvider(p);
10812            if (p.info.authority == null) {
10813
10814                /* There was another ContentProvider with this authority when
10815                 * this app was installed so this authority is null,
10816                 * Ignore it as we don't have to unregister the provider.
10817                 */
10818                continue;
10819            }
10820            String names[] = p.info.authority.split(";");
10821            for (int j = 0; j < names.length; j++) {
10822                if (mProvidersByAuthority.get(names[j]) == p) {
10823                    mProvidersByAuthority.remove(names[j]);
10824                    if (DEBUG_REMOVE) {
10825                        if (chatty)
10826                            Log.d(TAG, "Unregistered content provider: " + names[j]
10827                                    + ", className = " + p.info.name + ", isSyncable = "
10828                                    + p.info.isSyncable);
10829                    }
10830                }
10831            }
10832            if (DEBUG_REMOVE && chatty) {
10833                if (r == null) {
10834                    r = new StringBuilder(256);
10835                } else {
10836                    r.append(' ');
10837                }
10838                r.append(p.info.name);
10839            }
10840        }
10841        if (r != null) {
10842            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10843        }
10844
10845        N = pkg.services.size();
10846        r = null;
10847        for (i=0; i<N; i++) {
10848            PackageParser.Service s = pkg.services.get(i);
10849            mServices.removeService(s);
10850            if (chatty) {
10851                if (r == null) {
10852                    r = new StringBuilder(256);
10853                } else {
10854                    r.append(' ');
10855                }
10856                r.append(s.info.name);
10857            }
10858        }
10859        if (r != null) {
10860            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10861        }
10862
10863        N = pkg.receivers.size();
10864        r = null;
10865        for (i=0; i<N; i++) {
10866            PackageParser.Activity a = pkg.receivers.get(i);
10867            mReceivers.removeActivity(a, "receiver");
10868            if (DEBUG_REMOVE && chatty) {
10869                if (r == null) {
10870                    r = new StringBuilder(256);
10871                } else {
10872                    r.append(' ');
10873                }
10874                r.append(a.info.name);
10875            }
10876        }
10877        if (r != null) {
10878            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10879        }
10880
10881        N = pkg.activities.size();
10882        r = null;
10883        for (i=0; i<N; i++) {
10884            PackageParser.Activity a = pkg.activities.get(i);
10885            mActivities.removeActivity(a, "activity");
10886            if (DEBUG_REMOVE && chatty) {
10887                if (r == null) {
10888                    r = new StringBuilder(256);
10889                } else {
10890                    r.append(' ');
10891                }
10892                r.append(a.info.name);
10893            }
10894        }
10895        if (r != null) {
10896            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10897        }
10898
10899        N = pkg.permissions.size();
10900        r = null;
10901        for (i=0; i<N; i++) {
10902            PackageParser.Permission p = pkg.permissions.get(i);
10903            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10904            if (bp == null) {
10905                bp = mSettings.mPermissionTrees.get(p.info.name);
10906            }
10907            if (bp != null && bp.perm == p) {
10908                bp.perm = null;
10909                if (DEBUG_REMOVE && chatty) {
10910                    if (r == null) {
10911                        r = new StringBuilder(256);
10912                    } else {
10913                        r.append(' ');
10914                    }
10915                    r.append(p.info.name);
10916                }
10917            }
10918            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10919                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10920                if (appOpPkgs != null) {
10921                    appOpPkgs.remove(pkg.packageName);
10922                }
10923            }
10924        }
10925        if (r != null) {
10926            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10927        }
10928
10929        N = pkg.requestedPermissions.size();
10930        r = null;
10931        for (i=0; i<N; i++) {
10932            String perm = pkg.requestedPermissions.get(i);
10933            BasePermission bp = mSettings.mPermissions.get(perm);
10934            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10935                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10936                if (appOpPkgs != null) {
10937                    appOpPkgs.remove(pkg.packageName);
10938                    if (appOpPkgs.isEmpty()) {
10939                        mAppOpPermissionPackages.remove(perm);
10940                    }
10941                }
10942            }
10943        }
10944        if (r != null) {
10945            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10946        }
10947
10948        N = pkg.instrumentation.size();
10949        r = null;
10950        for (i=0; i<N; i++) {
10951            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10952            mInstrumentation.remove(a.getComponentName());
10953            if (DEBUG_REMOVE && chatty) {
10954                if (r == null) {
10955                    r = new StringBuilder(256);
10956                } else {
10957                    r.append(' ');
10958                }
10959                r.append(a.info.name);
10960            }
10961        }
10962        if (r != null) {
10963            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10964        }
10965
10966        r = null;
10967        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10968            // Only system apps can hold shared libraries.
10969            if (pkg.libraryNames != null) {
10970                for (i = 0; i < pkg.libraryNames.size(); i++) {
10971                    String name = pkg.libraryNames.get(i);
10972                    if (removeSharedLibraryLPw(name, 0)) {
10973                        if (DEBUG_REMOVE && chatty) {
10974                            if (r == null) {
10975                                r = new StringBuilder(256);
10976                            } else {
10977                                r.append(' ');
10978                            }
10979                            r.append(name);
10980                        }
10981                    }
10982                }
10983            }
10984        }
10985
10986        r = null;
10987
10988        // Any package can hold static shared libraries.
10989        if (pkg.staticSharedLibName != null) {
10990            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
10991                if (DEBUG_REMOVE && chatty) {
10992                    if (r == null) {
10993                        r = new StringBuilder(256);
10994                    } else {
10995                        r.append(' ');
10996                    }
10997                    r.append(pkg.staticSharedLibName);
10998                }
10999            }
11000        }
11001
11002        if (r != null) {
11003            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11004        }
11005    }
11006
11007    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11008        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11009            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11010                return true;
11011            }
11012        }
11013        return false;
11014    }
11015
11016    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11017    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11018    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11019
11020    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11021        // Update the parent permissions
11022        updatePermissionsLPw(pkg.packageName, pkg, flags);
11023        // Update the child permissions
11024        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11025        for (int i = 0; i < childCount; i++) {
11026            PackageParser.Package childPkg = pkg.childPackages.get(i);
11027            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11028        }
11029    }
11030
11031    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11032            int flags) {
11033        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11034        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11035    }
11036
11037    private void updatePermissionsLPw(String changingPkg,
11038            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11039        // Make sure there are no dangling permission trees.
11040        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11041        while (it.hasNext()) {
11042            final BasePermission bp = it.next();
11043            if (bp.packageSetting == null) {
11044                // We may not yet have parsed the package, so just see if
11045                // we still know about its settings.
11046                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11047            }
11048            if (bp.packageSetting == null) {
11049                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11050                        + " from package " + bp.sourcePackage);
11051                it.remove();
11052            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11053                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11054                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11055                            + " from package " + bp.sourcePackage);
11056                    flags |= UPDATE_PERMISSIONS_ALL;
11057                    it.remove();
11058                }
11059            }
11060        }
11061
11062        // Make sure all dynamic permissions have been assigned to a package,
11063        // and make sure there are no dangling permissions.
11064        it = mSettings.mPermissions.values().iterator();
11065        while (it.hasNext()) {
11066            final BasePermission bp = it.next();
11067            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11068                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11069                        + bp.name + " pkg=" + bp.sourcePackage
11070                        + " info=" + bp.pendingInfo);
11071                if (bp.packageSetting == null && bp.pendingInfo != null) {
11072                    final BasePermission tree = findPermissionTreeLP(bp.name);
11073                    if (tree != null && tree.perm != null) {
11074                        bp.packageSetting = tree.packageSetting;
11075                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11076                                new PermissionInfo(bp.pendingInfo));
11077                        bp.perm.info.packageName = tree.perm.info.packageName;
11078                        bp.perm.info.name = bp.name;
11079                        bp.uid = tree.uid;
11080                    }
11081                }
11082            }
11083            if (bp.packageSetting == null) {
11084                // We may not yet have parsed the package, so just see if
11085                // we still know about its settings.
11086                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11087            }
11088            if (bp.packageSetting == null) {
11089                Slog.w(TAG, "Removing dangling permission: " + bp.name
11090                        + " from package " + bp.sourcePackage);
11091                it.remove();
11092            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11093                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11094                    Slog.i(TAG, "Removing old permission: " + bp.name
11095                            + " from package " + bp.sourcePackage);
11096                    flags |= UPDATE_PERMISSIONS_ALL;
11097                    it.remove();
11098                }
11099            }
11100        }
11101
11102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11103        // Now update the permissions for all packages, in particular
11104        // replace the granted permissions of the system packages.
11105        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11106            for (PackageParser.Package pkg : mPackages.values()) {
11107                if (pkg != pkgInfo) {
11108                    // Only replace for packages on requested volume
11109                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11110                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11111                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11112                    grantPermissionsLPw(pkg, replace, changingPkg);
11113                }
11114            }
11115        }
11116
11117        if (pkgInfo != null) {
11118            // Only replace for packages on requested volume
11119            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11120            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11121                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11122            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11123        }
11124        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11125    }
11126
11127    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11128            String packageOfInterest) {
11129        // IMPORTANT: There are two types of permissions: install and runtime.
11130        // Install time permissions are granted when the app is installed to
11131        // all device users and users added in the future. Runtime permissions
11132        // are granted at runtime explicitly to specific users. Normal and signature
11133        // protected permissions are install time permissions. Dangerous permissions
11134        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11135        // otherwise they are runtime permissions. This function does not manage
11136        // runtime permissions except for the case an app targeting Lollipop MR1
11137        // being upgraded to target a newer SDK, in which case dangerous permissions
11138        // are transformed from install time to runtime ones.
11139
11140        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11141        if (ps == null) {
11142            return;
11143        }
11144
11145        PermissionsState permissionsState = ps.getPermissionsState();
11146        PermissionsState origPermissions = permissionsState;
11147
11148        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11149
11150        boolean runtimePermissionsRevoked = false;
11151        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11152
11153        boolean changedInstallPermission = false;
11154
11155        if (replace) {
11156            ps.installPermissionsFixed = false;
11157            if (!ps.isSharedUser()) {
11158                origPermissions = new PermissionsState(permissionsState);
11159                permissionsState.reset();
11160            } else {
11161                // We need to know only about runtime permission changes since the
11162                // calling code always writes the install permissions state but
11163                // the runtime ones are written only if changed. The only cases of
11164                // changed runtime permissions here are promotion of an install to
11165                // runtime and revocation of a runtime from a shared user.
11166                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11167                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11168                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11169                    runtimePermissionsRevoked = true;
11170                }
11171            }
11172        }
11173
11174        permissionsState.setGlobalGids(mGlobalGids);
11175
11176        final int N = pkg.requestedPermissions.size();
11177        for (int i=0; i<N; i++) {
11178            final String name = pkg.requestedPermissions.get(i);
11179            final BasePermission bp = mSettings.mPermissions.get(name);
11180
11181            if (DEBUG_INSTALL) {
11182                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11183            }
11184
11185            if (bp == null || bp.packageSetting == null) {
11186                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11187                    Slog.w(TAG, "Unknown permission " + name
11188                            + " in package " + pkg.packageName);
11189                }
11190                continue;
11191            }
11192
11193
11194            // Limit ephemeral apps to ephemeral allowed permissions.
11195            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
11196                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11197                        + pkg.packageName);
11198                continue;
11199            }
11200
11201            final String perm = bp.name;
11202            boolean allowedSig = false;
11203            int grant = GRANT_DENIED;
11204
11205            // Keep track of app op permissions.
11206            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11207                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11208                if (pkgs == null) {
11209                    pkgs = new ArraySet<>();
11210                    mAppOpPermissionPackages.put(bp.name, pkgs);
11211                }
11212                pkgs.add(pkg.packageName);
11213            }
11214
11215            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11216            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11217                    >= Build.VERSION_CODES.M;
11218            switch (level) {
11219                case PermissionInfo.PROTECTION_NORMAL: {
11220                    // For all apps normal permissions are install time ones.
11221                    grant = GRANT_INSTALL;
11222                } break;
11223
11224                case PermissionInfo.PROTECTION_DANGEROUS: {
11225                    // If a permission review is required for legacy apps we represent
11226                    // their permissions as always granted runtime ones since we need
11227                    // to keep the review required permission flag per user while an
11228                    // install permission's state is shared across all users.
11229                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11230                        // For legacy apps dangerous permissions are install time ones.
11231                        grant = GRANT_INSTALL;
11232                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11233                        // For legacy apps that became modern, install becomes runtime.
11234                        grant = GRANT_UPGRADE;
11235                    } else if (mPromoteSystemApps
11236                            && isSystemApp(ps)
11237                            && mExistingSystemPackages.contains(ps.name)) {
11238                        // For legacy system apps, install becomes runtime.
11239                        // We cannot check hasInstallPermission() for system apps since those
11240                        // permissions were granted implicitly and not persisted pre-M.
11241                        grant = GRANT_UPGRADE;
11242                    } else {
11243                        // For modern apps keep runtime permissions unchanged.
11244                        grant = GRANT_RUNTIME;
11245                    }
11246                } break;
11247
11248                case PermissionInfo.PROTECTION_SIGNATURE: {
11249                    // For all apps signature permissions are install time ones.
11250                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11251                    if (allowedSig) {
11252                        grant = GRANT_INSTALL;
11253                    }
11254                } break;
11255            }
11256
11257            if (DEBUG_INSTALL) {
11258                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11259            }
11260
11261            if (grant != GRANT_DENIED) {
11262                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11263                    // If this is an existing, non-system package, then
11264                    // we can't add any new permissions to it.
11265                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11266                        // Except...  if this is a permission that was added
11267                        // to the platform (note: need to only do this when
11268                        // updating the platform).
11269                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11270                            grant = GRANT_DENIED;
11271                        }
11272                    }
11273                }
11274
11275                switch (grant) {
11276                    case GRANT_INSTALL: {
11277                        // Revoke this as runtime permission to handle the case of
11278                        // a runtime permission being downgraded to an install one.
11279                        // Also in permission review mode we keep dangerous permissions
11280                        // for legacy apps
11281                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11282                            if (origPermissions.getRuntimePermissionState(
11283                                    bp.name, userId) != null) {
11284                                // Revoke the runtime permission and clear the flags.
11285                                origPermissions.revokeRuntimePermission(bp, userId);
11286                                origPermissions.updatePermissionFlags(bp, userId,
11287                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11288                                // If we revoked a permission permission, we have to write.
11289                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11290                                        changedRuntimePermissionUserIds, userId);
11291                            }
11292                        }
11293                        // Grant an install permission.
11294                        if (permissionsState.grantInstallPermission(bp) !=
11295                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11296                            changedInstallPermission = true;
11297                        }
11298                    } break;
11299
11300                    case GRANT_RUNTIME: {
11301                        // Grant previously granted runtime permissions.
11302                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11303                            PermissionState permissionState = origPermissions
11304                                    .getRuntimePermissionState(bp.name, userId);
11305                            int flags = permissionState != null
11306                                    ? permissionState.getFlags() : 0;
11307                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11308                                // Don't propagate the permission in a permission review mode if
11309                                // the former was revoked, i.e. marked to not propagate on upgrade.
11310                                // Note that in a permission review mode install permissions are
11311                                // represented as constantly granted runtime ones since we need to
11312                                // keep a per user state associated with the permission. Also the
11313                                // revoke on upgrade flag is no longer applicable and is reset.
11314                                final boolean revokeOnUpgrade = (flags & PackageManager
11315                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11316                                if (revokeOnUpgrade) {
11317                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11318                                    // Since we changed the flags, we have to write.
11319                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11320                                            changedRuntimePermissionUserIds, userId);
11321                                }
11322                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11323                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11324                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11325                                        // If we cannot put the permission as it was,
11326                                        // we have to write.
11327                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11328                                                changedRuntimePermissionUserIds, userId);
11329                                    }
11330                                }
11331
11332                                // If the app supports runtime permissions no need for a review.
11333                                if (mPermissionReviewRequired
11334                                        && appSupportsRuntimePermissions
11335                                        && (flags & PackageManager
11336                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11337                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11338                                    // Since we changed the flags, we have to write.
11339                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11340                                            changedRuntimePermissionUserIds, userId);
11341                                }
11342                            } else if (mPermissionReviewRequired
11343                                    && !appSupportsRuntimePermissions) {
11344                                // For legacy apps that need a permission review, every new
11345                                // runtime permission is granted but it is pending a review.
11346                                // We also need to review only platform defined runtime
11347                                // permissions as these are the only ones the platform knows
11348                                // how to disable the API to simulate revocation as legacy
11349                                // apps don't expect to run with revoked permissions.
11350                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11351                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11352                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11353                                        // We changed the flags, hence have to write.
11354                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11355                                                changedRuntimePermissionUserIds, userId);
11356                                    }
11357                                }
11358                                if (permissionsState.grantRuntimePermission(bp, userId)
11359                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11360                                    // We changed the permission, hence have to write.
11361                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11362                                            changedRuntimePermissionUserIds, userId);
11363                                }
11364                            }
11365                            // Propagate the permission flags.
11366                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11367                        }
11368                    } break;
11369
11370                    case GRANT_UPGRADE: {
11371                        // Grant runtime permissions for a previously held install permission.
11372                        PermissionState permissionState = origPermissions
11373                                .getInstallPermissionState(bp.name);
11374                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11375
11376                        if (origPermissions.revokeInstallPermission(bp)
11377                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11378                            // We will be transferring the permission flags, so clear them.
11379                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11380                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11381                            changedInstallPermission = true;
11382                        }
11383
11384                        // If the permission is not to be promoted to runtime we ignore it and
11385                        // also its other flags as they are not applicable to install permissions.
11386                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11387                            for (int userId : currentUserIds) {
11388                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11389                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11390                                    // Transfer the permission flags.
11391                                    permissionsState.updatePermissionFlags(bp, userId,
11392                                            flags, flags);
11393                                    // If we granted the permission, we have to write.
11394                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11395                                            changedRuntimePermissionUserIds, userId);
11396                                }
11397                            }
11398                        }
11399                    } break;
11400
11401                    default: {
11402                        if (packageOfInterest == null
11403                                || packageOfInterest.equals(pkg.packageName)) {
11404                            Slog.w(TAG, "Not granting permission " + perm
11405                                    + " to package " + pkg.packageName
11406                                    + " because it was previously installed without");
11407                        }
11408                    } break;
11409                }
11410            } else {
11411                if (permissionsState.revokeInstallPermission(bp) !=
11412                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11413                    // Also drop the permission flags.
11414                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11415                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11416                    changedInstallPermission = true;
11417                    Slog.i(TAG, "Un-granting permission " + perm
11418                            + " from package " + pkg.packageName
11419                            + " (protectionLevel=" + bp.protectionLevel
11420                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11421                            + ")");
11422                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11423                    // Don't print warning for app op permissions, since it is fine for them
11424                    // not to be granted, there is a UI for the user to decide.
11425                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11426                        Slog.w(TAG, "Not granting permission " + perm
11427                                + " to package " + pkg.packageName
11428                                + " (protectionLevel=" + bp.protectionLevel
11429                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11430                                + ")");
11431                    }
11432                }
11433            }
11434        }
11435
11436        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11437                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11438            // This is the first that we have heard about this package, so the
11439            // permissions we have now selected are fixed until explicitly
11440            // changed.
11441            ps.installPermissionsFixed = true;
11442        }
11443
11444        // Persist the runtime permissions state for users with changes. If permissions
11445        // were revoked because no app in the shared user declares them we have to
11446        // write synchronously to avoid losing runtime permissions state.
11447        for (int userId : changedRuntimePermissionUserIds) {
11448            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11449        }
11450    }
11451
11452    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11453        boolean allowed = false;
11454        final int NP = PackageParser.NEW_PERMISSIONS.length;
11455        for (int ip=0; ip<NP; ip++) {
11456            final PackageParser.NewPermissionInfo npi
11457                    = PackageParser.NEW_PERMISSIONS[ip];
11458            if (npi.name.equals(perm)
11459                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11460                allowed = true;
11461                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11462                        + pkg.packageName);
11463                break;
11464            }
11465        }
11466        return allowed;
11467    }
11468
11469    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11470            BasePermission bp, PermissionsState origPermissions) {
11471        boolean privilegedPermission = (bp.protectionLevel
11472                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11473        boolean privappPermissionsDisable =
11474                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11475        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11476        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11477        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11478                && !platformPackage && platformPermission) {
11479            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11480                    .getPrivAppPermissions(pkg.packageName);
11481            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11482            if (!whitelisted) {
11483                Slog.w(TAG, "Privileged permission " + perm + " for package "
11484                        + pkg.packageName + " - not in privapp-permissions whitelist");
11485                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11486                    return false;
11487                }
11488            }
11489        }
11490        boolean allowed = (compareSignatures(
11491                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11492                        == PackageManager.SIGNATURE_MATCH)
11493                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11494                        == PackageManager.SIGNATURE_MATCH);
11495        if (!allowed && privilegedPermission) {
11496            if (isSystemApp(pkg)) {
11497                // For updated system applications, a system permission
11498                // is granted only if it had been defined by the original application.
11499                if (pkg.isUpdatedSystemApp()) {
11500                    final PackageSetting sysPs = mSettings
11501                            .getDisabledSystemPkgLPr(pkg.packageName);
11502                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11503                        // If the original was granted this permission, we take
11504                        // that grant decision as read and propagate it to the
11505                        // update.
11506                        if (sysPs.isPrivileged()) {
11507                            allowed = true;
11508                        }
11509                    } else {
11510                        // The system apk may have been updated with an older
11511                        // version of the one on the data partition, but which
11512                        // granted a new system permission that it didn't have
11513                        // before.  In this case we do want to allow the app to
11514                        // now get the new permission if the ancestral apk is
11515                        // privileged to get it.
11516                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11517                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11518                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11519                                    allowed = true;
11520                                    break;
11521                                }
11522                            }
11523                        }
11524                        // Also if a privileged parent package on the system image or any of
11525                        // its children requested a privileged permission, the updated child
11526                        // packages can also get the permission.
11527                        if (pkg.parentPackage != null) {
11528                            final PackageSetting disabledSysParentPs = mSettings
11529                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11530                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11531                                    && disabledSysParentPs.isPrivileged()) {
11532                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11533                                    allowed = true;
11534                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11535                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11536                                    for (int i = 0; i < count; i++) {
11537                                        PackageParser.Package disabledSysChildPkg =
11538                                                disabledSysParentPs.pkg.childPackages.get(i);
11539                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11540                                                perm)) {
11541                                            allowed = true;
11542                                            break;
11543                                        }
11544                                    }
11545                                }
11546                            }
11547                        }
11548                    }
11549                } else {
11550                    allowed = isPrivilegedApp(pkg);
11551                }
11552            }
11553        }
11554        if (!allowed) {
11555            if (!allowed && (bp.protectionLevel
11556                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11557                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11558                // If this was a previously normal/dangerous permission that got moved
11559                // to a system permission as part of the runtime permission redesign, then
11560                // we still want to blindly grant it to old apps.
11561                allowed = true;
11562            }
11563            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11564                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11565                // If this permission is to be granted to the system installer and
11566                // this app is an installer, then it gets the permission.
11567                allowed = true;
11568            }
11569            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11570                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11571                // If this permission is to be granted to the system verifier and
11572                // this app is a verifier, then it gets the permission.
11573                allowed = true;
11574            }
11575            if (!allowed && (bp.protectionLevel
11576                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11577                    && isSystemApp(pkg)) {
11578                // Any pre-installed system app is allowed to get this permission.
11579                allowed = true;
11580            }
11581            if (!allowed && (bp.protectionLevel
11582                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11583                // For development permissions, a development permission
11584                // is granted only if it was already granted.
11585                allowed = origPermissions.hasInstallPermission(perm);
11586            }
11587            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11588                    && pkg.packageName.equals(mSetupWizardPackage)) {
11589                // If this permission is to be granted to the system setup wizard and
11590                // this app is a setup wizard, then it gets the permission.
11591                allowed = true;
11592            }
11593        }
11594        return allowed;
11595    }
11596
11597    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11598        final int permCount = pkg.requestedPermissions.size();
11599        for (int j = 0; j < permCount; j++) {
11600            String requestedPermission = pkg.requestedPermissions.get(j);
11601            if (permission.equals(requestedPermission)) {
11602                return true;
11603            }
11604        }
11605        return false;
11606    }
11607
11608    final class ActivityIntentResolver
11609            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11610        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11611                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11612            if (!sUserManager.exists(userId)) return null;
11613            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11614                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11615                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11616            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11617                    isEphemeral, userId);
11618        }
11619
11620        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11621                int userId) {
11622            if (!sUserManager.exists(userId)) return null;
11623            mFlags = flags;
11624            return super.queryIntent(intent, resolvedType,
11625                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11626                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11627                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11628        }
11629
11630        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11631                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11632            if (!sUserManager.exists(userId)) return null;
11633            if (packageActivities == null) {
11634                return null;
11635            }
11636            mFlags = flags;
11637            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11638            final boolean vislbleToEphemeral =
11639                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11640            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11641            final int N = packageActivities.size();
11642            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11643                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11644
11645            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11646            for (int i = 0; i < N; ++i) {
11647                intentFilters = packageActivities.get(i).intents;
11648                if (intentFilters != null && intentFilters.size() > 0) {
11649                    PackageParser.ActivityIntentInfo[] array =
11650                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11651                    intentFilters.toArray(array);
11652                    listCut.add(array);
11653                }
11654            }
11655            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11656                    vislbleToEphemeral, isEphemeral, listCut, userId);
11657        }
11658
11659        /**
11660         * Finds a privileged activity that matches the specified activity names.
11661         */
11662        private PackageParser.Activity findMatchingActivity(
11663                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11664            for (PackageParser.Activity sysActivity : activityList) {
11665                if (sysActivity.info.name.equals(activityInfo.name)) {
11666                    return sysActivity;
11667                }
11668                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11669                    return sysActivity;
11670                }
11671                if (sysActivity.info.targetActivity != null) {
11672                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11673                        return sysActivity;
11674                    }
11675                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11676                        return sysActivity;
11677                    }
11678                }
11679            }
11680            return null;
11681        }
11682
11683        public class IterGenerator<E> {
11684            public Iterator<E> generate(ActivityIntentInfo info) {
11685                return null;
11686            }
11687        }
11688
11689        public class ActionIterGenerator extends IterGenerator<String> {
11690            @Override
11691            public Iterator<String> generate(ActivityIntentInfo info) {
11692                return info.actionsIterator();
11693            }
11694        }
11695
11696        public class CategoriesIterGenerator extends IterGenerator<String> {
11697            @Override
11698            public Iterator<String> generate(ActivityIntentInfo info) {
11699                return info.categoriesIterator();
11700            }
11701        }
11702
11703        public class SchemesIterGenerator extends IterGenerator<String> {
11704            @Override
11705            public Iterator<String> generate(ActivityIntentInfo info) {
11706                return info.schemesIterator();
11707            }
11708        }
11709
11710        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11711            @Override
11712            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11713                return info.authoritiesIterator();
11714            }
11715        }
11716
11717        /**
11718         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11719         * MODIFIED. Do not pass in a list that should not be changed.
11720         */
11721        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11722                IterGenerator<T> generator, Iterator<T> searchIterator) {
11723            // loop through the set of actions; every one must be found in the intent filter
11724            while (searchIterator.hasNext()) {
11725                // we must have at least one filter in the list to consider a match
11726                if (intentList.size() == 0) {
11727                    break;
11728                }
11729
11730                final T searchAction = searchIterator.next();
11731
11732                // loop through the set of intent filters
11733                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11734                while (intentIter.hasNext()) {
11735                    final ActivityIntentInfo intentInfo = intentIter.next();
11736                    boolean selectionFound = false;
11737
11738                    // loop through the intent filter's selection criteria; at least one
11739                    // of them must match the searched criteria
11740                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11741                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11742                        final T intentSelection = intentSelectionIter.next();
11743                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11744                            selectionFound = true;
11745                            break;
11746                        }
11747                    }
11748
11749                    // the selection criteria wasn't found in this filter's set; this filter
11750                    // is not a potential match
11751                    if (!selectionFound) {
11752                        intentIter.remove();
11753                    }
11754                }
11755            }
11756        }
11757
11758        private boolean isProtectedAction(ActivityIntentInfo filter) {
11759            final Iterator<String> actionsIter = filter.actionsIterator();
11760            while (actionsIter != null && actionsIter.hasNext()) {
11761                final String filterAction = actionsIter.next();
11762                if (PROTECTED_ACTIONS.contains(filterAction)) {
11763                    return true;
11764                }
11765            }
11766            return false;
11767        }
11768
11769        /**
11770         * Adjusts the priority of the given intent filter according to policy.
11771         * <p>
11772         * <ul>
11773         * <li>The priority for non privileged applications is capped to '0'</li>
11774         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11775         * <li>The priority for unbundled updates to privileged applications is capped to the
11776         *      priority defined on the system partition</li>
11777         * </ul>
11778         * <p>
11779         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11780         * allowed to obtain any priority on any action.
11781         */
11782        private void adjustPriority(
11783                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11784            // nothing to do; priority is fine as-is
11785            if (intent.getPriority() <= 0) {
11786                return;
11787            }
11788
11789            final ActivityInfo activityInfo = intent.activity.info;
11790            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11791
11792            final boolean privilegedApp =
11793                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11794            if (!privilegedApp) {
11795                // non-privileged applications can never define a priority >0
11796                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11797                        + " package: " + applicationInfo.packageName
11798                        + " activity: " + intent.activity.className
11799                        + " origPrio: " + intent.getPriority());
11800                intent.setPriority(0);
11801                return;
11802            }
11803
11804            if (systemActivities == null) {
11805                // the system package is not disabled; we're parsing the system partition
11806                if (isProtectedAction(intent)) {
11807                    if (mDeferProtectedFilters) {
11808                        // We can't deal with these just yet. No component should ever obtain a
11809                        // >0 priority for a protected actions, with ONE exception -- the setup
11810                        // wizard. The setup wizard, however, cannot be known until we're able to
11811                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11812                        // until all intent filters have been processed. Chicken, meet egg.
11813                        // Let the filter temporarily have a high priority and rectify the
11814                        // priorities after all system packages have been scanned.
11815                        mProtectedFilters.add(intent);
11816                        if (DEBUG_FILTERS) {
11817                            Slog.i(TAG, "Protected action; save for later;"
11818                                    + " package: " + applicationInfo.packageName
11819                                    + " activity: " + intent.activity.className
11820                                    + " origPrio: " + intent.getPriority());
11821                        }
11822                        return;
11823                    } else {
11824                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11825                            Slog.i(TAG, "No setup wizard;"
11826                                + " All protected intents capped to priority 0");
11827                        }
11828                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11829                            if (DEBUG_FILTERS) {
11830                                Slog.i(TAG, "Found setup wizard;"
11831                                    + " allow priority " + intent.getPriority() + ";"
11832                                    + " package: " + intent.activity.info.packageName
11833                                    + " activity: " + intent.activity.className
11834                                    + " priority: " + intent.getPriority());
11835                            }
11836                            // setup wizard gets whatever it wants
11837                            return;
11838                        }
11839                        Slog.w(TAG, "Protected action; cap priority to 0;"
11840                                + " package: " + intent.activity.info.packageName
11841                                + " activity: " + intent.activity.className
11842                                + " origPrio: " + intent.getPriority());
11843                        intent.setPriority(0);
11844                        return;
11845                    }
11846                }
11847                // privileged apps on the system image get whatever priority they request
11848                return;
11849            }
11850
11851            // privileged app unbundled update ... try to find the same activity
11852            final PackageParser.Activity foundActivity =
11853                    findMatchingActivity(systemActivities, activityInfo);
11854            if (foundActivity == null) {
11855                // this is a new activity; it cannot obtain >0 priority
11856                if (DEBUG_FILTERS) {
11857                    Slog.i(TAG, "New activity; cap priority to 0;"
11858                            + " package: " + applicationInfo.packageName
11859                            + " activity: " + intent.activity.className
11860                            + " origPrio: " + intent.getPriority());
11861                }
11862                intent.setPriority(0);
11863                return;
11864            }
11865
11866            // found activity, now check for filter equivalence
11867
11868            // a shallow copy is enough; we modify the list, not its contents
11869            final List<ActivityIntentInfo> intentListCopy =
11870                    new ArrayList<>(foundActivity.intents);
11871            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11872
11873            // find matching action subsets
11874            final Iterator<String> actionsIterator = intent.actionsIterator();
11875            if (actionsIterator != null) {
11876                getIntentListSubset(
11877                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11878                if (intentListCopy.size() == 0) {
11879                    // no more intents to match; we're not equivalent
11880                    if (DEBUG_FILTERS) {
11881                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11882                                + " package: " + applicationInfo.packageName
11883                                + " activity: " + intent.activity.className
11884                                + " origPrio: " + intent.getPriority());
11885                    }
11886                    intent.setPriority(0);
11887                    return;
11888                }
11889            }
11890
11891            // find matching category subsets
11892            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11893            if (categoriesIterator != null) {
11894                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11895                        categoriesIterator);
11896                if (intentListCopy.size() == 0) {
11897                    // no more intents to match; we're not equivalent
11898                    if (DEBUG_FILTERS) {
11899                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11900                                + " package: " + applicationInfo.packageName
11901                                + " activity: " + intent.activity.className
11902                                + " origPrio: " + intent.getPriority());
11903                    }
11904                    intent.setPriority(0);
11905                    return;
11906                }
11907            }
11908
11909            // find matching schemes subsets
11910            final Iterator<String> schemesIterator = intent.schemesIterator();
11911            if (schemesIterator != null) {
11912                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11913                        schemesIterator);
11914                if (intentListCopy.size() == 0) {
11915                    // no more intents to match; we're not equivalent
11916                    if (DEBUG_FILTERS) {
11917                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11918                                + " package: " + applicationInfo.packageName
11919                                + " activity: " + intent.activity.className
11920                                + " origPrio: " + intent.getPriority());
11921                    }
11922                    intent.setPriority(0);
11923                    return;
11924                }
11925            }
11926
11927            // find matching authorities subsets
11928            final Iterator<IntentFilter.AuthorityEntry>
11929                    authoritiesIterator = intent.authoritiesIterator();
11930            if (authoritiesIterator != null) {
11931                getIntentListSubset(intentListCopy,
11932                        new AuthoritiesIterGenerator(),
11933                        authoritiesIterator);
11934                if (intentListCopy.size() == 0) {
11935                    // no more intents to match; we're not equivalent
11936                    if (DEBUG_FILTERS) {
11937                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11938                                + " package: " + applicationInfo.packageName
11939                                + " activity: " + intent.activity.className
11940                                + " origPrio: " + intent.getPriority());
11941                    }
11942                    intent.setPriority(0);
11943                    return;
11944                }
11945            }
11946
11947            // we found matching filter(s); app gets the max priority of all intents
11948            int cappedPriority = 0;
11949            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11950                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11951            }
11952            if (intent.getPriority() > cappedPriority) {
11953                if (DEBUG_FILTERS) {
11954                    Slog.i(TAG, "Found matching filter(s);"
11955                            + " cap priority to " + cappedPriority + ";"
11956                            + " package: " + applicationInfo.packageName
11957                            + " activity: " + intent.activity.className
11958                            + " origPrio: " + intent.getPriority());
11959                }
11960                intent.setPriority(cappedPriority);
11961                return;
11962            }
11963            // all this for nothing; the requested priority was <= what was on the system
11964        }
11965
11966        public final void addActivity(PackageParser.Activity a, String type) {
11967            mActivities.put(a.getComponentName(), a);
11968            if (DEBUG_SHOW_INFO)
11969                Log.v(
11970                TAG, "  " + type + " " +
11971                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11972            if (DEBUG_SHOW_INFO)
11973                Log.v(TAG, "    Class=" + a.info.name);
11974            final int NI = a.intents.size();
11975            for (int j=0; j<NI; j++) {
11976                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11977                if ("activity".equals(type)) {
11978                    final PackageSetting ps =
11979                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11980                    final List<PackageParser.Activity> systemActivities =
11981                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11982                    adjustPriority(systemActivities, intent);
11983                }
11984                if (DEBUG_SHOW_INFO) {
11985                    Log.v(TAG, "    IntentFilter:");
11986                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11987                }
11988                if (!intent.debugCheck()) {
11989                    Log.w(TAG, "==> For Activity " + a.info.name);
11990                }
11991                addFilter(intent);
11992            }
11993        }
11994
11995        public final void removeActivity(PackageParser.Activity a, String type) {
11996            mActivities.remove(a.getComponentName());
11997            if (DEBUG_SHOW_INFO) {
11998                Log.v(TAG, "  " + type + " "
11999                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12000                                : a.info.name) + ":");
12001                Log.v(TAG, "    Class=" + a.info.name);
12002            }
12003            final int NI = a.intents.size();
12004            for (int j=0; j<NI; j++) {
12005                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12006                if (DEBUG_SHOW_INFO) {
12007                    Log.v(TAG, "    IntentFilter:");
12008                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12009                }
12010                removeFilter(intent);
12011            }
12012        }
12013
12014        @Override
12015        protected boolean allowFilterResult(
12016                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12017            ActivityInfo filterAi = filter.activity.info;
12018            for (int i=dest.size()-1; i>=0; i--) {
12019                ActivityInfo destAi = dest.get(i).activityInfo;
12020                if (destAi.name == filterAi.name
12021                        && destAi.packageName == filterAi.packageName) {
12022                    return false;
12023                }
12024            }
12025            return true;
12026        }
12027
12028        @Override
12029        protected ActivityIntentInfo[] newArray(int size) {
12030            return new ActivityIntentInfo[size];
12031        }
12032
12033        @Override
12034        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12035            if (!sUserManager.exists(userId)) return true;
12036            PackageParser.Package p = filter.activity.owner;
12037            if (p != null) {
12038                PackageSetting ps = (PackageSetting)p.mExtras;
12039                if (ps != null) {
12040                    // System apps are never considered stopped for purposes of
12041                    // filtering, because there may be no way for the user to
12042                    // actually re-launch them.
12043                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12044                            && ps.getStopped(userId);
12045                }
12046            }
12047            return false;
12048        }
12049
12050        @Override
12051        protected boolean isPackageForFilter(String packageName,
12052                PackageParser.ActivityIntentInfo info) {
12053            return packageName.equals(info.activity.owner.packageName);
12054        }
12055
12056        @Override
12057        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12058                int match, int userId) {
12059            if (!sUserManager.exists(userId)) return null;
12060            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12061                return null;
12062            }
12063            final PackageParser.Activity activity = info.activity;
12064            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12065            if (ps == null) {
12066                return null;
12067            }
12068            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12069                    ps.readUserState(userId), userId);
12070            if (ai == null) {
12071                return null;
12072            }
12073            final ResolveInfo res = new ResolveInfo();
12074            res.activityInfo = ai;
12075            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12076                res.filter = info;
12077            }
12078            if (info != null) {
12079                res.handleAllWebDataURI = info.handleAllWebDataURI();
12080            }
12081            res.priority = info.getPriority();
12082            res.preferredOrder = activity.owner.mPreferredOrder;
12083            //System.out.println("Result: " + res.activityInfo.className +
12084            //                   " = " + res.priority);
12085            res.match = match;
12086            res.isDefault = info.hasDefault;
12087            res.labelRes = info.labelRes;
12088            res.nonLocalizedLabel = info.nonLocalizedLabel;
12089            if (userNeedsBadging(userId)) {
12090                res.noResourceId = true;
12091            } else {
12092                res.icon = info.icon;
12093            }
12094            res.iconResourceId = info.icon;
12095            res.system = res.activityInfo.applicationInfo.isSystemApp();
12096            return res;
12097        }
12098
12099        @Override
12100        protected void sortResults(List<ResolveInfo> results) {
12101            Collections.sort(results, mResolvePrioritySorter);
12102        }
12103
12104        @Override
12105        protected void dumpFilter(PrintWriter out, String prefix,
12106                PackageParser.ActivityIntentInfo filter) {
12107            out.print(prefix); out.print(
12108                    Integer.toHexString(System.identityHashCode(filter.activity)));
12109                    out.print(' ');
12110                    filter.activity.printComponentShortName(out);
12111                    out.print(" filter ");
12112                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12113        }
12114
12115        @Override
12116        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12117            return filter.activity;
12118        }
12119
12120        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12121            PackageParser.Activity activity = (PackageParser.Activity)label;
12122            out.print(prefix); out.print(
12123                    Integer.toHexString(System.identityHashCode(activity)));
12124                    out.print(' ');
12125                    activity.printComponentShortName(out);
12126            if (count > 1) {
12127                out.print(" ("); out.print(count); out.print(" filters)");
12128            }
12129            out.println();
12130        }
12131
12132        // Keys are String (activity class name), values are Activity.
12133        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12134                = new ArrayMap<ComponentName, PackageParser.Activity>();
12135        private int mFlags;
12136    }
12137
12138    private final class ServiceIntentResolver
12139            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12140        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12141                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12142            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12143            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12144                    isEphemeral, userId);
12145        }
12146
12147        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12148                int userId) {
12149            if (!sUserManager.exists(userId)) return null;
12150            mFlags = flags;
12151            return super.queryIntent(intent, resolvedType,
12152                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12153                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12154                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12155        }
12156
12157        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12158                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12159            if (!sUserManager.exists(userId)) return null;
12160            if (packageServices == null) {
12161                return null;
12162            }
12163            mFlags = flags;
12164            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12165            final boolean vislbleToEphemeral =
12166                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12167            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12168            final int N = packageServices.size();
12169            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12170                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12171
12172            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12173            for (int i = 0; i < N; ++i) {
12174                intentFilters = packageServices.get(i).intents;
12175                if (intentFilters != null && intentFilters.size() > 0) {
12176                    PackageParser.ServiceIntentInfo[] array =
12177                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12178                    intentFilters.toArray(array);
12179                    listCut.add(array);
12180                }
12181            }
12182            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12183                    vislbleToEphemeral, isEphemeral, listCut, userId);
12184        }
12185
12186        public final void addService(PackageParser.Service s) {
12187            mServices.put(s.getComponentName(), s);
12188            if (DEBUG_SHOW_INFO) {
12189                Log.v(TAG, "  "
12190                        + (s.info.nonLocalizedLabel != null
12191                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12192                Log.v(TAG, "    Class=" + s.info.name);
12193            }
12194            final int NI = s.intents.size();
12195            int j;
12196            for (j=0; j<NI; j++) {
12197                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12198                if (DEBUG_SHOW_INFO) {
12199                    Log.v(TAG, "    IntentFilter:");
12200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12201                }
12202                if (!intent.debugCheck()) {
12203                    Log.w(TAG, "==> For Service " + s.info.name);
12204                }
12205                addFilter(intent);
12206            }
12207        }
12208
12209        public final void removeService(PackageParser.Service s) {
12210            mServices.remove(s.getComponentName());
12211            if (DEBUG_SHOW_INFO) {
12212                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12213                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12214                Log.v(TAG, "    Class=" + s.info.name);
12215            }
12216            final int NI = s.intents.size();
12217            int j;
12218            for (j=0; j<NI; j++) {
12219                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12220                if (DEBUG_SHOW_INFO) {
12221                    Log.v(TAG, "    IntentFilter:");
12222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12223                }
12224                removeFilter(intent);
12225            }
12226        }
12227
12228        @Override
12229        protected boolean allowFilterResult(
12230                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12231            ServiceInfo filterSi = filter.service.info;
12232            for (int i=dest.size()-1; i>=0; i--) {
12233                ServiceInfo destAi = dest.get(i).serviceInfo;
12234                if (destAi.name == filterSi.name
12235                        && destAi.packageName == filterSi.packageName) {
12236                    return false;
12237                }
12238            }
12239            return true;
12240        }
12241
12242        @Override
12243        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12244            return new PackageParser.ServiceIntentInfo[size];
12245        }
12246
12247        @Override
12248        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12249            if (!sUserManager.exists(userId)) return true;
12250            PackageParser.Package p = filter.service.owner;
12251            if (p != null) {
12252                PackageSetting ps = (PackageSetting)p.mExtras;
12253                if (ps != null) {
12254                    // System apps are never considered stopped for purposes of
12255                    // filtering, because there may be no way for the user to
12256                    // actually re-launch them.
12257                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12258                            && ps.getStopped(userId);
12259                }
12260            }
12261            return false;
12262        }
12263
12264        @Override
12265        protected boolean isPackageForFilter(String packageName,
12266                PackageParser.ServiceIntentInfo info) {
12267            return packageName.equals(info.service.owner.packageName);
12268        }
12269
12270        @Override
12271        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12272                int match, int userId) {
12273            if (!sUserManager.exists(userId)) return null;
12274            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12275            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12276                return null;
12277            }
12278            final PackageParser.Service service = info.service;
12279            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12280            if (ps == null) {
12281                return null;
12282            }
12283            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12284                    ps.readUserState(userId), userId);
12285            if (si == null) {
12286                return null;
12287            }
12288            final ResolveInfo res = new ResolveInfo();
12289            res.serviceInfo = si;
12290            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12291                res.filter = filter;
12292            }
12293            res.priority = info.getPriority();
12294            res.preferredOrder = service.owner.mPreferredOrder;
12295            res.match = match;
12296            res.isDefault = info.hasDefault;
12297            res.labelRes = info.labelRes;
12298            res.nonLocalizedLabel = info.nonLocalizedLabel;
12299            res.icon = info.icon;
12300            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12301            return res;
12302        }
12303
12304        @Override
12305        protected void sortResults(List<ResolveInfo> results) {
12306            Collections.sort(results, mResolvePrioritySorter);
12307        }
12308
12309        @Override
12310        protected void dumpFilter(PrintWriter out, String prefix,
12311                PackageParser.ServiceIntentInfo filter) {
12312            out.print(prefix); out.print(
12313                    Integer.toHexString(System.identityHashCode(filter.service)));
12314                    out.print(' ');
12315                    filter.service.printComponentShortName(out);
12316                    out.print(" filter ");
12317                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12318        }
12319
12320        @Override
12321        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12322            return filter.service;
12323        }
12324
12325        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12326            PackageParser.Service service = (PackageParser.Service)label;
12327            out.print(prefix); out.print(
12328                    Integer.toHexString(System.identityHashCode(service)));
12329                    out.print(' ');
12330                    service.printComponentShortName(out);
12331            if (count > 1) {
12332                out.print(" ("); out.print(count); out.print(" filters)");
12333            }
12334            out.println();
12335        }
12336
12337//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12338//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12339//            final List<ResolveInfo> retList = Lists.newArrayList();
12340//            while (i.hasNext()) {
12341//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12342//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12343//                    retList.add(resolveInfo);
12344//                }
12345//            }
12346//            return retList;
12347//        }
12348
12349        // Keys are String (activity class name), values are Activity.
12350        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12351                = new ArrayMap<ComponentName, PackageParser.Service>();
12352        private int mFlags;
12353    }
12354
12355    private final class ProviderIntentResolver
12356            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12357        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12358                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12359            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12360            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12361                    isEphemeral, userId);
12362        }
12363
12364        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12365                int userId) {
12366            if (!sUserManager.exists(userId))
12367                return null;
12368            mFlags = flags;
12369            return super.queryIntent(intent, resolvedType,
12370                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12371                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12372                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12373        }
12374
12375        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12376                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12377            if (!sUserManager.exists(userId))
12378                return null;
12379            if (packageProviders == null) {
12380                return null;
12381            }
12382            mFlags = flags;
12383            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12384            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12385            final boolean vislbleToEphemeral =
12386                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12387            final int N = packageProviders.size();
12388            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12389                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12390
12391            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12392            for (int i = 0; i < N; ++i) {
12393                intentFilters = packageProviders.get(i).intents;
12394                if (intentFilters != null && intentFilters.size() > 0) {
12395                    PackageParser.ProviderIntentInfo[] array =
12396                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12397                    intentFilters.toArray(array);
12398                    listCut.add(array);
12399                }
12400            }
12401            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12402                    vislbleToEphemeral, isEphemeral, listCut, userId);
12403        }
12404
12405        public final void addProvider(PackageParser.Provider p) {
12406            if (mProviders.containsKey(p.getComponentName())) {
12407                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12408                return;
12409            }
12410
12411            mProviders.put(p.getComponentName(), p);
12412            if (DEBUG_SHOW_INFO) {
12413                Log.v(TAG, "  "
12414                        + (p.info.nonLocalizedLabel != null
12415                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12416                Log.v(TAG, "    Class=" + p.info.name);
12417            }
12418            final int NI = p.intents.size();
12419            int j;
12420            for (j = 0; j < NI; j++) {
12421                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12422                if (DEBUG_SHOW_INFO) {
12423                    Log.v(TAG, "    IntentFilter:");
12424                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12425                }
12426                if (!intent.debugCheck()) {
12427                    Log.w(TAG, "==> For Provider " + p.info.name);
12428                }
12429                addFilter(intent);
12430            }
12431        }
12432
12433        public final void removeProvider(PackageParser.Provider p) {
12434            mProviders.remove(p.getComponentName());
12435            if (DEBUG_SHOW_INFO) {
12436                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12437                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12438                Log.v(TAG, "    Class=" + p.info.name);
12439            }
12440            final int NI = p.intents.size();
12441            int j;
12442            for (j = 0; j < NI; j++) {
12443                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12444                if (DEBUG_SHOW_INFO) {
12445                    Log.v(TAG, "    IntentFilter:");
12446                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12447                }
12448                removeFilter(intent);
12449            }
12450        }
12451
12452        @Override
12453        protected boolean allowFilterResult(
12454                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12455            ProviderInfo filterPi = filter.provider.info;
12456            for (int i = dest.size() - 1; i >= 0; i--) {
12457                ProviderInfo destPi = dest.get(i).providerInfo;
12458                if (destPi.name == filterPi.name
12459                        && destPi.packageName == filterPi.packageName) {
12460                    return false;
12461                }
12462            }
12463            return true;
12464        }
12465
12466        @Override
12467        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12468            return new PackageParser.ProviderIntentInfo[size];
12469        }
12470
12471        @Override
12472        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12473            if (!sUserManager.exists(userId))
12474                return true;
12475            PackageParser.Package p = filter.provider.owner;
12476            if (p != null) {
12477                PackageSetting ps = (PackageSetting) p.mExtras;
12478                if (ps != null) {
12479                    // System apps are never considered stopped for purposes of
12480                    // filtering, because there may be no way for the user to
12481                    // actually re-launch them.
12482                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12483                            && ps.getStopped(userId);
12484                }
12485            }
12486            return false;
12487        }
12488
12489        @Override
12490        protected boolean isPackageForFilter(String packageName,
12491                PackageParser.ProviderIntentInfo info) {
12492            return packageName.equals(info.provider.owner.packageName);
12493        }
12494
12495        @Override
12496        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12497                int match, int userId) {
12498            if (!sUserManager.exists(userId))
12499                return null;
12500            final PackageParser.ProviderIntentInfo info = filter;
12501            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12502                return null;
12503            }
12504            final PackageParser.Provider provider = info.provider;
12505            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12506            if (ps == null) {
12507                return null;
12508            }
12509            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12510                    ps.readUserState(userId), userId);
12511            if (pi == null) {
12512                return null;
12513            }
12514            final ResolveInfo res = new ResolveInfo();
12515            res.providerInfo = pi;
12516            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12517                res.filter = filter;
12518            }
12519            res.priority = info.getPriority();
12520            res.preferredOrder = provider.owner.mPreferredOrder;
12521            res.match = match;
12522            res.isDefault = info.hasDefault;
12523            res.labelRes = info.labelRes;
12524            res.nonLocalizedLabel = info.nonLocalizedLabel;
12525            res.icon = info.icon;
12526            res.system = res.providerInfo.applicationInfo.isSystemApp();
12527            return res;
12528        }
12529
12530        @Override
12531        protected void sortResults(List<ResolveInfo> results) {
12532            Collections.sort(results, mResolvePrioritySorter);
12533        }
12534
12535        @Override
12536        protected void dumpFilter(PrintWriter out, String prefix,
12537                PackageParser.ProviderIntentInfo filter) {
12538            out.print(prefix);
12539            out.print(
12540                    Integer.toHexString(System.identityHashCode(filter.provider)));
12541            out.print(' ');
12542            filter.provider.printComponentShortName(out);
12543            out.print(" filter ");
12544            out.println(Integer.toHexString(System.identityHashCode(filter)));
12545        }
12546
12547        @Override
12548        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12549            return filter.provider;
12550        }
12551
12552        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12553            PackageParser.Provider provider = (PackageParser.Provider)label;
12554            out.print(prefix); out.print(
12555                    Integer.toHexString(System.identityHashCode(provider)));
12556                    out.print(' ');
12557                    provider.printComponentShortName(out);
12558            if (count > 1) {
12559                out.print(" ("); out.print(count); out.print(" filters)");
12560            }
12561            out.println();
12562        }
12563
12564        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12565                = new ArrayMap<ComponentName, PackageParser.Provider>();
12566        private int mFlags;
12567    }
12568
12569    static final class EphemeralIntentResolver
12570            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12571        /**
12572         * The result that has the highest defined order. Ordering applies on a
12573         * per-package basis. Mapping is from package name to Pair of order and
12574         * EphemeralResolveInfo.
12575         * <p>
12576         * NOTE: This is implemented as a field variable for convenience and efficiency.
12577         * By having a field variable, we're able to track filter ordering as soon as
12578         * a non-zero order is defined. Otherwise, multiple loops across the result set
12579         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12580         * this needs to be contained entirely within {@link #filterResults()}.
12581         */
12582        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12583
12584        @Override
12585        protected EphemeralResponse[] newArray(int size) {
12586            return new EphemeralResponse[size];
12587        }
12588
12589        @Override
12590        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12591            return true;
12592        }
12593
12594        @Override
12595        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12596                int userId) {
12597            if (!sUserManager.exists(userId)) {
12598                return null;
12599            }
12600            final String packageName = responseObj.resolveInfo.getPackageName();
12601            final Integer order = responseObj.getOrder();
12602            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12603                    mOrderResult.get(packageName);
12604            // ordering is enabled and this item's order isn't high enough
12605            if (lastOrderResult != null && lastOrderResult.first >= order) {
12606                return null;
12607            }
12608            final EphemeralResolveInfo res = responseObj.resolveInfo;
12609            if (order > 0) {
12610                // non-zero order, enable ordering
12611                mOrderResult.put(packageName, new Pair<>(order, res));
12612            }
12613            return responseObj;
12614        }
12615
12616        @Override
12617        protected void filterResults(List<EphemeralResponse> results) {
12618            // only do work if ordering is enabled [most of the time it won't be]
12619            if (mOrderResult.size() == 0) {
12620                return;
12621            }
12622            int resultSize = results.size();
12623            for (int i = 0; i < resultSize; i++) {
12624                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12625                final String packageName = info.getPackageName();
12626                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12627                if (savedInfo == null) {
12628                    // package doesn't having ordering
12629                    continue;
12630                }
12631                if (savedInfo.second == info) {
12632                    // circled back to the highest ordered item; remove from order list
12633                    mOrderResult.remove(savedInfo);
12634                    if (mOrderResult.size() == 0) {
12635                        // no more ordered items
12636                        break;
12637                    }
12638                    continue;
12639                }
12640                // item has a worse order, remove it from the result list
12641                results.remove(i);
12642                resultSize--;
12643                i--;
12644            }
12645        }
12646    }
12647
12648    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12649            new Comparator<ResolveInfo>() {
12650        public int compare(ResolveInfo r1, ResolveInfo r2) {
12651            int v1 = r1.priority;
12652            int v2 = r2.priority;
12653            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12654            if (v1 != v2) {
12655                return (v1 > v2) ? -1 : 1;
12656            }
12657            v1 = r1.preferredOrder;
12658            v2 = r2.preferredOrder;
12659            if (v1 != v2) {
12660                return (v1 > v2) ? -1 : 1;
12661            }
12662            if (r1.isDefault != r2.isDefault) {
12663                return r1.isDefault ? -1 : 1;
12664            }
12665            v1 = r1.match;
12666            v2 = r2.match;
12667            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12668            if (v1 != v2) {
12669                return (v1 > v2) ? -1 : 1;
12670            }
12671            if (r1.system != r2.system) {
12672                return r1.system ? -1 : 1;
12673            }
12674            if (r1.activityInfo != null) {
12675                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12676            }
12677            if (r1.serviceInfo != null) {
12678                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12679            }
12680            if (r1.providerInfo != null) {
12681                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12682            }
12683            return 0;
12684        }
12685    };
12686
12687    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12688            new Comparator<ProviderInfo>() {
12689        public int compare(ProviderInfo p1, ProviderInfo p2) {
12690            final int v1 = p1.initOrder;
12691            final int v2 = p2.initOrder;
12692            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12693        }
12694    };
12695
12696    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12697            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12698            final int[] userIds) {
12699        mHandler.post(new Runnable() {
12700            @Override
12701            public void run() {
12702                try {
12703                    final IActivityManager am = ActivityManager.getService();
12704                    if (am == null) return;
12705                    final int[] resolvedUserIds;
12706                    if (userIds == null) {
12707                        resolvedUserIds = am.getRunningUserIds();
12708                    } else {
12709                        resolvedUserIds = userIds;
12710                    }
12711                    for (int id : resolvedUserIds) {
12712                        final Intent intent = new Intent(action,
12713                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12714                        if (extras != null) {
12715                            intent.putExtras(extras);
12716                        }
12717                        if (targetPkg != null) {
12718                            intent.setPackage(targetPkg);
12719                        }
12720                        // Modify the UID when posting to other users
12721                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12722                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12723                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12724                            intent.putExtra(Intent.EXTRA_UID, uid);
12725                        }
12726                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12727                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12728                        if (DEBUG_BROADCASTS) {
12729                            RuntimeException here = new RuntimeException("here");
12730                            here.fillInStackTrace();
12731                            Slog.d(TAG, "Sending to user " + id + ": "
12732                                    + intent.toShortString(false, true, false, false)
12733                                    + " " + intent.getExtras(), here);
12734                        }
12735                        am.broadcastIntent(null, intent, null, finishedReceiver,
12736                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12737                                null, finishedReceiver != null, false, id);
12738                    }
12739                } catch (RemoteException ex) {
12740                }
12741            }
12742        });
12743    }
12744
12745    /**
12746     * Check if the external storage media is available. This is true if there
12747     * is a mounted external storage medium or if the external storage is
12748     * emulated.
12749     */
12750    private boolean isExternalMediaAvailable() {
12751        return mMediaMounted || Environment.isExternalStorageEmulated();
12752    }
12753
12754    @Override
12755    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12756        // writer
12757        synchronized (mPackages) {
12758            if (!isExternalMediaAvailable()) {
12759                // If the external storage is no longer mounted at this point,
12760                // the caller may not have been able to delete all of this
12761                // packages files and can not delete any more.  Bail.
12762                return null;
12763            }
12764            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12765            if (lastPackage != null) {
12766                pkgs.remove(lastPackage);
12767            }
12768            if (pkgs.size() > 0) {
12769                return pkgs.get(0);
12770            }
12771        }
12772        return null;
12773    }
12774
12775    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12776        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12777                userId, andCode ? 1 : 0, packageName);
12778        if (mSystemReady) {
12779            msg.sendToTarget();
12780        } else {
12781            if (mPostSystemReadyMessages == null) {
12782                mPostSystemReadyMessages = new ArrayList<>();
12783            }
12784            mPostSystemReadyMessages.add(msg);
12785        }
12786    }
12787
12788    void startCleaningPackages() {
12789        // reader
12790        if (!isExternalMediaAvailable()) {
12791            return;
12792        }
12793        synchronized (mPackages) {
12794            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12795                return;
12796            }
12797        }
12798        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12799        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12800        IActivityManager am = ActivityManager.getService();
12801        if (am != null) {
12802            try {
12803                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12804                        UserHandle.USER_SYSTEM);
12805            } catch (RemoteException e) {
12806            }
12807        }
12808    }
12809
12810    @Override
12811    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12812            int installFlags, String installerPackageName, int userId) {
12813        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12814
12815        final int callingUid = Binder.getCallingUid();
12816        enforceCrossUserPermission(callingUid, userId,
12817                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12818
12819        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12820            try {
12821                if (observer != null) {
12822                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12823                }
12824            } catch (RemoteException re) {
12825            }
12826            return;
12827        }
12828
12829        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12830            installFlags |= PackageManager.INSTALL_FROM_ADB;
12831
12832        } else {
12833            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12834            // about installerPackageName.
12835
12836            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12837            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12838        }
12839
12840        UserHandle user;
12841        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12842            user = UserHandle.ALL;
12843        } else {
12844            user = new UserHandle(userId);
12845        }
12846
12847        // Only system components can circumvent runtime permissions when installing.
12848        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12849                && mContext.checkCallingOrSelfPermission(Manifest.permission
12850                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12851            throw new SecurityException("You need the "
12852                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12853                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12854        }
12855
12856        final File originFile = new File(originPath);
12857        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12858
12859        final Message msg = mHandler.obtainMessage(INIT_COPY);
12860        final VerificationInfo verificationInfo = new VerificationInfo(
12861                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12862        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12863                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12864                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12865                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12866        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12867        msg.obj = params;
12868
12869        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12870                System.identityHashCode(msg.obj));
12871        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12872                System.identityHashCode(msg.obj));
12873
12874        mHandler.sendMessage(msg);
12875    }
12876
12877
12878    /**
12879     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12880     * it is acting on behalf on an enterprise or the user).
12881     *
12882     * Note that the ordering of the conditionals in this method is important. The checks we perform
12883     * are as follows, in this order:
12884     *
12885     * 1) If the install is being performed by a system app, we can trust the app to have set the
12886     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12887     *    what it is.
12888     * 2) If the install is being performed by a device or profile owner app, the install reason
12889     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12890     *    set the install reason correctly. If the app targets an older SDK version where install
12891     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12892     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12893     * 3) In all other cases, the install is being performed by a regular app that is neither part
12894     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12895     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12896     *    set to enterprise policy and if so, change it to unknown instead.
12897     */
12898    private int fixUpInstallReason(String installerPackageName, int installerUid,
12899            int installReason) {
12900        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12901                == PERMISSION_GRANTED) {
12902            // If the install is being performed by a system app, we trust that app to have set the
12903            // install reason correctly.
12904            return installReason;
12905        }
12906
12907        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12908            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12909        if (dpm != null) {
12910            ComponentName owner = null;
12911            try {
12912                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12913                if (owner == null) {
12914                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12915                }
12916            } catch (RemoteException e) {
12917            }
12918            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12919                // If the install is being performed by a device or profile owner, the install
12920                // reason should be enterprise policy.
12921                return PackageManager.INSTALL_REASON_POLICY;
12922            }
12923        }
12924
12925        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12926            // If the install is being performed by a regular app (i.e. neither system app nor
12927            // device or profile owner), we have no reason to believe that the app is acting on
12928            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12929            // change it to unknown instead.
12930            return PackageManager.INSTALL_REASON_UNKNOWN;
12931        }
12932
12933        // If the install is being performed by a regular app and the install reason was set to any
12934        // value but enterprise policy, leave the install reason unchanged.
12935        return installReason;
12936    }
12937
12938    void installStage(String packageName, File stagedDir, String stagedCid,
12939            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12940            String installerPackageName, int installerUid, UserHandle user,
12941            Certificate[][] certificates) {
12942        if (DEBUG_EPHEMERAL) {
12943            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12944                Slog.d(TAG, "Ephemeral install of " + packageName);
12945            }
12946        }
12947        final VerificationInfo verificationInfo = new VerificationInfo(
12948                sessionParams.originatingUri, sessionParams.referrerUri,
12949                sessionParams.originatingUid, installerUid);
12950
12951        final OriginInfo origin;
12952        if (stagedDir != null) {
12953            origin = OriginInfo.fromStagedFile(stagedDir);
12954        } else {
12955            origin = OriginInfo.fromStagedContainer(stagedCid);
12956        }
12957
12958        final Message msg = mHandler.obtainMessage(INIT_COPY);
12959        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
12960                sessionParams.installReason);
12961        final InstallParams params = new InstallParams(origin, null, observer,
12962                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12963                verificationInfo, user, sessionParams.abiOverride,
12964                sessionParams.grantedRuntimePermissions, certificates, installReason);
12965        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12966        msg.obj = params;
12967
12968        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12969                System.identityHashCode(msg.obj));
12970        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12971                System.identityHashCode(msg.obj));
12972
12973        mHandler.sendMessage(msg);
12974    }
12975
12976    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12977            int userId) {
12978        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12979        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12980    }
12981
12982    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12983            int appId, int... userIds) {
12984        if (ArrayUtils.isEmpty(userIds)) {
12985            return;
12986        }
12987        Bundle extras = new Bundle(1);
12988        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12989        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12990
12991        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12992                packageName, extras, 0, null, null, userIds);
12993        if (isSystem) {
12994            mHandler.post(() -> {
12995                        for (int userId : userIds) {
12996                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12997                        }
12998                    }
12999            );
13000        }
13001    }
13002
13003    /**
13004     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13005     * automatically without needing an explicit launch.
13006     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13007     */
13008    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13009        // If user is not running, the app didn't miss any broadcast
13010        if (!mUserManagerInternal.isUserRunning(userId)) {
13011            return;
13012        }
13013        final IActivityManager am = ActivityManager.getService();
13014        try {
13015            // Deliver LOCKED_BOOT_COMPLETED first
13016            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13017                    .setPackage(packageName);
13018            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13019            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13020                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13021
13022            // Deliver BOOT_COMPLETED only if user is unlocked
13023            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13024                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13025                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13026                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13027            }
13028        } catch (RemoteException e) {
13029            throw e.rethrowFromSystemServer();
13030        }
13031    }
13032
13033    @Override
13034    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13035            int userId) {
13036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13037        PackageSetting pkgSetting;
13038        final int uid = Binder.getCallingUid();
13039        enforceCrossUserPermission(uid, userId,
13040                true /* requireFullPermission */, true /* checkShell */,
13041                "setApplicationHiddenSetting for user " + userId);
13042
13043        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13044            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13045            return false;
13046        }
13047
13048        long callingId = Binder.clearCallingIdentity();
13049        try {
13050            boolean sendAdded = false;
13051            boolean sendRemoved = false;
13052            // writer
13053            synchronized (mPackages) {
13054                pkgSetting = mSettings.mPackages.get(packageName);
13055                if (pkgSetting == null) {
13056                    return false;
13057                }
13058                // Do not allow "android" is being disabled
13059                if ("android".equals(packageName)) {
13060                    Slog.w(TAG, "Cannot hide package: android");
13061                    return false;
13062                }
13063                // Cannot hide static shared libs as they are considered
13064                // a part of the using app (emulating static linking). Also
13065                // static libs are installed always on internal storage.
13066                PackageParser.Package pkg = mPackages.get(packageName);
13067                if (pkg != null && pkg.staticSharedLibName != null) {
13068                    Slog.w(TAG, "Cannot hide package: " + packageName
13069                            + " providing static shared library: "
13070                            + pkg.staticSharedLibName);
13071                    return false;
13072                }
13073                // Only allow protected packages to hide themselves.
13074                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13075                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13076                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13077                    return false;
13078                }
13079
13080                if (pkgSetting.getHidden(userId) != hidden) {
13081                    pkgSetting.setHidden(hidden, userId);
13082                    mSettings.writePackageRestrictionsLPr(userId);
13083                    if (hidden) {
13084                        sendRemoved = true;
13085                    } else {
13086                        sendAdded = true;
13087                    }
13088                }
13089            }
13090            if (sendAdded) {
13091                sendPackageAddedForUser(packageName, pkgSetting, userId);
13092                return true;
13093            }
13094            if (sendRemoved) {
13095                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13096                        "hiding pkg");
13097                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13098                return true;
13099            }
13100        } finally {
13101            Binder.restoreCallingIdentity(callingId);
13102        }
13103        return false;
13104    }
13105
13106    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13107            int userId) {
13108        final PackageRemovedInfo info = new PackageRemovedInfo();
13109        info.removedPackage = packageName;
13110        info.removedUsers = new int[] {userId};
13111        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13112        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13113    }
13114
13115    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13116        if (pkgList.length > 0) {
13117            Bundle extras = new Bundle(1);
13118            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13119
13120            sendPackageBroadcast(
13121                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13122                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13123                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13124                    new int[] {userId});
13125        }
13126    }
13127
13128    /**
13129     * Returns true if application is not found or there was an error. Otherwise it returns
13130     * the hidden state of the package for the given user.
13131     */
13132    @Override
13133    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13134        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13136                true /* requireFullPermission */, false /* checkShell */,
13137                "getApplicationHidden for user " + userId);
13138        PackageSetting pkgSetting;
13139        long callingId = Binder.clearCallingIdentity();
13140        try {
13141            // writer
13142            synchronized (mPackages) {
13143                pkgSetting = mSettings.mPackages.get(packageName);
13144                if (pkgSetting == null) {
13145                    return true;
13146                }
13147                return pkgSetting.getHidden(userId);
13148            }
13149        } finally {
13150            Binder.restoreCallingIdentity(callingId);
13151        }
13152    }
13153
13154    /**
13155     * @hide
13156     */
13157    @Override
13158    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13159        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13160                null);
13161        PackageSetting pkgSetting;
13162        final int uid = Binder.getCallingUid();
13163        enforceCrossUserPermission(uid, userId,
13164                true /* requireFullPermission */, true /* checkShell */,
13165                "installExistingPackage for user " + userId);
13166        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13167            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13168        }
13169
13170        long callingId = Binder.clearCallingIdentity();
13171        try {
13172            boolean installed = false;
13173
13174            // writer
13175            synchronized (mPackages) {
13176                pkgSetting = mSettings.mPackages.get(packageName);
13177                if (pkgSetting == null) {
13178                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13179                }
13180                if (!pkgSetting.getInstalled(userId)) {
13181                    pkgSetting.setInstalled(true, userId);
13182                    pkgSetting.setHidden(false, userId);
13183                    pkgSetting.setInstallReason(installReason, userId);
13184                    mSettings.writePackageRestrictionsLPr(userId);
13185                    installed = true;
13186                }
13187            }
13188
13189            if (installed) {
13190                if (pkgSetting.pkg != null) {
13191                    synchronized (mInstallLock) {
13192                        // We don't need to freeze for a brand new install
13193                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13194                    }
13195                }
13196                sendPackageAddedForUser(packageName, pkgSetting, userId);
13197            }
13198        } finally {
13199            Binder.restoreCallingIdentity(callingId);
13200        }
13201
13202        return PackageManager.INSTALL_SUCCEEDED;
13203    }
13204
13205    boolean isUserRestricted(int userId, String restrictionKey) {
13206        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13207        if (restrictions.getBoolean(restrictionKey, false)) {
13208            Log.w(TAG, "User is restricted: " + restrictionKey);
13209            return true;
13210        }
13211        return false;
13212    }
13213
13214    @Override
13215    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13216            int userId) {
13217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13218        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13219                true /* requireFullPermission */, true /* checkShell */,
13220                "setPackagesSuspended for user " + userId);
13221
13222        if (ArrayUtils.isEmpty(packageNames)) {
13223            return packageNames;
13224        }
13225
13226        // List of package names for whom the suspended state has changed.
13227        List<String> changedPackages = new ArrayList<>(packageNames.length);
13228        // List of package names for whom the suspended state is not set as requested in this
13229        // method.
13230        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13231        long callingId = Binder.clearCallingIdentity();
13232        try {
13233            for (int i = 0; i < packageNames.length; i++) {
13234                String packageName = packageNames[i];
13235                boolean changed = false;
13236                final int appId;
13237                synchronized (mPackages) {
13238                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13239                    if (pkgSetting == null) {
13240                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13241                                + "\". Skipping suspending/un-suspending.");
13242                        unactionedPackages.add(packageName);
13243                        continue;
13244                    }
13245                    appId = pkgSetting.appId;
13246                    if (pkgSetting.getSuspended(userId) != suspended) {
13247                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13248                            unactionedPackages.add(packageName);
13249                            continue;
13250                        }
13251                        pkgSetting.setSuspended(suspended, userId);
13252                        mSettings.writePackageRestrictionsLPr(userId);
13253                        changed = true;
13254                        changedPackages.add(packageName);
13255                    }
13256                }
13257
13258                if (changed && suspended) {
13259                    killApplication(packageName, UserHandle.getUid(userId, appId),
13260                            "suspending package");
13261                }
13262            }
13263        } finally {
13264            Binder.restoreCallingIdentity(callingId);
13265        }
13266
13267        if (!changedPackages.isEmpty()) {
13268            sendPackagesSuspendedForUser(changedPackages.toArray(
13269                    new String[changedPackages.size()]), userId, suspended);
13270        }
13271
13272        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13273    }
13274
13275    @Override
13276    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13277        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13278                true /* requireFullPermission */, false /* checkShell */,
13279                "isPackageSuspendedForUser for user " + userId);
13280        synchronized (mPackages) {
13281            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13282            if (pkgSetting == null) {
13283                throw new IllegalArgumentException("Unknown target package: " + packageName);
13284            }
13285            return pkgSetting.getSuspended(userId);
13286        }
13287    }
13288
13289    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13290        if (isPackageDeviceAdmin(packageName, userId)) {
13291            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13292                    + "\": has an active device admin");
13293            return false;
13294        }
13295
13296        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13297        if (packageName.equals(activeLauncherPackageName)) {
13298            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13299                    + "\": contains the active launcher");
13300            return false;
13301        }
13302
13303        if (packageName.equals(mRequiredInstallerPackage)) {
13304            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13305                    + "\": required for package installation");
13306            return false;
13307        }
13308
13309        if (packageName.equals(mRequiredUninstallerPackage)) {
13310            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13311                    + "\": required for package uninstallation");
13312            return false;
13313        }
13314
13315        if (packageName.equals(mRequiredVerifierPackage)) {
13316            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13317                    + "\": required for package verification");
13318            return false;
13319        }
13320
13321        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13322            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13323                    + "\": is the default dialer");
13324            return false;
13325        }
13326
13327        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13328            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13329                    + "\": protected package");
13330            return false;
13331        }
13332
13333        // Cannot suspend static shared libs as they are considered
13334        // a part of the using app (emulating static linking). Also
13335        // static libs are installed always on internal storage.
13336        PackageParser.Package pkg = mPackages.get(packageName);
13337        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13338            Slog.w(TAG, "Cannot suspend package: " + packageName
13339                    + " providing static shared library: "
13340                    + pkg.staticSharedLibName);
13341            return false;
13342        }
13343
13344        return true;
13345    }
13346
13347    private String getActiveLauncherPackageName(int userId) {
13348        Intent intent = new Intent(Intent.ACTION_MAIN);
13349        intent.addCategory(Intent.CATEGORY_HOME);
13350        ResolveInfo resolveInfo = resolveIntent(
13351                intent,
13352                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13353                PackageManager.MATCH_DEFAULT_ONLY,
13354                userId);
13355
13356        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13357    }
13358
13359    private String getDefaultDialerPackageName(int userId) {
13360        synchronized (mPackages) {
13361            return mSettings.getDefaultDialerPackageNameLPw(userId);
13362        }
13363    }
13364
13365    @Override
13366    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13367        mContext.enforceCallingOrSelfPermission(
13368                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13369                "Only package verification agents can verify applications");
13370
13371        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13372        final PackageVerificationResponse response = new PackageVerificationResponse(
13373                verificationCode, Binder.getCallingUid());
13374        msg.arg1 = id;
13375        msg.obj = response;
13376        mHandler.sendMessage(msg);
13377    }
13378
13379    @Override
13380    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13381            long millisecondsToDelay) {
13382        mContext.enforceCallingOrSelfPermission(
13383                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13384                "Only package verification agents can extend verification timeouts");
13385
13386        final PackageVerificationState state = mPendingVerification.get(id);
13387        final PackageVerificationResponse response = new PackageVerificationResponse(
13388                verificationCodeAtTimeout, Binder.getCallingUid());
13389
13390        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13391            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13392        }
13393        if (millisecondsToDelay < 0) {
13394            millisecondsToDelay = 0;
13395        }
13396        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13397                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13398            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13399        }
13400
13401        if ((state != null) && !state.timeoutExtended()) {
13402            state.extendTimeout();
13403
13404            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13405            msg.arg1 = id;
13406            msg.obj = response;
13407            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13408        }
13409    }
13410
13411    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13412            int verificationCode, UserHandle user) {
13413        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13414        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13415        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13416        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13417        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13418
13419        mContext.sendBroadcastAsUser(intent, user,
13420                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13421    }
13422
13423    private ComponentName matchComponentForVerifier(String packageName,
13424            List<ResolveInfo> receivers) {
13425        ActivityInfo targetReceiver = null;
13426
13427        final int NR = receivers.size();
13428        for (int i = 0; i < NR; i++) {
13429            final ResolveInfo info = receivers.get(i);
13430            if (info.activityInfo == null) {
13431                continue;
13432            }
13433
13434            if (packageName.equals(info.activityInfo.packageName)) {
13435                targetReceiver = info.activityInfo;
13436                break;
13437            }
13438        }
13439
13440        if (targetReceiver == null) {
13441            return null;
13442        }
13443
13444        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13445    }
13446
13447    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13448            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13449        if (pkgInfo.verifiers.length == 0) {
13450            return null;
13451        }
13452
13453        final int N = pkgInfo.verifiers.length;
13454        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13455        for (int i = 0; i < N; i++) {
13456            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13457
13458            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13459                    receivers);
13460            if (comp == null) {
13461                continue;
13462            }
13463
13464            final int verifierUid = getUidForVerifier(verifierInfo);
13465            if (verifierUid == -1) {
13466                continue;
13467            }
13468
13469            if (DEBUG_VERIFY) {
13470                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13471                        + " with the correct signature");
13472            }
13473            sufficientVerifiers.add(comp);
13474            verificationState.addSufficientVerifier(verifierUid);
13475        }
13476
13477        return sufficientVerifiers;
13478    }
13479
13480    private int getUidForVerifier(VerifierInfo verifierInfo) {
13481        synchronized (mPackages) {
13482            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13483            if (pkg == null) {
13484                return -1;
13485            } else if (pkg.mSignatures.length != 1) {
13486                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13487                        + " has more than one signature; ignoring");
13488                return -1;
13489            }
13490
13491            /*
13492             * If the public key of the package's signature does not match
13493             * our expected public key, then this is a different package and
13494             * we should skip.
13495             */
13496
13497            final byte[] expectedPublicKey;
13498            try {
13499                final Signature verifierSig = pkg.mSignatures[0];
13500                final PublicKey publicKey = verifierSig.getPublicKey();
13501                expectedPublicKey = publicKey.getEncoded();
13502            } catch (CertificateException e) {
13503                return -1;
13504            }
13505
13506            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13507
13508            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13509                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13510                        + " does not have the expected public key; ignoring");
13511                return -1;
13512            }
13513
13514            return pkg.applicationInfo.uid;
13515        }
13516    }
13517
13518    @Override
13519    public void finishPackageInstall(int token, boolean didLaunch) {
13520        enforceSystemOrRoot("Only the system is allowed to finish installs");
13521
13522        if (DEBUG_INSTALL) {
13523            Slog.v(TAG, "BM finishing package install for " + token);
13524        }
13525        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13526
13527        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13528        mHandler.sendMessage(msg);
13529    }
13530
13531    /**
13532     * Get the verification agent timeout.
13533     *
13534     * @return verification timeout in milliseconds
13535     */
13536    private long getVerificationTimeout() {
13537        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13538                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13539                DEFAULT_VERIFICATION_TIMEOUT);
13540    }
13541
13542    /**
13543     * Get the default verification agent response code.
13544     *
13545     * @return default verification response code
13546     */
13547    private int getDefaultVerificationResponse() {
13548        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13549                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13550                DEFAULT_VERIFICATION_RESPONSE);
13551    }
13552
13553    /**
13554     * Check whether or not package verification has been enabled.
13555     *
13556     * @return true if verification should be performed
13557     */
13558    private boolean isVerificationEnabled(int userId, int installFlags) {
13559        if (!DEFAULT_VERIFY_ENABLE) {
13560            return false;
13561        }
13562        // Ephemeral apps don't get the full verification treatment
13563        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13564            if (DEBUG_EPHEMERAL) {
13565                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13566            }
13567            return false;
13568        }
13569
13570        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13571
13572        // Check if installing from ADB
13573        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13574            // Do not run verification in a test harness environment
13575            if (ActivityManager.isRunningInTestHarness()) {
13576                return false;
13577            }
13578            if (ensureVerifyAppsEnabled) {
13579                return true;
13580            }
13581            // Check if the developer does not want package verification for ADB installs
13582            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13583                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13584                return false;
13585            }
13586        }
13587
13588        if (ensureVerifyAppsEnabled) {
13589            return true;
13590        }
13591
13592        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13593                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13594    }
13595
13596    @Override
13597    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13598            throws RemoteException {
13599        mContext.enforceCallingOrSelfPermission(
13600                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13601                "Only intentfilter verification agents can verify applications");
13602
13603        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13604        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13605                Binder.getCallingUid(), verificationCode, failedDomains);
13606        msg.arg1 = id;
13607        msg.obj = response;
13608        mHandler.sendMessage(msg);
13609    }
13610
13611    @Override
13612    public int getIntentVerificationStatus(String packageName, int userId) {
13613        synchronized (mPackages) {
13614            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13615        }
13616    }
13617
13618    @Override
13619    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13620        mContext.enforceCallingOrSelfPermission(
13621                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13622
13623        boolean result = false;
13624        synchronized (mPackages) {
13625            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13626        }
13627        if (result) {
13628            scheduleWritePackageRestrictionsLocked(userId);
13629        }
13630        return result;
13631    }
13632
13633    @Override
13634    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13635            String packageName) {
13636        synchronized (mPackages) {
13637            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13638        }
13639    }
13640
13641    @Override
13642    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13643        if (TextUtils.isEmpty(packageName)) {
13644            return ParceledListSlice.emptyList();
13645        }
13646        synchronized (mPackages) {
13647            PackageParser.Package pkg = mPackages.get(packageName);
13648            if (pkg == null || pkg.activities == null) {
13649                return ParceledListSlice.emptyList();
13650            }
13651            final int count = pkg.activities.size();
13652            ArrayList<IntentFilter> result = new ArrayList<>();
13653            for (int n=0; n<count; n++) {
13654                PackageParser.Activity activity = pkg.activities.get(n);
13655                if (activity.intents != null && activity.intents.size() > 0) {
13656                    result.addAll(activity.intents);
13657                }
13658            }
13659            return new ParceledListSlice<>(result);
13660        }
13661    }
13662
13663    @Override
13664    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13665        mContext.enforceCallingOrSelfPermission(
13666                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13667
13668        synchronized (mPackages) {
13669            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13670            if (packageName != null) {
13671                result |= updateIntentVerificationStatus(packageName,
13672                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13673                        userId);
13674                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13675                        packageName, userId);
13676            }
13677            return result;
13678        }
13679    }
13680
13681    @Override
13682    public String getDefaultBrowserPackageName(int userId) {
13683        synchronized (mPackages) {
13684            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13685        }
13686    }
13687
13688    /**
13689     * Get the "allow unknown sources" setting.
13690     *
13691     * @return the current "allow unknown sources" setting
13692     */
13693    private int getUnknownSourcesSettings() {
13694        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13695                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13696                -1);
13697    }
13698
13699    @Override
13700    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13701        final int uid = Binder.getCallingUid();
13702        // writer
13703        synchronized (mPackages) {
13704            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13705            if (targetPackageSetting == null) {
13706                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13707            }
13708
13709            PackageSetting installerPackageSetting;
13710            if (installerPackageName != null) {
13711                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13712                if (installerPackageSetting == null) {
13713                    throw new IllegalArgumentException("Unknown installer package: "
13714                            + installerPackageName);
13715                }
13716            } else {
13717                installerPackageSetting = null;
13718            }
13719
13720            Signature[] callerSignature;
13721            Object obj = mSettings.getUserIdLPr(uid);
13722            if (obj != null) {
13723                if (obj instanceof SharedUserSetting) {
13724                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13725                } else if (obj instanceof PackageSetting) {
13726                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13727                } else {
13728                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13729                }
13730            } else {
13731                throw new SecurityException("Unknown calling UID: " + uid);
13732            }
13733
13734            // Verify: can't set installerPackageName to a package that is
13735            // not signed with the same cert as the caller.
13736            if (installerPackageSetting != null) {
13737                if (compareSignatures(callerSignature,
13738                        installerPackageSetting.signatures.mSignatures)
13739                        != PackageManager.SIGNATURE_MATCH) {
13740                    throw new SecurityException(
13741                            "Caller does not have same cert as new installer package "
13742                            + installerPackageName);
13743                }
13744            }
13745
13746            // Verify: if target already has an installer package, it must
13747            // be signed with the same cert as the caller.
13748            if (targetPackageSetting.installerPackageName != null) {
13749                PackageSetting setting = mSettings.mPackages.get(
13750                        targetPackageSetting.installerPackageName);
13751                // If the currently set package isn't valid, then it's always
13752                // okay to change it.
13753                if (setting != null) {
13754                    if (compareSignatures(callerSignature,
13755                            setting.signatures.mSignatures)
13756                            != PackageManager.SIGNATURE_MATCH) {
13757                        throw new SecurityException(
13758                                "Caller does not have same cert as old installer package "
13759                                + targetPackageSetting.installerPackageName);
13760                    }
13761                }
13762            }
13763
13764            // Okay!
13765            targetPackageSetting.installerPackageName = installerPackageName;
13766            if (installerPackageName != null) {
13767                mSettings.mInstallerPackages.add(installerPackageName);
13768            }
13769            scheduleWriteSettingsLocked();
13770        }
13771    }
13772
13773    @Override
13774    public void setApplicationCategoryHint(String packageName, int categoryHint,
13775            String callerPackageName) {
13776        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13777                callerPackageName);
13778        synchronized (mPackages) {
13779            PackageSetting ps = mSettings.mPackages.get(packageName);
13780            if (ps == null) {
13781                throw new IllegalArgumentException("Unknown target package " + packageName);
13782            }
13783
13784            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13785                throw new IllegalArgumentException("Calling package " + callerPackageName
13786                        + " is not installer for " + packageName);
13787            }
13788
13789            if (ps.categoryHint != categoryHint) {
13790                ps.categoryHint = categoryHint;
13791                scheduleWriteSettingsLocked();
13792            }
13793        }
13794    }
13795
13796    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13797        // Queue up an async operation since the package installation may take a little while.
13798        mHandler.post(new Runnable() {
13799            public void run() {
13800                mHandler.removeCallbacks(this);
13801                 // Result object to be returned
13802                PackageInstalledInfo res = new PackageInstalledInfo();
13803                res.setReturnCode(currentStatus);
13804                res.uid = -1;
13805                res.pkg = null;
13806                res.removedInfo = null;
13807                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13808                    args.doPreInstall(res.returnCode);
13809                    synchronized (mInstallLock) {
13810                        installPackageTracedLI(args, res);
13811                    }
13812                    args.doPostInstall(res.returnCode, res.uid);
13813                }
13814
13815                // A restore should be performed at this point if (a) the install
13816                // succeeded, (b) the operation is not an update, and (c) the new
13817                // package has not opted out of backup participation.
13818                final boolean update = res.removedInfo != null
13819                        && res.removedInfo.removedPackage != null;
13820                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13821                boolean doRestore = !update
13822                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13823
13824                // Set up the post-install work request bookkeeping.  This will be used
13825                // and cleaned up by the post-install event handling regardless of whether
13826                // there's a restore pass performed.  Token values are >= 1.
13827                int token;
13828                if (mNextInstallToken < 0) mNextInstallToken = 1;
13829                token = mNextInstallToken++;
13830
13831                PostInstallData data = new PostInstallData(args, res);
13832                mRunningInstalls.put(token, data);
13833                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13834
13835                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13836                    // Pass responsibility to the Backup Manager.  It will perform a
13837                    // restore if appropriate, then pass responsibility back to the
13838                    // Package Manager to run the post-install observer callbacks
13839                    // and broadcasts.
13840                    IBackupManager bm = IBackupManager.Stub.asInterface(
13841                            ServiceManager.getService(Context.BACKUP_SERVICE));
13842                    if (bm != null) {
13843                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13844                                + " to BM for possible restore");
13845                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13846                        try {
13847                            // TODO: http://b/22388012
13848                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13849                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13850                            } else {
13851                                doRestore = false;
13852                            }
13853                        } catch (RemoteException e) {
13854                            // can't happen; the backup manager is local
13855                        } catch (Exception e) {
13856                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13857                            doRestore = false;
13858                        }
13859                    } else {
13860                        Slog.e(TAG, "Backup Manager not found!");
13861                        doRestore = false;
13862                    }
13863                }
13864
13865                if (!doRestore) {
13866                    // No restore possible, or the Backup Manager was mysteriously not
13867                    // available -- just fire the post-install work request directly.
13868                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13869
13870                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13871
13872                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13873                    mHandler.sendMessage(msg);
13874                }
13875            }
13876        });
13877    }
13878
13879    /**
13880     * Callback from PackageSettings whenever an app is first transitioned out of the
13881     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13882     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13883     * here whether the app is the target of an ongoing install, and only send the
13884     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13885     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13886     * handling.
13887     */
13888    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13889        // Serialize this with the rest of the install-process message chain.  In the
13890        // restore-at-install case, this Runnable will necessarily run before the
13891        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13892        // are coherent.  In the non-restore case, the app has already completed install
13893        // and been launched through some other means, so it is not in a problematic
13894        // state for observers to see the FIRST_LAUNCH signal.
13895        mHandler.post(new Runnable() {
13896            @Override
13897            public void run() {
13898                for (int i = 0; i < mRunningInstalls.size(); i++) {
13899                    final PostInstallData data = mRunningInstalls.valueAt(i);
13900                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13901                        continue;
13902                    }
13903                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13904                        // right package; but is it for the right user?
13905                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13906                            if (userId == data.res.newUsers[uIndex]) {
13907                                if (DEBUG_BACKUP) {
13908                                    Slog.i(TAG, "Package " + pkgName
13909                                            + " being restored so deferring FIRST_LAUNCH");
13910                                }
13911                                return;
13912                            }
13913                        }
13914                    }
13915                }
13916                // didn't find it, so not being restored
13917                if (DEBUG_BACKUP) {
13918                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13919                }
13920                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13921            }
13922        });
13923    }
13924
13925    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13926        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13927                installerPkg, null, userIds);
13928    }
13929
13930    private abstract class HandlerParams {
13931        private static final int MAX_RETRIES = 4;
13932
13933        /**
13934         * Number of times startCopy() has been attempted and had a non-fatal
13935         * error.
13936         */
13937        private int mRetries = 0;
13938
13939        /** User handle for the user requesting the information or installation. */
13940        private final UserHandle mUser;
13941        String traceMethod;
13942        int traceCookie;
13943
13944        HandlerParams(UserHandle user) {
13945            mUser = user;
13946        }
13947
13948        UserHandle getUser() {
13949            return mUser;
13950        }
13951
13952        HandlerParams setTraceMethod(String traceMethod) {
13953            this.traceMethod = traceMethod;
13954            return this;
13955        }
13956
13957        HandlerParams setTraceCookie(int traceCookie) {
13958            this.traceCookie = traceCookie;
13959            return this;
13960        }
13961
13962        final boolean startCopy() {
13963            boolean res;
13964            try {
13965                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13966
13967                if (++mRetries > MAX_RETRIES) {
13968                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13969                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13970                    handleServiceError();
13971                    return false;
13972                } else {
13973                    handleStartCopy();
13974                    res = true;
13975                }
13976            } catch (RemoteException e) {
13977                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13978                mHandler.sendEmptyMessage(MCS_RECONNECT);
13979                res = false;
13980            }
13981            handleReturnCode();
13982            return res;
13983        }
13984
13985        final void serviceError() {
13986            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13987            handleServiceError();
13988            handleReturnCode();
13989        }
13990
13991        abstract void handleStartCopy() throws RemoteException;
13992        abstract void handleServiceError();
13993        abstract void handleReturnCode();
13994    }
13995
13996    class MeasureParams extends HandlerParams {
13997        private final PackageStats mStats;
13998        private boolean mSuccess;
13999
14000        private final IPackageStatsObserver mObserver;
14001
14002        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14003            super(new UserHandle(stats.userHandle));
14004            mObserver = observer;
14005            mStats = stats;
14006        }
14007
14008        @Override
14009        public String toString() {
14010            return "MeasureParams{"
14011                + Integer.toHexString(System.identityHashCode(this))
14012                + " " + mStats.packageName + "}";
14013        }
14014
14015        @Override
14016        void handleStartCopy() throws RemoteException {
14017            synchronized (mInstallLock) {
14018                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14019            }
14020
14021            if (mSuccess) {
14022                boolean mounted = false;
14023                try {
14024                    final String status = Environment.getExternalStorageState();
14025                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14026                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14027                } catch (Exception e) {
14028                }
14029
14030                if (mounted) {
14031                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14032
14033                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14034                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14035
14036                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14037                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14038
14039                    // Always subtract cache size, since it's a subdirectory
14040                    mStats.externalDataSize -= mStats.externalCacheSize;
14041
14042                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14043                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14044
14045                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14046                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14047                }
14048            }
14049        }
14050
14051        @Override
14052        void handleReturnCode() {
14053            if (mObserver != null) {
14054                try {
14055                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14056                } catch (RemoteException e) {
14057                    Slog.i(TAG, "Observer no longer exists.");
14058                }
14059            }
14060        }
14061
14062        @Override
14063        void handleServiceError() {
14064            Slog.e(TAG, "Could not measure application " + mStats.packageName
14065                            + " external storage");
14066        }
14067    }
14068
14069    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14070            throws RemoteException {
14071        long result = 0;
14072        for (File path : paths) {
14073            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14074        }
14075        return result;
14076    }
14077
14078    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14079        for (File path : paths) {
14080            try {
14081                mcs.clearDirectory(path.getAbsolutePath());
14082            } catch (RemoteException e) {
14083            }
14084        }
14085    }
14086
14087    static class OriginInfo {
14088        /**
14089         * Location where install is coming from, before it has been
14090         * copied/renamed into place. This could be a single monolithic APK
14091         * file, or a cluster directory. This location may be untrusted.
14092         */
14093        final File file;
14094        final String cid;
14095
14096        /**
14097         * Flag indicating that {@link #file} or {@link #cid} has already been
14098         * staged, meaning downstream users don't need to defensively copy the
14099         * contents.
14100         */
14101        final boolean staged;
14102
14103        /**
14104         * Flag indicating that {@link #file} or {@link #cid} is an already
14105         * installed app that is being moved.
14106         */
14107        final boolean existing;
14108
14109        final String resolvedPath;
14110        final File resolvedFile;
14111
14112        static OriginInfo fromNothing() {
14113            return new OriginInfo(null, null, false, false);
14114        }
14115
14116        static OriginInfo fromUntrustedFile(File file) {
14117            return new OriginInfo(file, null, false, false);
14118        }
14119
14120        static OriginInfo fromExistingFile(File file) {
14121            return new OriginInfo(file, null, false, true);
14122        }
14123
14124        static OriginInfo fromStagedFile(File file) {
14125            return new OriginInfo(file, null, true, false);
14126        }
14127
14128        static OriginInfo fromStagedContainer(String cid) {
14129            return new OriginInfo(null, cid, true, false);
14130        }
14131
14132        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14133            this.file = file;
14134            this.cid = cid;
14135            this.staged = staged;
14136            this.existing = existing;
14137
14138            if (cid != null) {
14139                resolvedPath = PackageHelper.getSdDir(cid);
14140                resolvedFile = new File(resolvedPath);
14141            } else if (file != null) {
14142                resolvedPath = file.getAbsolutePath();
14143                resolvedFile = file;
14144            } else {
14145                resolvedPath = null;
14146                resolvedFile = null;
14147            }
14148        }
14149    }
14150
14151    static class MoveInfo {
14152        final int moveId;
14153        final String fromUuid;
14154        final String toUuid;
14155        final String packageName;
14156        final String dataAppName;
14157        final int appId;
14158        final String seinfo;
14159        final int targetSdkVersion;
14160
14161        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14162                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14163            this.moveId = moveId;
14164            this.fromUuid = fromUuid;
14165            this.toUuid = toUuid;
14166            this.packageName = packageName;
14167            this.dataAppName = dataAppName;
14168            this.appId = appId;
14169            this.seinfo = seinfo;
14170            this.targetSdkVersion = targetSdkVersion;
14171        }
14172    }
14173
14174    static class VerificationInfo {
14175        /** A constant used to indicate that a uid value is not present. */
14176        public static final int NO_UID = -1;
14177
14178        /** URI referencing where the package was downloaded from. */
14179        final Uri originatingUri;
14180
14181        /** HTTP referrer URI associated with the originatingURI. */
14182        final Uri referrer;
14183
14184        /** UID of the application that the install request originated from. */
14185        final int originatingUid;
14186
14187        /** UID of application requesting the install */
14188        final int installerUid;
14189
14190        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14191            this.originatingUri = originatingUri;
14192            this.referrer = referrer;
14193            this.originatingUid = originatingUid;
14194            this.installerUid = installerUid;
14195        }
14196    }
14197
14198    class InstallParams extends HandlerParams {
14199        final OriginInfo origin;
14200        final MoveInfo move;
14201        final IPackageInstallObserver2 observer;
14202        int installFlags;
14203        final String installerPackageName;
14204        final String volumeUuid;
14205        private InstallArgs mArgs;
14206        private int mRet;
14207        final String packageAbiOverride;
14208        final String[] grantedRuntimePermissions;
14209        final VerificationInfo verificationInfo;
14210        final Certificate[][] certificates;
14211        final int installReason;
14212
14213        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14214                int installFlags, String installerPackageName, String volumeUuid,
14215                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14216                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14217            super(user);
14218            this.origin = origin;
14219            this.move = move;
14220            this.observer = observer;
14221            this.installFlags = installFlags;
14222            this.installerPackageName = installerPackageName;
14223            this.volumeUuid = volumeUuid;
14224            this.verificationInfo = verificationInfo;
14225            this.packageAbiOverride = packageAbiOverride;
14226            this.grantedRuntimePermissions = grantedPermissions;
14227            this.certificates = certificates;
14228            this.installReason = installReason;
14229        }
14230
14231        @Override
14232        public String toString() {
14233            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14234                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14235        }
14236
14237        private int installLocationPolicy(PackageInfoLite pkgLite) {
14238            String packageName = pkgLite.packageName;
14239            int installLocation = pkgLite.installLocation;
14240            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14241            // reader
14242            synchronized (mPackages) {
14243                // Currently installed package which the new package is attempting to replace or
14244                // null if no such package is installed.
14245                PackageParser.Package installedPkg = mPackages.get(packageName);
14246                // Package which currently owns the data which the new package will own if installed.
14247                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14248                // will be null whereas dataOwnerPkg will contain information about the package
14249                // which was uninstalled while keeping its data.
14250                PackageParser.Package dataOwnerPkg = installedPkg;
14251                if (dataOwnerPkg  == null) {
14252                    PackageSetting ps = mSettings.mPackages.get(packageName);
14253                    if (ps != null) {
14254                        dataOwnerPkg = ps.pkg;
14255                    }
14256                }
14257
14258                if (dataOwnerPkg != null) {
14259                    // If installed, the package will get access to data left on the device by its
14260                    // predecessor. As a security measure, this is permited only if this is not a
14261                    // version downgrade or if the predecessor package is marked as debuggable and
14262                    // a downgrade is explicitly requested.
14263                    //
14264                    // On debuggable platform builds, downgrades are permitted even for
14265                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14266                    // not offer security guarantees and thus it's OK to disable some security
14267                    // mechanisms to make debugging/testing easier on those builds. However, even on
14268                    // debuggable builds downgrades of packages are permitted only if requested via
14269                    // installFlags. This is because we aim to keep the behavior of debuggable
14270                    // platform builds as close as possible to the behavior of non-debuggable
14271                    // platform builds.
14272                    final boolean downgradeRequested =
14273                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14274                    final boolean packageDebuggable =
14275                                (dataOwnerPkg.applicationInfo.flags
14276                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14277                    final boolean downgradePermitted =
14278                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14279                    if (!downgradePermitted) {
14280                        try {
14281                            checkDowngrade(dataOwnerPkg, pkgLite);
14282                        } catch (PackageManagerException e) {
14283                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14284                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14285                        }
14286                    }
14287                }
14288
14289                if (installedPkg != null) {
14290                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14291                        // Check for updated system application.
14292                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14293                            if (onSd) {
14294                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14295                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14296                            }
14297                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14298                        } else {
14299                            if (onSd) {
14300                                // Install flag overrides everything.
14301                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14302                            }
14303                            // If current upgrade specifies particular preference
14304                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14305                                // Application explicitly specified internal.
14306                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14307                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14308                                // App explictly prefers external. Let policy decide
14309                            } else {
14310                                // Prefer previous location
14311                                if (isExternal(installedPkg)) {
14312                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14313                                }
14314                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14315                            }
14316                        }
14317                    } else {
14318                        // Invalid install. Return error code
14319                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14320                    }
14321                }
14322            }
14323            // All the special cases have been taken care of.
14324            // Return result based on recommended install location.
14325            if (onSd) {
14326                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14327            }
14328            return pkgLite.recommendedInstallLocation;
14329        }
14330
14331        /*
14332         * Invoke remote method to get package information and install
14333         * location values. Override install location based on default
14334         * policy if needed and then create install arguments based
14335         * on the install location.
14336         */
14337        public void handleStartCopy() throws RemoteException {
14338            int ret = PackageManager.INSTALL_SUCCEEDED;
14339
14340            // If we're already staged, we've firmly committed to an install location
14341            if (origin.staged) {
14342                if (origin.file != null) {
14343                    installFlags |= PackageManager.INSTALL_INTERNAL;
14344                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14345                } else if (origin.cid != null) {
14346                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14347                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14348                } else {
14349                    throw new IllegalStateException("Invalid stage location");
14350                }
14351            }
14352
14353            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14354            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14355            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14356            PackageInfoLite pkgLite = null;
14357
14358            if (onInt && onSd) {
14359                // Check if both bits are set.
14360                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14361                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14362            } else if (onSd && ephemeral) {
14363                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14364                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14365            } else {
14366                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14367                        packageAbiOverride);
14368
14369                if (DEBUG_EPHEMERAL && ephemeral) {
14370                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14371                }
14372
14373                /*
14374                 * If we have too little free space, try to free cache
14375                 * before giving up.
14376                 */
14377                if (!origin.staged && pkgLite.recommendedInstallLocation
14378                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14379                    // TODO: focus freeing disk space on the target device
14380                    final StorageManager storage = StorageManager.from(mContext);
14381                    final long lowThreshold = storage.getStorageLowBytes(
14382                            Environment.getDataDirectory());
14383
14384                    final long sizeBytes = mContainerService.calculateInstalledSize(
14385                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14386
14387                    try {
14388                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14389                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14390                                installFlags, packageAbiOverride);
14391                    } catch (InstallerException e) {
14392                        Slog.w(TAG, "Failed to free cache", e);
14393                    }
14394
14395                    /*
14396                     * The cache free must have deleted the file we
14397                     * downloaded to install.
14398                     *
14399                     * TODO: fix the "freeCache" call to not delete
14400                     *       the file we care about.
14401                     */
14402                    if (pkgLite.recommendedInstallLocation
14403                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14404                        pkgLite.recommendedInstallLocation
14405                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14406                    }
14407                }
14408            }
14409
14410            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14411                int loc = pkgLite.recommendedInstallLocation;
14412                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14413                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14414                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14415                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14416                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14417                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14418                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14419                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14420                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14421                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14422                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14423                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14424                } else {
14425                    // Override with defaults if needed.
14426                    loc = installLocationPolicy(pkgLite);
14427                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14428                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14429                    } else if (!onSd && !onInt) {
14430                        // Override install location with flags
14431                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14432                            // Set the flag to install on external media.
14433                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14434                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14435                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14436                            if (DEBUG_EPHEMERAL) {
14437                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14438                            }
14439                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14440                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14441                                    |PackageManager.INSTALL_INTERNAL);
14442                        } else {
14443                            // Make sure the flag for installing on external
14444                            // media is unset
14445                            installFlags |= PackageManager.INSTALL_INTERNAL;
14446                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14447                        }
14448                    }
14449                }
14450            }
14451
14452            final InstallArgs args = createInstallArgs(this);
14453            mArgs = args;
14454
14455            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14456                // TODO: http://b/22976637
14457                // Apps installed for "all" users use the device owner to verify the app
14458                UserHandle verifierUser = getUser();
14459                if (verifierUser == UserHandle.ALL) {
14460                    verifierUser = UserHandle.SYSTEM;
14461                }
14462
14463                /*
14464                 * Determine if we have any installed package verifiers. If we
14465                 * do, then we'll defer to them to verify the packages.
14466                 */
14467                final int requiredUid = mRequiredVerifierPackage == null ? -1
14468                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14469                                verifierUser.getIdentifier());
14470                if (!origin.existing && requiredUid != -1
14471                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14472                    final Intent verification = new Intent(
14473                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14474                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14475                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14476                            PACKAGE_MIME_TYPE);
14477                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14478
14479                    // Query all live verifiers based on current user state
14480                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14481                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14482
14483                    if (DEBUG_VERIFY) {
14484                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14485                                + verification.toString() + " with " + pkgLite.verifiers.length
14486                                + " optional verifiers");
14487                    }
14488
14489                    final int verificationId = mPendingVerificationToken++;
14490
14491                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14492
14493                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14494                            installerPackageName);
14495
14496                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14497                            installFlags);
14498
14499                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14500                            pkgLite.packageName);
14501
14502                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14503                            pkgLite.versionCode);
14504
14505                    if (verificationInfo != null) {
14506                        if (verificationInfo.originatingUri != null) {
14507                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14508                                    verificationInfo.originatingUri);
14509                        }
14510                        if (verificationInfo.referrer != null) {
14511                            verification.putExtra(Intent.EXTRA_REFERRER,
14512                                    verificationInfo.referrer);
14513                        }
14514                        if (verificationInfo.originatingUid >= 0) {
14515                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14516                                    verificationInfo.originatingUid);
14517                        }
14518                        if (verificationInfo.installerUid >= 0) {
14519                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14520                                    verificationInfo.installerUid);
14521                        }
14522                    }
14523
14524                    final PackageVerificationState verificationState = new PackageVerificationState(
14525                            requiredUid, args);
14526
14527                    mPendingVerification.append(verificationId, verificationState);
14528
14529                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14530                            receivers, verificationState);
14531
14532                    /*
14533                     * If any sufficient verifiers were listed in the package
14534                     * manifest, attempt to ask them.
14535                     */
14536                    if (sufficientVerifiers != null) {
14537                        final int N = sufficientVerifiers.size();
14538                        if (N == 0) {
14539                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14540                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14541                        } else {
14542                            for (int i = 0; i < N; i++) {
14543                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14544
14545                                final Intent sufficientIntent = new Intent(verification);
14546                                sufficientIntent.setComponent(verifierComponent);
14547                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14548                            }
14549                        }
14550                    }
14551
14552                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14553                            mRequiredVerifierPackage, receivers);
14554                    if (ret == PackageManager.INSTALL_SUCCEEDED
14555                            && mRequiredVerifierPackage != null) {
14556                        Trace.asyncTraceBegin(
14557                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14558                        /*
14559                         * Send the intent to the required verification agent,
14560                         * but only start the verification timeout after the
14561                         * target BroadcastReceivers have run.
14562                         */
14563                        verification.setComponent(requiredVerifierComponent);
14564                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14565                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14566                                new BroadcastReceiver() {
14567                                    @Override
14568                                    public void onReceive(Context context, Intent intent) {
14569                                        final Message msg = mHandler
14570                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14571                                        msg.arg1 = verificationId;
14572                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14573                                    }
14574                                }, null, 0, null, null);
14575
14576                        /*
14577                         * We don't want the copy to proceed until verification
14578                         * succeeds, so null out this field.
14579                         */
14580                        mArgs = null;
14581                    }
14582                } else {
14583                    /*
14584                     * No package verification is enabled, so immediately start
14585                     * the remote call to initiate copy using temporary file.
14586                     */
14587                    ret = args.copyApk(mContainerService, true);
14588                }
14589            }
14590
14591            mRet = ret;
14592        }
14593
14594        @Override
14595        void handleReturnCode() {
14596            // If mArgs is null, then MCS couldn't be reached. When it
14597            // reconnects, it will try again to install. At that point, this
14598            // will succeed.
14599            if (mArgs != null) {
14600                processPendingInstall(mArgs, mRet);
14601            }
14602        }
14603
14604        @Override
14605        void handleServiceError() {
14606            mArgs = createInstallArgs(this);
14607            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14608        }
14609
14610        public boolean isForwardLocked() {
14611            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14612        }
14613    }
14614
14615    /**
14616     * Used during creation of InstallArgs
14617     *
14618     * @param installFlags package installation flags
14619     * @return true if should be installed on external storage
14620     */
14621    private static boolean installOnExternalAsec(int installFlags) {
14622        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14623            return false;
14624        }
14625        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14626            return true;
14627        }
14628        return false;
14629    }
14630
14631    /**
14632     * Used during creation of InstallArgs
14633     *
14634     * @param installFlags package installation flags
14635     * @return true if should be installed as forward locked
14636     */
14637    private static boolean installForwardLocked(int installFlags) {
14638        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14639    }
14640
14641    private InstallArgs createInstallArgs(InstallParams params) {
14642        if (params.move != null) {
14643            return new MoveInstallArgs(params);
14644        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14645            return new AsecInstallArgs(params);
14646        } else {
14647            return new FileInstallArgs(params);
14648        }
14649    }
14650
14651    /**
14652     * Create args that describe an existing installed package. Typically used
14653     * when cleaning up old installs, or used as a move source.
14654     */
14655    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14656            String resourcePath, String[] instructionSets) {
14657        final boolean isInAsec;
14658        if (installOnExternalAsec(installFlags)) {
14659            /* Apps on SD card are always in ASEC containers. */
14660            isInAsec = true;
14661        } else if (installForwardLocked(installFlags)
14662                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14663            /*
14664             * Forward-locked apps are only in ASEC containers if they're the
14665             * new style
14666             */
14667            isInAsec = true;
14668        } else {
14669            isInAsec = false;
14670        }
14671
14672        if (isInAsec) {
14673            return new AsecInstallArgs(codePath, instructionSets,
14674                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14675        } else {
14676            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14677        }
14678    }
14679
14680    static abstract class InstallArgs {
14681        /** @see InstallParams#origin */
14682        final OriginInfo origin;
14683        /** @see InstallParams#move */
14684        final MoveInfo move;
14685
14686        final IPackageInstallObserver2 observer;
14687        // Always refers to PackageManager flags only
14688        final int installFlags;
14689        final String installerPackageName;
14690        final String volumeUuid;
14691        final UserHandle user;
14692        final String abiOverride;
14693        final String[] installGrantPermissions;
14694        /** If non-null, drop an async trace when the install completes */
14695        final String traceMethod;
14696        final int traceCookie;
14697        final Certificate[][] certificates;
14698        final int installReason;
14699
14700        // The list of instruction sets supported by this app. This is currently
14701        // only used during the rmdex() phase to clean up resources. We can get rid of this
14702        // if we move dex files under the common app path.
14703        /* nullable */ String[] instructionSets;
14704
14705        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14706                int installFlags, String installerPackageName, String volumeUuid,
14707                UserHandle user, String[] instructionSets,
14708                String abiOverride, String[] installGrantPermissions,
14709                String traceMethod, int traceCookie, Certificate[][] certificates,
14710                int installReason) {
14711            this.origin = origin;
14712            this.move = move;
14713            this.installFlags = installFlags;
14714            this.observer = observer;
14715            this.installerPackageName = installerPackageName;
14716            this.volumeUuid = volumeUuid;
14717            this.user = user;
14718            this.instructionSets = instructionSets;
14719            this.abiOverride = abiOverride;
14720            this.installGrantPermissions = installGrantPermissions;
14721            this.traceMethod = traceMethod;
14722            this.traceCookie = traceCookie;
14723            this.certificates = certificates;
14724            this.installReason = installReason;
14725        }
14726
14727        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14728        abstract int doPreInstall(int status);
14729
14730        /**
14731         * Rename package into final resting place. All paths on the given
14732         * scanned package should be updated to reflect the rename.
14733         */
14734        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14735        abstract int doPostInstall(int status, int uid);
14736
14737        /** @see PackageSettingBase#codePathString */
14738        abstract String getCodePath();
14739        /** @see PackageSettingBase#resourcePathString */
14740        abstract String getResourcePath();
14741
14742        // Need installer lock especially for dex file removal.
14743        abstract void cleanUpResourcesLI();
14744        abstract boolean doPostDeleteLI(boolean delete);
14745
14746        /**
14747         * Called before the source arguments are copied. This is used mostly
14748         * for MoveParams when it needs to read the source file to put it in the
14749         * destination.
14750         */
14751        int doPreCopy() {
14752            return PackageManager.INSTALL_SUCCEEDED;
14753        }
14754
14755        /**
14756         * Called after the source arguments are copied. This is used mostly for
14757         * MoveParams when it needs to read the source file to put it in the
14758         * destination.
14759         */
14760        int doPostCopy(int uid) {
14761            return PackageManager.INSTALL_SUCCEEDED;
14762        }
14763
14764        protected boolean isFwdLocked() {
14765            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14766        }
14767
14768        protected boolean isExternalAsec() {
14769            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14770        }
14771
14772        protected boolean isEphemeral() {
14773            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14774        }
14775
14776        UserHandle getUser() {
14777            return user;
14778        }
14779    }
14780
14781    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14782        if (!allCodePaths.isEmpty()) {
14783            if (instructionSets == null) {
14784                throw new IllegalStateException("instructionSet == null");
14785            }
14786            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14787            for (String codePath : allCodePaths) {
14788                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14789                    try {
14790                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14791                    } catch (InstallerException ignored) {
14792                    }
14793                }
14794            }
14795        }
14796    }
14797
14798    /**
14799     * Logic to handle installation of non-ASEC applications, including copying
14800     * and renaming logic.
14801     */
14802    class FileInstallArgs extends InstallArgs {
14803        private File codeFile;
14804        private File resourceFile;
14805
14806        // Example topology:
14807        // /data/app/com.example/base.apk
14808        // /data/app/com.example/split_foo.apk
14809        // /data/app/com.example/lib/arm/libfoo.so
14810        // /data/app/com.example/lib/arm64/libfoo.so
14811        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14812
14813        /** New install */
14814        FileInstallArgs(InstallParams params) {
14815            super(params.origin, params.move, params.observer, params.installFlags,
14816                    params.installerPackageName, params.volumeUuid,
14817                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14818                    params.grantedRuntimePermissions,
14819                    params.traceMethod, params.traceCookie, params.certificates,
14820                    params.installReason);
14821            if (isFwdLocked()) {
14822                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14823            }
14824        }
14825
14826        /** Existing install */
14827        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14828            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14829                    null, null, null, 0, null /*certificates*/,
14830                    PackageManager.INSTALL_REASON_UNKNOWN);
14831            this.codeFile = (codePath != null) ? new File(codePath) : null;
14832            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14833        }
14834
14835        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14837            try {
14838                return doCopyApk(imcs, temp);
14839            } finally {
14840                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14841            }
14842        }
14843
14844        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14845            if (origin.staged) {
14846                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14847                codeFile = origin.file;
14848                resourceFile = origin.file;
14849                return PackageManager.INSTALL_SUCCEEDED;
14850            }
14851
14852            try {
14853                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14854                final File tempDir =
14855                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14856                codeFile = tempDir;
14857                resourceFile = tempDir;
14858            } catch (IOException e) {
14859                Slog.w(TAG, "Failed to create copy file: " + e);
14860                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14861            }
14862
14863            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14864                @Override
14865                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14866                    if (!FileUtils.isValidExtFilename(name)) {
14867                        throw new IllegalArgumentException("Invalid filename: " + name);
14868                    }
14869                    try {
14870                        final File file = new File(codeFile, name);
14871                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14872                                O_RDWR | O_CREAT, 0644);
14873                        Os.chmod(file.getAbsolutePath(), 0644);
14874                        return new ParcelFileDescriptor(fd);
14875                    } catch (ErrnoException e) {
14876                        throw new RemoteException("Failed to open: " + e.getMessage());
14877                    }
14878                }
14879            };
14880
14881            int ret = PackageManager.INSTALL_SUCCEEDED;
14882            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14883            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14884                Slog.e(TAG, "Failed to copy package");
14885                return ret;
14886            }
14887
14888            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14889            NativeLibraryHelper.Handle handle = null;
14890            try {
14891                handle = NativeLibraryHelper.Handle.create(codeFile);
14892                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14893                        abiOverride);
14894            } catch (IOException e) {
14895                Slog.e(TAG, "Copying native libraries failed", e);
14896                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14897            } finally {
14898                IoUtils.closeQuietly(handle);
14899            }
14900
14901            return ret;
14902        }
14903
14904        int doPreInstall(int status) {
14905            if (status != PackageManager.INSTALL_SUCCEEDED) {
14906                cleanUp();
14907            }
14908            return status;
14909        }
14910
14911        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14912            if (status != PackageManager.INSTALL_SUCCEEDED) {
14913                cleanUp();
14914                return false;
14915            }
14916
14917            final File targetDir = codeFile.getParentFile();
14918            final File beforeCodeFile = codeFile;
14919            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14920
14921            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14922            try {
14923                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14924            } catch (ErrnoException e) {
14925                Slog.w(TAG, "Failed to rename", e);
14926                return false;
14927            }
14928
14929            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14930                Slog.w(TAG, "Failed to restorecon");
14931                return false;
14932            }
14933
14934            // Reflect the rename internally
14935            codeFile = afterCodeFile;
14936            resourceFile = afterCodeFile;
14937
14938            // Reflect the rename in scanned details
14939            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14940            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14941                    afterCodeFile, pkg.baseCodePath));
14942            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14943                    afterCodeFile, pkg.splitCodePaths));
14944
14945            // Reflect the rename in app info
14946            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14947            pkg.setApplicationInfoCodePath(pkg.codePath);
14948            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14949            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14950            pkg.setApplicationInfoResourcePath(pkg.codePath);
14951            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14952            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14953
14954            return true;
14955        }
14956
14957        int doPostInstall(int status, int uid) {
14958            if (status != PackageManager.INSTALL_SUCCEEDED) {
14959                cleanUp();
14960            }
14961            return status;
14962        }
14963
14964        @Override
14965        String getCodePath() {
14966            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14967        }
14968
14969        @Override
14970        String getResourcePath() {
14971            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14972        }
14973
14974        private boolean cleanUp() {
14975            if (codeFile == null || !codeFile.exists()) {
14976                return false;
14977            }
14978
14979            removeCodePathLI(codeFile);
14980
14981            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14982                resourceFile.delete();
14983            }
14984
14985            return true;
14986        }
14987
14988        void cleanUpResourcesLI() {
14989            // Try enumerating all code paths before deleting
14990            List<String> allCodePaths = Collections.EMPTY_LIST;
14991            if (codeFile != null && codeFile.exists()) {
14992                try {
14993                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14994                    allCodePaths = pkg.getAllCodePaths();
14995                } catch (PackageParserException e) {
14996                    // Ignored; we tried our best
14997                }
14998            }
14999
15000            cleanUp();
15001            removeDexFiles(allCodePaths, instructionSets);
15002        }
15003
15004        boolean doPostDeleteLI(boolean delete) {
15005            // XXX err, shouldn't we respect the delete flag?
15006            cleanUpResourcesLI();
15007            return true;
15008        }
15009    }
15010
15011    private boolean isAsecExternal(String cid) {
15012        final String asecPath = PackageHelper.getSdFilesystem(cid);
15013        return !asecPath.startsWith(mAsecInternalPath);
15014    }
15015
15016    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15017            PackageManagerException {
15018        if (copyRet < 0) {
15019            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15020                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15021                throw new PackageManagerException(copyRet, message);
15022            }
15023        }
15024    }
15025
15026    /**
15027     * Extract the StorageManagerService "container ID" from the full code path of an
15028     * .apk.
15029     */
15030    static String cidFromCodePath(String fullCodePath) {
15031        int eidx = fullCodePath.lastIndexOf("/");
15032        String subStr1 = fullCodePath.substring(0, eidx);
15033        int sidx = subStr1.lastIndexOf("/");
15034        return subStr1.substring(sidx+1, eidx);
15035    }
15036
15037    /**
15038     * Logic to handle installation of ASEC applications, including copying and
15039     * renaming logic.
15040     */
15041    class AsecInstallArgs extends InstallArgs {
15042        static final String RES_FILE_NAME = "pkg.apk";
15043        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15044
15045        String cid;
15046        String packagePath;
15047        String resourcePath;
15048
15049        /** New install */
15050        AsecInstallArgs(InstallParams params) {
15051            super(params.origin, params.move, params.observer, params.installFlags,
15052                    params.installerPackageName, params.volumeUuid,
15053                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15054                    params.grantedRuntimePermissions,
15055                    params.traceMethod, params.traceCookie, params.certificates,
15056                    params.installReason);
15057        }
15058
15059        /** Existing install */
15060        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15061                        boolean isExternal, boolean isForwardLocked) {
15062            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15063                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15064                    instructionSets, null, null, null, 0, null /*certificates*/,
15065                    PackageManager.INSTALL_REASON_UNKNOWN);
15066            // Hackily pretend we're still looking at a full code path
15067            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15068                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15069            }
15070
15071            // Extract cid from fullCodePath
15072            int eidx = fullCodePath.lastIndexOf("/");
15073            String subStr1 = fullCodePath.substring(0, eidx);
15074            int sidx = subStr1.lastIndexOf("/");
15075            cid = subStr1.substring(sidx+1, eidx);
15076            setMountPath(subStr1);
15077        }
15078
15079        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15080            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15081                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15082                    instructionSets, null, null, null, 0, null /*certificates*/,
15083                    PackageManager.INSTALL_REASON_UNKNOWN);
15084            this.cid = cid;
15085            setMountPath(PackageHelper.getSdDir(cid));
15086        }
15087
15088        void createCopyFile() {
15089            cid = mInstallerService.allocateExternalStageCidLegacy();
15090        }
15091
15092        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15093            if (origin.staged && origin.cid != null) {
15094                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15095                cid = origin.cid;
15096                setMountPath(PackageHelper.getSdDir(cid));
15097                return PackageManager.INSTALL_SUCCEEDED;
15098            }
15099
15100            if (temp) {
15101                createCopyFile();
15102            } else {
15103                /*
15104                 * Pre-emptively destroy the container since it's destroyed if
15105                 * copying fails due to it existing anyway.
15106                 */
15107                PackageHelper.destroySdDir(cid);
15108            }
15109
15110            final String newMountPath = imcs.copyPackageToContainer(
15111                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15112                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15113
15114            if (newMountPath != null) {
15115                setMountPath(newMountPath);
15116                return PackageManager.INSTALL_SUCCEEDED;
15117            } else {
15118                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15119            }
15120        }
15121
15122        @Override
15123        String getCodePath() {
15124            return packagePath;
15125        }
15126
15127        @Override
15128        String getResourcePath() {
15129            return resourcePath;
15130        }
15131
15132        int doPreInstall(int status) {
15133            if (status != PackageManager.INSTALL_SUCCEEDED) {
15134                // Destroy container
15135                PackageHelper.destroySdDir(cid);
15136            } else {
15137                boolean mounted = PackageHelper.isContainerMounted(cid);
15138                if (!mounted) {
15139                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15140                            Process.SYSTEM_UID);
15141                    if (newMountPath != null) {
15142                        setMountPath(newMountPath);
15143                    } else {
15144                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15145                    }
15146                }
15147            }
15148            return status;
15149        }
15150
15151        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15152            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15153            String newMountPath = null;
15154            if (PackageHelper.isContainerMounted(cid)) {
15155                // Unmount the container
15156                if (!PackageHelper.unMountSdDir(cid)) {
15157                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15158                    return false;
15159                }
15160            }
15161            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15162                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15163                        " which might be stale. Will try to clean up.");
15164                // Clean up the stale container and proceed to recreate.
15165                if (!PackageHelper.destroySdDir(newCacheId)) {
15166                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15167                    return false;
15168                }
15169                // Successfully cleaned up stale container. Try to rename again.
15170                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15171                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15172                            + " inspite of cleaning it up.");
15173                    return false;
15174                }
15175            }
15176            if (!PackageHelper.isContainerMounted(newCacheId)) {
15177                Slog.w(TAG, "Mounting container " + newCacheId);
15178                newMountPath = PackageHelper.mountSdDir(newCacheId,
15179                        getEncryptKey(), Process.SYSTEM_UID);
15180            } else {
15181                newMountPath = PackageHelper.getSdDir(newCacheId);
15182            }
15183            if (newMountPath == null) {
15184                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15185                return false;
15186            }
15187            Log.i(TAG, "Succesfully renamed " + cid +
15188                    " to " + newCacheId +
15189                    " at new path: " + newMountPath);
15190            cid = newCacheId;
15191
15192            final File beforeCodeFile = new File(packagePath);
15193            setMountPath(newMountPath);
15194            final File afterCodeFile = new File(packagePath);
15195
15196            // Reflect the rename in scanned details
15197            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15198            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15199                    afterCodeFile, pkg.baseCodePath));
15200            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15201                    afterCodeFile, pkg.splitCodePaths));
15202
15203            // Reflect the rename in app info
15204            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15205            pkg.setApplicationInfoCodePath(pkg.codePath);
15206            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15207            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15208            pkg.setApplicationInfoResourcePath(pkg.codePath);
15209            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15210            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15211
15212            return true;
15213        }
15214
15215        private void setMountPath(String mountPath) {
15216            final File mountFile = new File(mountPath);
15217
15218            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15219            if (monolithicFile.exists()) {
15220                packagePath = monolithicFile.getAbsolutePath();
15221                if (isFwdLocked()) {
15222                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15223                } else {
15224                    resourcePath = packagePath;
15225                }
15226            } else {
15227                packagePath = mountFile.getAbsolutePath();
15228                resourcePath = packagePath;
15229            }
15230        }
15231
15232        int doPostInstall(int status, int uid) {
15233            if (status != PackageManager.INSTALL_SUCCEEDED) {
15234                cleanUp();
15235            } else {
15236                final int groupOwner;
15237                final String protectedFile;
15238                if (isFwdLocked()) {
15239                    groupOwner = UserHandle.getSharedAppGid(uid);
15240                    protectedFile = RES_FILE_NAME;
15241                } else {
15242                    groupOwner = -1;
15243                    protectedFile = null;
15244                }
15245
15246                if (uid < Process.FIRST_APPLICATION_UID
15247                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15248                    Slog.e(TAG, "Failed to finalize " + cid);
15249                    PackageHelper.destroySdDir(cid);
15250                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15251                }
15252
15253                boolean mounted = PackageHelper.isContainerMounted(cid);
15254                if (!mounted) {
15255                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15256                }
15257            }
15258            return status;
15259        }
15260
15261        private void cleanUp() {
15262            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15263
15264            // Destroy secure container
15265            PackageHelper.destroySdDir(cid);
15266        }
15267
15268        private List<String> getAllCodePaths() {
15269            final File codeFile = new File(getCodePath());
15270            if (codeFile != null && codeFile.exists()) {
15271                try {
15272                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15273                    return pkg.getAllCodePaths();
15274                } catch (PackageParserException e) {
15275                    // Ignored; we tried our best
15276                }
15277            }
15278            return Collections.EMPTY_LIST;
15279        }
15280
15281        void cleanUpResourcesLI() {
15282            // Enumerate all code paths before deleting
15283            cleanUpResourcesLI(getAllCodePaths());
15284        }
15285
15286        private void cleanUpResourcesLI(List<String> allCodePaths) {
15287            cleanUp();
15288            removeDexFiles(allCodePaths, instructionSets);
15289        }
15290
15291        String getPackageName() {
15292            return getAsecPackageName(cid);
15293        }
15294
15295        boolean doPostDeleteLI(boolean delete) {
15296            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15297            final List<String> allCodePaths = getAllCodePaths();
15298            boolean mounted = PackageHelper.isContainerMounted(cid);
15299            if (mounted) {
15300                // Unmount first
15301                if (PackageHelper.unMountSdDir(cid)) {
15302                    mounted = false;
15303                }
15304            }
15305            if (!mounted && delete) {
15306                cleanUpResourcesLI(allCodePaths);
15307            }
15308            return !mounted;
15309        }
15310
15311        @Override
15312        int doPreCopy() {
15313            if (isFwdLocked()) {
15314                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15315                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15316                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15317                }
15318            }
15319
15320            return PackageManager.INSTALL_SUCCEEDED;
15321        }
15322
15323        @Override
15324        int doPostCopy(int uid) {
15325            if (isFwdLocked()) {
15326                if (uid < Process.FIRST_APPLICATION_UID
15327                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15328                                RES_FILE_NAME)) {
15329                    Slog.e(TAG, "Failed to finalize " + cid);
15330                    PackageHelper.destroySdDir(cid);
15331                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15332                }
15333            }
15334
15335            return PackageManager.INSTALL_SUCCEEDED;
15336        }
15337    }
15338
15339    /**
15340     * Logic to handle movement of existing installed applications.
15341     */
15342    class MoveInstallArgs extends InstallArgs {
15343        private File codeFile;
15344        private File resourceFile;
15345
15346        /** New install */
15347        MoveInstallArgs(InstallParams params) {
15348            super(params.origin, params.move, params.observer, params.installFlags,
15349                    params.installerPackageName, params.volumeUuid,
15350                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15351                    params.grantedRuntimePermissions,
15352                    params.traceMethod, params.traceCookie, params.certificates,
15353                    params.installReason);
15354        }
15355
15356        int copyApk(IMediaContainerService imcs, boolean temp) {
15357            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15358                    + move.fromUuid + " to " + move.toUuid);
15359            synchronized (mInstaller) {
15360                try {
15361                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15362                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15363                } catch (InstallerException e) {
15364                    Slog.w(TAG, "Failed to move app", e);
15365                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15366                }
15367            }
15368
15369            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15370            resourceFile = codeFile;
15371            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15372
15373            return PackageManager.INSTALL_SUCCEEDED;
15374        }
15375
15376        int doPreInstall(int status) {
15377            if (status != PackageManager.INSTALL_SUCCEEDED) {
15378                cleanUp(move.toUuid);
15379            }
15380            return status;
15381        }
15382
15383        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15384            if (status != PackageManager.INSTALL_SUCCEEDED) {
15385                cleanUp(move.toUuid);
15386                return false;
15387            }
15388
15389            // Reflect the move in app info
15390            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15391            pkg.setApplicationInfoCodePath(pkg.codePath);
15392            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15393            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15394            pkg.setApplicationInfoResourcePath(pkg.codePath);
15395            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15396            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15397
15398            return true;
15399        }
15400
15401        int doPostInstall(int status, int uid) {
15402            if (status == PackageManager.INSTALL_SUCCEEDED) {
15403                cleanUp(move.fromUuid);
15404            } else {
15405                cleanUp(move.toUuid);
15406            }
15407            return status;
15408        }
15409
15410        @Override
15411        String getCodePath() {
15412            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15413        }
15414
15415        @Override
15416        String getResourcePath() {
15417            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15418        }
15419
15420        private boolean cleanUp(String volumeUuid) {
15421            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15422                    move.dataAppName);
15423            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15424            final int[] userIds = sUserManager.getUserIds();
15425            synchronized (mInstallLock) {
15426                // Clean up both app data and code
15427                // All package moves are frozen until finished
15428                for (int userId : userIds) {
15429                    try {
15430                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15431                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15432                    } catch (InstallerException e) {
15433                        Slog.w(TAG, String.valueOf(e));
15434                    }
15435                }
15436                removeCodePathLI(codeFile);
15437            }
15438            return true;
15439        }
15440
15441        void cleanUpResourcesLI() {
15442            throw new UnsupportedOperationException();
15443        }
15444
15445        boolean doPostDeleteLI(boolean delete) {
15446            throw new UnsupportedOperationException();
15447        }
15448    }
15449
15450    static String getAsecPackageName(String packageCid) {
15451        int idx = packageCid.lastIndexOf("-");
15452        if (idx == -1) {
15453            return packageCid;
15454        }
15455        return packageCid.substring(0, idx);
15456    }
15457
15458    // Utility method used to create code paths based on package name and available index.
15459    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15460        String idxStr = "";
15461        int idx = 1;
15462        // Fall back to default value of idx=1 if prefix is not
15463        // part of oldCodePath
15464        if (oldCodePath != null) {
15465            String subStr = oldCodePath;
15466            // Drop the suffix right away
15467            if (suffix != null && subStr.endsWith(suffix)) {
15468                subStr = subStr.substring(0, subStr.length() - suffix.length());
15469            }
15470            // If oldCodePath already contains prefix find out the
15471            // ending index to either increment or decrement.
15472            int sidx = subStr.lastIndexOf(prefix);
15473            if (sidx != -1) {
15474                subStr = subStr.substring(sidx + prefix.length());
15475                if (subStr != null) {
15476                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15477                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15478                    }
15479                    try {
15480                        idx = Integer.parseInt(subStr);
15481                        if (idx <= 1) {
15482                            idx++;
15483                        } else {
15484                            idx--;
15485                        }
15486                    } catch(NumberFormatException e) {
15487                    }
15488                }
15489            }
15490        }
15491        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15492        return prefix + idxStr;
15493    }
15494
15495    private File getNextCodePath(File targetDir, String packageName) {
15496        File result;
15497        SecureRandom random = new SecureRandom();
15498        byte[] bytes = new byte[16];
15499        do {
15500            random.nextBytes(bytes);
15501            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15502            result = new File(targetDir, packageName + "-" + suffix);
15503        } while (result.exists());
15504        return result;
15505    }
15506
15507    // Utility method that returns the relative package path with respect
15508    // to the installation directory. Like say for /data/data/com.test-1.apk
15509    // string com.test-1 is returned.
15510    static String deriveCodePathName(String codePath) {
15511        if (codePath == null) {
15512            return null;
15513        }
15514        final File codeFile = new File(codePath);
15515        final String name = codeFile.getName();
15516        if (codeFile.isDirectory()) {
15517            return name;
15518        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15519            final int lastDot = name.lastIndexOf('.');
15520            return name.substring(0, lastDot);
15521        } else {
15522            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15523            return null;
15524        }
15525    }
15526
15527    static class PackageInstalledInfo {
15528        String name;
15529        int uid;
15530        // The set of users that originally had this package installed.
15531        int[] origUsers;
15532        // The set of users that now have this package installed.
15533        int[] newUsers;
15534        PackageParser.Package pkg;
15535        int returnCode;
15536        String returnMsg;
15537        PackageRemovedInfo removedInfo;
15538        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15539
15540        public void setError(int code, String msg) {
15541            setReturnCode(code);
15542            setReturnMessage(msg);
15543            Slog.w(TAG, msg);
15544        }
15545
15546        public void setError(String msg, PackageParserException e) {
15547            setReturnCode(e.error);
15548            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15549            Slog.w(TAG, msg, e);
15550        }
15551
15552        public void setError(String msg, PackageManagerException e) {
15553            returnCode = e.error;
15554            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15555            Slog.w(TAG, msg, e);
15556        }
15557
15558        public void setReturnCode(int returnCode) {
15559            this.returnCode = returnCode;
15560            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15561            for (int i = 0; i < childCount; i++) {
15562                addedChildPackages.valueAt(i).returnCode = returnCode;
15563            }
15564        }
15565
15566        private void setReturnMessage(String returnMsg) {
15567            this.returnMsg = returnMsg;
15568            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15569            for (int i = 0; i < childCount; i++) {
15570                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15571            }
15572        }
15573
15574        // In some error cases we want to convey more info back to the observer
15575        String origPackage;
15576        String origPermission;
15577    }
15578
15579    /*
15580     * Install a non-existing package.
15581     */
15582    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15583            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15584            PackageInstalledInfo res, int installReason) {
15585        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15586
15587        // Remember this for later, in case we need to rollback this install
15588        String pkgName = pkg.packageName;
15589
15590        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15591
15592        synchronized(mPackages) {
15593            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15594            if (renamedPackage != null) {
15595                // A package with the same name is already installed, though
15596                // it has been renamed to an older name.  The package we
15597                // are trying to install should be installed as an update to
15598                // the existing one, but that has not been requested, so bail.
15599                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15600                        + " without first uninstalling package running as "
15601                        + renamedPackage);
15602                return;
15603            }
15604            if (mPackages.containsKey(pkgName)) {
15605                // Don't allow installation over an existing package with the same name.
15606                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15607                        + " without first uninstalling.");
15608                return;
15609            }
15610        }
15611
15612        try {
15613            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15614                    System.currentTimeMillis(), user);
15615
15616            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15617
15618            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15619                prepareAppDataAfterInstallLIF(newPackage);
15620
15621            } else {
15622                // Remove package from internal structures, but keep around any
15623                // data that might have already existed
15624                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15625                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15626            }
15627        } catch (PackageManagerException e) {
15628            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15629        }
15630
15631        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15632    }
15633
15634    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15635        // Can't rotate keys during boot or if sharedUser.
15636        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15637                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15638            return false;
15639        }
15640        // app is using upgradeKeySets; make sure all are valid
15641        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15642        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15643        for (int i = 0; i < upgradeKeySets.length; i++) {
15644            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15645                Slog.wtf(TAG, "Package "
15646                         + (oldPs.name != null ? oldPs.name : "<null>")
15647                         + " contains upgrade-key-set reference to unknown key-set: "
15648                         + upgradeKeySets[i]
15649                         + " reverting to signatures check.");
15650                return false;
15651            }
15652        }
15653        return true;
15654    }
15655
15656    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15657        // Upgrade keysets are being used.  Determine if new package has a superset of the
15658        // required keys.
15659        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15660        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15661        for (int i = 0; i < upgradeKeySets.length; i++) {
15662            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15663            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15664                return true;
15665            }
15666        }
15667        return false;
15668    }
15669
15670    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15671        try (DigestInputStream digestStream =
15672                new DigestInputStream(new FileInputStream(file), digest)) {
15673            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15674        }
15675    }
15676
15677    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15678            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15679            int installReason) {
15680        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15681
15682        final PackageParser.Package oldPackage;
15683        final String pkgName = pkg.packageName;
15684        final int[] allUsers;
15685        final int[] installedUsers;
15686
15687        synchronized(mPackages) {
15688            oldPackage = mPackages.get(pkgName);
15689            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15690
15691            // don't allow upgrade to target a release SDK from a pre-release SDK
15692            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15693                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15694            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15695                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15696            if (oldTargetsPreRelease
15697                    && !newTargetsPreRelease
15698                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15699                Slog.w(TAG, "Can't install package targeting released sdk");
15700                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15701                return;
15702            }
15703
15704            // don't allow an upgrade from full to ephemeral
15705            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
15706            if (isEphemeral && !oldIsEphemeral) {
15707                // can't downgrade from full to ephemeral
15708                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15709                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15710                return;
15711            }
15712
15713            // verify signatures are valid
15714            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15715            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15716                if (!checkUpgradeKeySetLP(ps, pkg)) {
15717                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15718                            "New package not signed by keys specified by upgrade-keysets: "
15719                                    + pkgName);
15720                    return;
15721                }
15722            } else {
15723                // default to original signature matching
15724                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15725                        != PackageManager.SIGNATURE_MATCH) {
15726                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15727                            "New package has a different signature: " + pkgName);
15728                    return;
15729                }
15730            }
15731
15732            // don't allow a system upgrade unless the upgrade hash matches
15733            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15734                byte[] digestBytes = null;
15735                try {
15736                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15737                    updateDigest(digest, new File(pkg.baseCodePath));
15738                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15739                        for (String path : pkg.splitCodePaths) {
15740                            updateDigest(digest, new File(path));
15741                        }
15742                    }
15743                    digestBytes = digest.digest();
15744                } catch (NoSuchAlgorithmException | IOException e) {
15745                    res.setError(INSTALL_FAILED_INVALID_APK,
15746                            "Could not compute hash: " + pkgName);
15747                    return;
15748                }
15749                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15750                    res.setError(INSTALL_FAILED_INVALID_APK,
15751                            "New package fails restrict-update check: " + pkgName);
15752                    return;
15753                }
15754                // retain upgrade restriction
15755                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15756            }
15757
15758            // Check for shared user id changes
15759            String invalidPackageName =
15760                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15761            if (invalidPackageName != null) {
15762                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15763                        "Package " + invalidPackageName + " tried to change user "
15764                                + oldPackage.mSharedUserId);
15765                return;
15766            }
15767
15768            // In case of rollback, remember per-user/profile install state
15769            allUsers = sUserManager.getUserIds();
15770            installedUsers = ps.queryInstalledUsers(allUsers, true);
15771        }
15772
15773        // Update what is removed
15774        res.removedInfo = new PackageRemovedInfo();
15775        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15776        res.removedInfo.removedPackage = oldPackage.packageName;
15777        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15778        res.removedInfo.isUpdate = true;
15779        res.removedInfo.origUsers = installedUsers;
15780        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15781        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15782        for (int i = 0; i < installedUsers.length; i++) {
15783            final int userId = installedUsers[i];
15784            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15785        }
15786
15787        final int childCount = (oldPackage.childPackages != null)
15788                ? oldPackage.childPackages.size() : 0;
15789        for (int i = 0; i < childCount; i++) {
15790            boolean childPackageUpdated = false;
15791            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15792            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15793            if (res.addedChildPackages != null) {
15794                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15795                if (childRes != null) {
15796                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15797                    childRes.removedInfo.removedPackage = childPkg.packageName;
15798                    childRes.removedInfo.isUpdate = true;
15799                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15800                    childPackageUpdated = true;
15801                }
15802            }
15803            if (!childPackageUpdated) {
15804                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15805                childRemovedRes.removedPackage = childPkg.packageName;
15806                childRemovedRes.isUpdate = false;
15807                childRemovedRes.dataRemoved = true;
15808                synchronized (mPackages) {
15809                    if (childPs != null) {
15810                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15811                    }
15812                }
15813                if (res.removedInfo.removedChildPackages == null) {
15814                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15815                }
15816                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15817            }
15818        }
15819
15820        boolean sysPkg = (isSystemApp(oldPackage));
15821        if (sysPkg) {
15822            // Set the system/privileged flags as needed
15823            final boolean privileged =
15824                    (oldPackage.applicationInfo.privateFlags
15825                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15826            final int systemPolicyFlags = policyFlags
15827                    | PackageParser.PARSE_IS_SYSTEM
15828                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15829
15830            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15831                    user, allUsers, installerPackageName, res, installReason);
15832        } else {
15833            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15834                    user, allUsers, installerPackageName, res, installReason);
15835        }
15836    }
15837
15838    public List<String> getPreviousCodePaths(String packageName) {
15839        final PackageSetting ps = mSettings.mPackages.get(packageName);
15840        final List<String> result = new ArrayList<String>();
15841        if (ps != null && ps.oldCodePaths != null) {
15842            result.addAll(ps.oldCodePaths);
15843        }
15844        return result;
15845    }
15846
15847    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15848            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15849            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15850            int installReason) {
15851        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15852                + deletedPackage);
15853
15854        String pkgName = deletedPackage.packageName;
15855        boolean deletedPkg = true;
15856        boolean addedPkg = false;
15857        boolean updatedSettings = false;
15858        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15859        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15860                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15861
15862        final long origUpdateTime = (pkg.mExtras != null)
15863                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15864
15865        // First delete the existing package while retaining the data directory
15866        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15867                res.removedInfo, true, pkg)) {
15868            // If the existing package wasn't successfully deleted
15869            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15870            deletedPkg = false;
15871        } else {
15872            // Successfully deleted the old package; proceed with replace.
15873
15874            // If deleted package lived in a container, give users a chance to
15875            // relinquish resources before killing.
15876            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15877                if (DEBUG_INSTALL) {
15878                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15879                }
15880                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15881                final ArrayList<String> pkgList = new ArrayList<String>(1);
15882                pkgList.add(deletedPackage.applicationInfo.packageName);
15883                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15884            }
15885
15886            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15887                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15888            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15889
15890            try {
15891                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15892                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15893                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15894                        installReason);
15895
15896                // Update the in-memory copy of the previous code paths.
15897                PackageSetting ps = mSettings.mPackages.get(pkgName);
15898                if (!killApp) {
15899                    if (ps.oldCodePaths == null) {
15900                        ps.oldCodePaths = new ArraySet<>();
15901                    }
15902                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15903                    if (deletedPackage.splitCodePaths != null) {
15904                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15905                    }
15906                } else {
15907                    ps.oldCodePaths = null;
15908                }
15909                if (ps.childPackageNames != null) {
15910                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15911                        final String childPkgName = ps.childPackageNames.get(i);
15912                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15913                        childPs.oldCodePaths = ps.oldCodePaths;
15914                    }
15915                }
15916                prepareAppDataAfterInstallLIF(newPackage);
15917                addedPkg = true;
15918            } catch (PackageManagerException e) {
15919                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15920            }
15921        }
15922
15923        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15924            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15925
15926            // Revert all internal state mutations and added folders for the failed install
15927            if (addedPkg) {
15928                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15929                        res.removedInfo, true, null);
15930            }
15931
15932            // Restore the old package
15933            if (deletedPkg) {
15934                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15935                File restoreFile = new File(deletedPackage.codePath);
15936                // Parse old package
15937                boolean oldExternal = isExternal(deletedPackage);
15938                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15939                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15940                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15941                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15942                try {
15943                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15944                            null);
15945                } catch (PackageManagerException e) {
15946                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15947                            + e.getMessage());
15948                    return;
15949                }
15950
15951                synchronized (mPackages) {
15952                    // Ensure the installer package name up to date
15953                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15954
15955                    // Update permissions for restored package
15956                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15957
15958                    mSettings.writeLPr();
15959                }
15960
15961                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15962            }
15963        } else {
15964            synchronized (mPackages) {
15965                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15966                if (ps != null) {
15967                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15968                    if (res.removedInfo.removedChildPackages != null) {
15969                        final int childCount = res.removedInfo.removedChildPackages.size();
15970                        // Iterate in reverse as we may modify the collection
15971                        for (int i = childCount - 1; i >= 0; i--) {
15972                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15973                            if (res.addedChildPackages.containsKey(childPackageName)) {
15974                                res.removedInfo.removedChildPackages.removeAt(i);
15975                            } else {
15976                                PackageRemovedInfo childInfo = res.removedInfo
15977                                        .removedChildPackages.valueAt(i);
15978                                childInfo.removedForAllUsers = mPackages.get(
15979                                        childInfo.removedPackage) == null;
15980                            }
15981                        }
15982                    }
15983                }
15984            }
15985        }
15986    }
15987
15988    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15989            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15990            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15991            int installReason) {
15992        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15993                + ", old=" + deletedPackage);
15994
15995        final boolean disabledSystem;
15996
15997        // Remove existing system package
15998        removePackageLI(deletedPackage, true);
15999
16000        synchronized (mPackages) {
16001            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16002        }
16003        if (!disabledSystem) {
16004            // We didn't need to disable the .apk as a current system package,
16005            // which means we are replacing another update that is already
16006            // installed.  We need to make sure to delete the older one's .apk.
16007            res.removedInfo.args = createInstallArgsForExisting(0,
16008                    deletedPackage.applicationInfo.getCodePath(),
16009                    deletedPackage.applicationInfo.getResourcePath(),
16010                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16011        } else {
16012            res.removedInfo.args = null;
16013        }
16014
16015        // Successfully disabled the old package. Now proceed with re-installation
16016        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16017                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16018        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16019
16020        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16021        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16022                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16023
16024        PackageParser.Package newPackage = null;
16025        try {
16026            // Add the package to the internal data structures
16027            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16028
16029            // Set the update and install times
16030            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16031            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16032                    System.currentTimeMillis());
16033
16034            // Update the package dynamic state if succeeded
16035            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16036                // Now that the install succeeded make sure we remove data
16037                // directories for any child package the update removed.
16038                final int deletedChildCount = (deletedPackage.childPackages != null)
16039                        ? deletedPackage.childPackages.size() : 0;
16040                final int newChildCount = (newPackage.childPackages != null)
16041                        ? newPackage.childPackages.size() : 0;
16042                for (int i = 0; i < deletedChildCount; i++) {
16043                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16044                    boolean childPackageDeleted = true;
16045                    for (int j = 0; j < newChildCount; j++) {
16046                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16047                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16048                            childPackageDeleted = false;
16049                            break;
16050                        }
16051                    }
16052                    if (childPackageDeleted) {
16053                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16054                                deletedChildPkg.packageName);
16055                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16056                            PackageRemovedInfo removedChildRes = res.removedInfo
16057                                    .removedChildPackages.get(deletedChildPkg.packageName);
16058                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16059                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16060                        }
16061                    }
16062                }
16063
16064                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16065                        installReason);
16066                prepareAppDataAfterInstallLIF(newPackage);
16067            }
16068        } catch (PackageManagerException e) {
16069            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16070            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16071        }
16072
16073        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16074            // Re installation failed. Restore old information
16075            // Remove new pkg information
16076            if (newPackage != null) {
16077                removeInstalledPackageLI(newPackage, true);
16078            }
16079            // Add back the old system package
16080            try {
16081                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16082            } catch (PackageManagerException e) {
16083                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16084            }
16085
16086            synchronized (mPackages) {
16087                if (disabledSystem) {
16088                    enableSystemPackageLPw(deletedPackage);
16089                }
16090
16091                // Ensure the installer package name up to date
16092                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16093
16094                // Update permissions for restored package
16095                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16096
16097                mSettings.writeLPr();
16098            }
16099
16100            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16101                    + " after failed upgrade");
16102        }
16103    }
16104
16105    /**
16106     * Checks whether the parent or any of the child packages have a change shared
16107     * user. For a package to be a valid update the shred users of the parent and
16108     * the children should match. We may later support changing child shared users.
16109     * @param oldPkg The updated package.
16110     * @param newPkg The update package.
16111     * @return The shared user that change between the versions.
16112     */
16113    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16114            PackageParser.Package newPkg) {
16115        // Check parent shared user
16116        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16117            return newPkg.packageName;
16118        }
16119        // Check child shared users
16120        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16121        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16122        for (int i = 0; i < newChildCount; i++) {
16123            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16124            // If this child was present, did it have the same shared user?
16125            for (int j = 0; j < oldChildCount; j++) {
16126                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16127                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16128                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16129                    return newChildPkg.packageName;
16130                }
16131            }
16132        }
16133        return null;
16134    }
16135
16136    private void removeNativeBinariesLI(PackageSetting ps) {
16137        // Remove the lib path for the parent package
16138        if (ps != null) {
16139            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16140            // Remove the lib path for the child packages
16141            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16142            for (int i = 0; i < childCount; i++) {
16143                PackageSetting childPs = null;
16144                synchronized (mPackages) {
16145                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16146                }
16147                if (childPs != null) {
16148                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16149                            .legacyNativeLibraryPathString);
16150                }
16151            }
16152        }
16153    }
16154
16155    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16156        // Enable the parent package
16157        mSettings.enableSystemPackageLPw(pkg.packageName);
16158        // Enable the child packages
16159        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16160        for (int i = 0; i < childCount; i++) {
16161            PackageParser.Package childPkg = pkg.childPackages.get(i);
16162            mSettings.enableSystemPackageLPw(childPkg.packageName);
16163        }
16164    }
16165
16166    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16167            PackageParser.Package newPkg) {
16168        // Disable the parent package (parent always replaced)
16169        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16170        // Disable the child packages
16171        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16172        for (int i = 0; i < childCount; i++) {
16173            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16174            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16175            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16176        }
16177        return disabled;
16178    }
16179
16180    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16181            String installerPackageName) {
16182        // Enable the parent package
16183        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16184        // Enable the child packages
16185        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16186        for (int i = 0; i < childCount; i++) {
16187            PackageParser.Package childPkg = pkg.childPackages.get(i);
16188            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16189        }
16190    }
16191
16192    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16193        // Collect all used permissions in the UID
16194        ArraySet<String> usedPermissions = new ArraySet<>();
16195        final int packageCount = su.packages.size();
16196        for (int i = 0; i < packageCount; i++) {
16197            PackageSetting ps = su.packages.valueAt(i);
16198            if (ps.pkg == null) {
16199                continue;
16200            }
16201            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16202            for (int j = 0; j < requestedPermCount; j++) {
16203                String permission = ps.pkg.requestedPermissions.get(j);
16204                BasePermission bp = mSettings.mPermissions.get(permission);
16205                if (bp != null) {
16206                    usedPermissions.add(permission);
16207                }
16208            }
16209        }
16210
16211        PermissionsState permissionsState = su.getPermissionsState();
16212        // Prune install permissions
16213        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16214        final int installPermCount = installPermStates.size();
16215        for (int i = installPermCount - 1; i >= 0;  i--) {
16216            PermissionState permissionState = installPermStates.get(i);
16217            if (!usedPermissions.contains(permissionState.getName())) {
16218                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16219                if (bp != null) {
16220                    permissionsState.revokeInstallPermission(bp);
16221                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16222                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16223                }
16224            }
16225        }
16226
16227        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16228
16229        // Prune runtime permissions
16230        for (int userId : allUserIds) {
16231            List<PermissionState> runtimePermStates = permissionsState
16232                    .getRuntimePermissionStates(userId);
16233            final int runtimePermCount = runtimePermStates.size();
16234            for (int i = runtimePermCount - 1; i >= 0; i--) {
16235                PermissionState permissionState = runtimePermStates.get(i);
16236                if (!usedPermissions.contains(permissionState.getName())) {
16237                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16238                    if (bp != null) {
16239                        permissionsState.revokeRuntimePermission(bp, userId);
16240                        permissionsState.updatePermissionFlags(bp, userId,
16241                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16242                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16243                                runtimePermissionChangedUserIds, userId);
16244                    }
16245                }
16246            }
16247        }
16248
16249        return runtimePermissionChangedUserIds;
16250    }
16251
16252    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16253            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16254        // Update the parent package setting
16255        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16256                res, user, installReason);
16257        // Update the child packages setting
16258        final int childCount = (newPackage.childPackages != null)
16259                ? newPackage.childPackages.size() : 0;
16260        for (int i = 0; i < childCount; i++) {
16261            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16262            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16263            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16264                    childRes.origUsers, childRes, user, installReason);
16265        }
16266    }
16267
16268    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16269            String installerPackageName, int[] allUsers, int[] installedForUsers,
16270            PackageInstalledInfo res, UserHandle user, int installReason) {
16271        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16272
16273        String pkgName = newPackage.packageName;
16274        synchronized (mPackages) {
16275            //write settings. the installStatus will be incomplete at this stage.
16276            //note that the new package setting would have already been
16277            //added to mPackages. It hasn't been persisted yet.
16278            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16279            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16280            mSettings.writeLPr();
16281            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16282        }
16283
16284        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16285        synchronized (mPackages) {
16286            updatePermissionsLPw(newPackage.packageName, newPackage,
16287                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16288                            ? UPDATE_PERMISSIONS_ALL : 0));
16289            // For system-bundled packages, we assume that installing an upgraded version
16290            // of the package implies that the user actually wants to run that new code,
16291            // so we enable the package.
16292            PackageSetting ps = mSettings.mPackages.get(pkgName);
16293            final int userId = user.getIdentifier();
16294            if (ps != null) {
16295                if (isSystemApp(newPackage)) {
16296                    if (DEBUG_INSTALL) {
16297                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16298                    }
16299                    // Enable system package for requested users
16300                    if (res.origUsers != null) {
16301                        for (int origUserId : res.origUsers) {
16302                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16303                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16304                                        origUserId, installerPackageName);
16305                            }
16306                        }
16307                    }
16308                    // Also convey the prior install/uninstall state
16309                    if (allUsers != null && installedForUsers != null) {
16310                        for (int currentUserId : allUsers) {
16311                            final boolean installed = ArrayUtils.contains(
16312                                    installedForUsers, currentUserId);
16313                            if (DEBUG_INSTALL) {
16314                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16315                            }
16316                            ps.setInstalled(installed, currentUserId);
16317                        }
16318                        // these install state changes will be persisted in the
16319                        // upcoming call to mSettings.writeLPr().
16320                    }
16321                }
16322                // It's implied that when a user requests installation, they want the app to be
16323                // installed and enabled.
16324                if (userId != UserHandle.USER_ALL) {
16325                    ps.setInstalled(true, userId);
16326                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16327                }
16328
16329                // When replacing an existing package, preserve the original install reason for all
16330                // users that had the package installed before.
16331                final Set<Integer> previousUserIds = new ArraySet<>();
16332                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16333                    final int installReasonCount = res.removedInfo.installReasons.size();
16334                    for (int i = 0; i < installReasonCount; i++) {
16335                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16336                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16337                        ps.setInstallReason(previousInstallReason, previousUserId);
16338                        previousUserIds.add(previousUserId);
16339                    }
16340                }
16341
16342                // Set install reason for users that are having the package newly installed.
16343                if (userId == UserHandle.USER_ALL) {
16344                    for (int currentUserId : sUserManager.getUserIds()) {
16345                        if (!previousUserIds.contains(currentUserId)) {
16346                            ps.setInstallReason(installReason, currentUserId);
16347                        }
16348                    }
16349                } else if (!previousUserIds.contains(userId)) {
16350                    ps.setInstallReason(installReason, userId);
16351                }
16352            }
16353            res.name = pkgName;
16354            res.uid = newPackage.applicationInfo.uid;
16355            res.pkg = newPackage;
16356            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16357            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16358            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16359            //to update install status
16360            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16361            mSettings.writeLPr();
16362            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16363        }
16364
16365        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16366    }
16367
16368    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16369        try {
16370            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16371            installPackageLI(args, res);
16372        } finally {
16373            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16374        }
16375    }
16376
16377    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16378        final int installFlags = args.installFlags;
16379        final String installerPackageName = args.installerPackageName;
16380        final String volumeUuid = args.volumeUuid;
16381        final File tmpPackageFile = new File(args.getCodePath());
16382        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16383        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16384                || (args.volumeUuid != null));
16385        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16386        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16387        boolean replace = false;
16388        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16389        if (args.move != null) {
16390            // moving a complete application; perform an initial scan on the new install location
16391            scanFlags |= SCAN_INITIAL;
16392        }
16393        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16394            scanFlags |= SCAN_DONT_KILL_APP;
16395        }
16396
16397        // Result object to be returned
16398        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16399
16400        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16401
16402        // Sanity check
16403        if (ephemeral && (forwardLocked || onExternal)) {
16404            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16405                    + " external=" + onExternal);
16406            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16407            return;
16408        }
16409
16410        // Retrieve PackageSettings and parse package
16411        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16412                | PackageParser.PARSE_ENFORCE_CODE
16413                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16414                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16415                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16416                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16417        PackageParser pp = new PackageParser();
16418        pp.setSeparateProcesses(mSeparateProcesses);
16419        pp.setDisplayMetrics(mMetrics);
16420
16421        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16422        final PackageParser.Package pkg;
16423        try {
16424            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16425        } catch (PackageParserException e) {
16426            res.setError("Failed parse during installPackageLI", e);
16427            return;
16428        } finally {
16429            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16430        }
16431
16432        // Ephemeral apps must have target SDK >= O.
16433        // TODO: Update conditional and error message when O gets locked down
16434        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16435            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16436                    "Ephemeral apps must have target SDK version of at least O");
16437            return;
16438        }
16439
16440        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16441            // Static shared libraries have synthetic package names
16442            renameStaticSharedLibraryPackage(pkg);
16443
16444            // No static shared libs on external storage
16445            if (onExternal) {
16446                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16447                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16448                        "Packages declaring static-shared libs cannot be updated");
16449                return;
16450            }
16451        }
16452
16453        // If we are installing a clustered package add results for the children
16454        if (pkg.childPackages != null) {
16455            synchronized (mPackages) {
16456                final int childCount = pkg.childPackages.size();
16457                for (int i = 0; i < childCount; i++) {
16458                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16459                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16460                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16461                    childRes.pkg = childPkg;
16462                    childRes.name = childPkg.packageName;
16463                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16464                    if (childPs != null) {
16465                        childRes.origUsers = childPs.queryInstalledUsers(
16466                                sUserManager.getUserIds(), true);
16467                    }
16468                    if ((mPackages.containsKey(childPkg.packageName))) {
16469                        childRes.removedInfo = new PackageRemovedInfo();
16470                        childRes.removedInfo.removedPackage = childPkg.packageName;
16471                    }
16472                    if (res.addedChildPackages == null) {
16473                        res.addedChildPackages = new ArrayMap<>();
16474                    }
16475                    res.addedChildPackages.put(childPkg.packageName, childRes);
16476                }
16477            }
16478        }
16479
16480        // If package doesn't declare API override, mark that we have an install
16481        // time CPU ABI override.
16482        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16483            pkg.cpuAbiOverride = args.abiOverride;
16484        }
16485
16486        String pkgName = res.name = pkg.packageName;
16487        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16488            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16489                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16490                return;
16491            }
16492        }
16493
16494        try {
16495            // either use what we've been given or parse directly from the APK
16496            if (args.certificates != null) {
16497                try {
16498                    PackageParser.populateCertificates(pkg, args.certificates);
16499                } catch (PackageParserException e) {
16500                    // there was something wrong with the certificates we were given;
16501                    // try to pull them from the APK
16502                    PackageParser.collectCertificates(pkg, parseFlags);
16503                }
16504            } else {
16505                PackageParser.collectCertificates(pkg, parseFlags);
16506            }
16507        } catch (PackageParserException e) {
16508            res.setError("Failed collect during installPackageLI", e);
16509            return;
16510        }
16511
16512        // Get rid of all references to package scan path via parser.
16513        pp = null;
16514        String oldCodePath = null;
16515        boolean systemApp = false;
16516        synchronized (mPackages) {
16517            // Check if installing already existing package
16518            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16519                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16520                if (pkg.mOriginalPackages != null
16521                        && pkg.mOriginalPackages.contains(oldName)
16522                        && mPackages.containsKey(oldName)) {
16523                    // This package is derived from an original package,
16524                    // and this device has been updating from that original
16525                    // name.  We must continue using the original name, so
16526                    // rename the new package here.
16527                    pkg.setPackageName(oldName);
16528                    pkgName = pkg.packageName;
16529                    replace = true;
16530                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16531                            + oldName + " pkgName=" + pkgName);
16532                } else if (mPackages.containsKey(pkgName)) {
16533                    // This package, under its official name, already exists
16534                    // on the device; we should replace it.
16535                    replace = true;
16536                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16537                }
16538
16539                // Child packages are installed through the parent package
16540                if (pkg.parentPackage != null) {
16541                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16542                            "Package " + pkg.packageName + " is child of package "
16543                                    + pkg.parentPackage.parentPackage + ". Child packages "
16544                                    + "can be updated only through the parent package.");
16545                    return;
16546                }
16547
16548                if (replace) {
16549                    // Prevent apps opting out from runtime permissions
16550                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16551                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16552                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16553                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16554                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16555                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16556                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16557                                        + " doesn't support runtime permissions but the old"
16558                                        + " target SDK " + oldTargetSdk + " does.");
16559                        return;
16560                    }
16561
16562                    // Prevent installing of child packages
16563                    if (oldPackage.parentPackage != null) {
16564                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16565                                "Package " + pkg.packageName + " is child of package "
16566                                        + oldPackage.parentPackage + ". Child packages "
16567                                        + "can be updated only through the parent package.");
16568                        return;
16569                    }
16570                }
16571            }
16572
16573            PackageSetting ps = mSettings.mPackages.get(pkgName);
16574            if (ps != null) {
16575                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16576
16577                // Static shared libs have same package with different versions where
16578                // we internally use a synthetic package name to allow multiple versions
16579                // of the same package, therefore we need to compare signatures against
16580                // the package setting for the latest library version.
16581                PackageSetting signatureCheckPs = ps;
16582                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16583                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16584                    if (libraryEntry != null) {
16585                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16586                    }
16587                }
16588
16589                // Quick sanity check that we're signed correctly if updating;
16590                // we'll check this again later when scanning, but we want to
16591                // bail early here before tripping over redefined permissions.
16592                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16593                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16594                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16595                                + pkg.packageName + " upgrade keys do not match the "
16596                                + "previously installed version");
16597                        return;
16598                    }
16599                } else {
16600                    try {
16601                        verifySignaturesLP(signatureCheckPs, pkg);
16602                    } catch (PackageManagerException e) {
16603                        res.setError(e.error, e.getMessage());
16604                        return;
16605                    }
16606                }
16607
16608                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16609                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16610                    systemApp = (ps.pkg.applicationInfo.flags &
16611                            ApplicationInfo.FLAG_SYSTEM) != 0;
16612                }
16613                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16614            }
16615
16616            // Check whether the newly-scanned package wants to define an already-defined perm
16617            int N = pkg.permissions.size();
16618            for (int i = N-1; i >= 0; i--) {
16619                PackageParser.Permission perm = pkg.permissions.get(i);
16620                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16621                if (bp != null) {
16622                    // If the defining package is signed with our cert, it's okay.  This
16623                    // also includes the "updating the same package" case, of course.
16624                    // "updating same package" could also involve key-rotation.
16625                    final boolean sigsOk;
16626                    if (bp.sourcePackage.equals(pkg.packageName)
16627                            && (bp.packageSetting instanceof PackageSetting)
16628                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16629                                    scanFlags))) {
16630                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16631                    } else {
16632                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16633                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16634                    }
16635                    if (!sigsOk) {
16636                        // If the owning package is the system itself, we log but allow
16637                        // install to proceed; we fail the install on all other permission
16638                        // redefinitions.
16639                        if (!bp.sourcePackage.equals("android")) {
16640                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16641                                    + pkg.packageName + " attempting to redeclare permission "
16642                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16643                            res.origPermission = perm.info.name;
16644                            res.origPackage = bp.sourcePackage;
16645                            return;
16646                        } else {
16647                            Slog.w(TAG, "Package " + pkg.packageName
16648                                    + " attempting to redeclare system permission "
16649                                    + perm.info.name + "; ignoring new declaration");
16650                            pkg.permissions.remove(i);
16651                        }
16652                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16653                        // Prevent apps to change protection level to dangerous from any other
16654                        // type as this would allow a privilege escalation where an app adds a
16655                        // normal/signature permission in other app's group and later redefines
16656                        // it as dangerous leading to the group auto-grant.
16657                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16658                                == PermissionInfo.PROTECTION_DANGEROUS) {
16659                            if (bp != null && !bp.isRuntime()) {
16660                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16661                                        + "non-runtime permission " + perm.info.name
16662                                        + " to runtime; keeping old protection level");
16663                                perm.info.protectionLevel = bp.protectionLevel;
16664                            }
16665                        }
16666                    }
16667                }
16668            }
16669        }
16670
16671        if (systemApp) {
16672            if (onExternal) {
16673                // Abort update; system app can't be replaced with app on sdcard
16674                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16675                        "Cannot install updates to system apps on sdcard");
16676                return;
16677            } else if (ephemeral) {
16678                // Abort update; system app can't be replaced with an ephemeral app
16679                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16680                        "Cannot update a system app with an ephemeral app");
16681                return;
16682            }
16683        }
16684
16685        if (args.move != null) {
16686            // We did an in-place move, so dex is ready to roll
16687            scanFlags |= SCAN_NO_DEX;
16688            scanFlags |= SCAN_MOVE;
16689
16690            synchronized (mPackages) {
16691                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16692                if (ps == null) {
16693                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16694                            "Missing settings for moved package " + pkgName);
16695                }
16696
16697                // We moved the entire application as-is, so bring over the
16698                // previously derived ABI information.
16699                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16700                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16701            }
16702
16703        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16704            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16705            scanFlags |= SCAN_NO_DEX;
16706
16707            try {
16708                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16709                    args.abiOverride : pkg.cpuAbiOverride);
16710                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16711                        true /*extractLibs*/, mAppLib32InstallDir);
16712            } catch (PackageManagerException pme) {
16713                Slog.e(TAG, "Error deriving application ABI", pme);
16714                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16715                return;
16716            }
16717
16718            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16719            // Do not run PackageDexOptimizer through the local performDexOpt
16720            // method because `pkg` may not be in `mPackages` yet.
16721            //
16722            // Also, don't fail application installs if the dexopt step fails.
16723            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16724                    null /* instructionSets */, false /* checkProfiles */,
16725                    getCompilerFilterForReason(REASON_INSTALL),
16726                    getOrCreateCompilerPackageStats(pkg));
16727            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16728
16729            // Notify BackgroundDexOptService that the package has been changed.
16730            // If this is an update of a package which used to fail to compile,
16731            // BDOS will remove it from its blacklist.
16732            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16733        }
16734
16735        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16736            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16737            return;
16738        }
16739
16740        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16741
16742        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16743                "installPackageLI")) {
16744            if (replace) {
16745                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16746                    // Static libs have a synthetic package name containing the version
16747                    // and cannot be updated as an update would get a new package name,
16748                    // unless this is the exact same version code which is useful for
16749                    // development.
16750                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16751                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16752                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16753                                + "static-shared libs cannot be updated");
16754                        return;
16755                    }
16756                }
16757                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16758                        installerPackageName, res, args.installReason);
16759            } else {
16760                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16761                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16762            }
16763        }
16764        synchronized (mPackages) {
16765            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16766            if (ps != null) {
16767                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16768            }
16769
16770            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16771            for (int i = 0; i < childCount; i++) {
16772                PackageParser.Package childPkg = pkg.childPackages.get(i);
16773                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16774                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16775                if (childPs != null) {
16776                    childRes.newUsers = childPs.queryInstalledUsers(
16777                            sUserManager.getUserIds(), true);
16778                }
16779            }
16780        }
16781    }
16782
16783    private void startIntentFilterVerifications(int userId, boolean replacing,
16784            PackageParser.Package pkg) {
16785        if (mIntentFilterVerifierComponent == null) {
16786            Slog.w(TAG, "No IntentFilter verification will not be done as "
16787                    + "there is no IntentFilterVerifier available!");
16788            return;
16789        }
16790
16791        final int verifierUid = getPackageUid(
16792                mIntentFilterVerifierComponent.getPackageName(),
16793                MATCH_DEBUG_TRIAGED_MISSING,
16794                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16795
16796        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16797        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16798        mHandler.sendMessage(msg);
16799
16800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16801        for (int i = 0; i < childCount; i++) {
16802            PackageParser.Package childPkg = pkg.childPackages.get(i);
16803            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16804            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16805            mHandler.sendMessage(msg);
16806        }
16807    }
16808
16809    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16810            PackageParser.Package pkg) {
16811        int size = pkg.activities.size();
16812        if (size == 0) {
16813            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16814                    "No activity, so no need to verify any IntentFilter!");
16815            return;
16816        }
16817
16818        final boolean hasDomainURLs = hasDomainURLs(pkg);
16819        if (!hasDomainURLs) {
16820            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16821                    "No domain URLs, so no need to verify any IntentFilter!");
16822            return;
16823        }
16824
16825        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16826                + " if any IntentFilter from the " + size
16827                + " Activities needs verification ...");
16828
16829        int count = 0;
16830        final String packageName = pkg.packageName;
16831
16832        synchronized (mPackages) {
16833            // If this is a new install and we see that we've already run verification for this
16834            // package, we have nothing to do: it means the state was restored from backup.
16835            if (!replacing) {
16836                IntentFilterVerificationInfo ivi =
16837                        mSettings.getIntentFilterVerificationLPr(packageName);
16838                if (ivi != null) {
16839                    if (DEBUG_DOMAIN_VERIFICATION) {
16840                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16841                                + ivi.getStatusString());
16842                    }
16843                    return;
16844                }
16845            }
16846
16847            // If any filters need to be verified, then all need to be.
16848            boolean needToVerify = false;
16849            for (PackageParser.Activity a : pkg.activities) {
16850                for (ActivityIntentInfo filter : a.intents) {
16851                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16852                        if (DEBUG_DOMAIN_VERIFICATION) {
16853                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16854                        }
16855                        needToVerify = true;
16856                        break;
16857                    }
16858                }
16859            }
16860
16861            if (needToVerify) {
16862                final int verificationId = mIntentFilterVerificationToken++;
16863                for (PackageParser.Activity a : pkg.activities) {
16864                    for (ActivityIntentInfo filter : a.intents) {
16865                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16866                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16867                                    "Verification needed for IntentFilter:" + filter.toString());
16868                            mIntentFilterVerifier.addOneIntentFilterVerification(
16869                                    verifierUid, userId, verificationId, filter, packageName);
16870                            count++;
16871                        }
16872                    }
16873                }
16874            }
16875        }
16876
16877        if (count > 0) {
16878            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16879                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16880                    +  " for userId:" + userId);
16881            mIntentFilterVerifier.startVerifications(userId);
16882        } else {
16883            if (DEBUG_DOMAIN_VERIFICATION) {
16884                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16885            }
16886        }
16887    }
16888
16889    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16890        final ComponentName cn  = filter.activity.getComponentName();
16891        final String packageName = cn.getPackageName();
16892
16893        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16894                packageName);
16895        if (ivi == null) {
16896            return true;
16897        }
16898        int status = ivi.getStatus();
16899        switch (status) {
16900            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16901            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16902                return true;
16903
16904            default:
16905                // Nothing to do
16906                return false;
16907        }
16908    }
16909
16910    private static boolean isMultiArch(ApplicationInfo info) {
16911        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16912    }
16913
16914    private static boolean isExternal(PackageParser.Package pkg) {
16915        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16916    }
16917
16918    private static boolean isExternal(PackageSetting ps) {
16919        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16920    }
16921
16922    private static boolean isEphemeral(PackageParser.Package pkg) {
16923        return pkg.applicationInfo.isEphemeralApp();
16924    }
16925
16926    private static boolean isEphemeral(PackageSetting ps) {
16927        return ps.pkg != null && isEphemeral(ps.pkg);
16928    }
16929
16930    private static boolean isSystemApp(PackageParser.Package pkg) {
16931        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16932    }
16933
16934    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16935        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16936    }
16937
16938    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16939        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16940    }
16941
16942    private static boolean isSystemApp(PackageSetting ps) {
16943        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16944    }
16945
16946    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16947        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16948    }
16949
16950    private int packageFlagsToInstallFlags(PackageSetting ps) {
16951        int installFlags = 0;
16952        if (isEphemeral(ps)) {
16953            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16954        }
16955        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16956            // This existing package was an external ASEC install when we have
16957            // the external flag without a UUID
16958            installFlags |= PackageManager.INSTALL_EXTERNAL;
16959        }
16960        if (ps.isForwardLocked()) {
16961            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16962        }
16963        return installFlags;
16964    }
16965
16966    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16967        if (isExternal(pkg)) {
16968            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16969                return StorageManager.UUID_PRIMARY_PHYSICAL;
16970            } else {
16971                return pkg.volumeUuid;
16972            }
16973        } else {
16974            return StorageManager.UUID_PRIVATE_INTERNAL;
16975        }
16976    }
16977
16978    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16979        if (isExternal(pkg)) {
16980            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16981                return mSettings.getExternalVersion();
16982            } else {
16983                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16984            }
16985        } else {
16986            return mSettings.getInternalVersion();
16987        }
16988    }
16989
16990    private void deleteTempPackageFiles() {
16991        final FilenameFilter filter = new FilenameFilter() {
16992            public boolean accept(File dir, String name) {
16993                return name.startsWith("vmdl") && name.endsWith(".tmp");
16994            }
16995        };
16996        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16997            file.delete();
16998        }
16999    }
17000
17001    @Override
17002    public void deletePackageAsUser(String packageName, int versionCode,
17003            IPackageDeleteObserver observer, int userId, int flags) {
17004        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17005                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17006    }
17007
17008    @Override
17009    public void deletePackageVersioned(VersionedPackage versionedPackage,
17010            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17011        mContext.enforceCallingOrSelfPermission(
17012                android.Manifest.permission.DELETE_PACKAGES, null);
17013        Preconditions.checkNotNull(versionedPackage);
17014        Preconditions.checkNotNull(observer);
17015        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17016                PackageManager.VERSION_CODE_HIGHEST,
17017                Integer.MAX_VALUE, "versionCode must be >= -1");
17018
17019        final String packageName = versionedPackage.getPackageName();
17020        // TODO: We will change version code to long, so in the new API it is long
17021        final int versionCode = (int) versionedPackage.getVersionCode();
17022        final String internalPackageName;
17023        synchronized (mPackages) {
17024            // Normalize package name to handle renamed packages and static libs
17025            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17026                    // TODO: We will change version code to long, so in the new API it is long
17027                    (int) versionedPackage.getVersionCode());
17028        }
17029
17030        final int uid = Binder.getCallingUid();
17031        if (!isOrphaned(internalPackageName)
17032                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17033            try {
17034                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17035                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17036                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17037                observer.onUserActionRequired(intent);
17038            } catch (RemoteException re) {
17039            }
17040            return;
17041        }
17042        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17043        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17044        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17045            mContext.enforceCallingOrSelfPermission(
17046                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17047                    "deletePackage for user " + userId);
17048        }
17049
17050        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17051            try {
17052                observer.onPackageDeleted(packageName,
17053                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17054            } catch (RemoteException re) {
17055            }
17056            return;
17057        }
17058
17059        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17060            try {
17061                observer.onPackageDeleted(packageName,
17062                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17063            } catch (RemoteException re) {
17064            }
17065            return;
17066        }
17067
17068        if (DEBUG_REMOVE) {
17069            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17070                    + " deleteAllUsers: " + deleteAllUsers + " version="
17071                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17072                    ? "VERSION_CODE_HIGHEST" : versionCode));
17073        }
17074        // Queue up an async operation since the package deletion may take a little while.
17075        mHandler.post(new Runnable() {
17076            public void run() {
17077                mHandler.removeCallbacks(this);
17078                int returnCode;
17079                if (!deleteAllUsers) {
17080                    returnCode = deletePackageX(internalPackageName, versionCode,
17081                            userId, deleteFlags);
17082                } else {
17083                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17084                            internalPackageName, users);
17085                    // If nobody is blocking uninstall, proceed with delete for all users
17086                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17087                        returnCode = deletePackageX(internalPackageName, versionCode,
17088                                userId, deleteFlags);
17089                    } else {
17090                        // Otherwise uninstall individually for users with blockUninstalls=false
17091                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17092                        for (int userId : users) {
17093                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17094                                returnCode = deletePackageX(internalPackageName, versionCode,
17095                                        userId, userFlags);
17096                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17097                                    Slog.w(TAG, "Package delete failed for user " + userId
17098                                            + ", returnCode " + returnCode);
17099                                }
17100                            }
17101                        }
17102                        // The app has only been marked uninstalled for certain users.
17103                        // We still need to report that delete was blocked
17104                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17105                    }
17106                }
17107                try {
17108                    observer.onPackageDeleted(packageName, returnCode, null);
17109                } catch (RemoteException e) {
17110                    Log.i(TAG, "Observer no longer exists.");
17111                } //end catch
17112            } //end run
17113        });
17114    }
17115
17116    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17117        if (pkg.staticSharedLibName != null) {
17118            return pkg.manifestPackageName;
17119        }
17120        return pkg.packageName;
17121    }
17122
17123    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17124        // Handle renamed packages
17125        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17126        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17127
17128        // Is this a static library?
17129        SparseArray<SharedLibraryEntry> versionedLib =
17130                mStaticLibsByDeclaringPackage.get(packageName);
17131        if (versionedLib == null || versionedLib.size() <= 0) {
17132            return packageName;
17133        }
17134
17135        // Figure out which lib versions the caller can see
17136        SparseIntArray versionsCallerCanSee = null;
17137        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17138        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17139                && callingAppId != Process.ROOT_UID) {
17140            versionsCallerCanSee = new SparseIntArray();
17141            String libName = versionedLib.valueAt(0).info.getName();
17142            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17143            if (uidPackages != null) {
17144                for (String uidPackage : uidPackages) {
17145                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17146                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17147                    if (libIdx >= 0) {
17148                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17149                        versionsCallerCanSee.append(libVersion, libVersion);
17150                    }
17151                }
17152            }
17153        }
17154
17155        // Caller can see nothing - done
17156        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17157            return packageName;
17158        }
17159
17160        // Find the version the caller can see and the app version code
17161        SharedLibraryEntry highestVersion = null;
17162        final int versionCount = versionedLib.size();
17163        for (int i = 0; i < versionCount; i++) {
17164            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17165            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17166                    libEntry.info.getVersion()) < 0) {
17167                continue;
17168            }
17169            // TODO: We will change version code to long, so in the new API it is long
17170            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17171            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17172                if (libVersionCode == versionCode) {
17173                    return libEntry.apk;
17174                }
17175            } else if (highestVersion == null) {
17176                highestVersion = libEntry;
17177            } else if (libVersionCode  > highestVersion.info
17178                    .getDeclaringPackage().getVersionCode()) {
17179                highestVersion = libEntry;
17180            }
17181        }
17182
17183        if (highestVersion != null) {
17184            return highestVersion.apk;
17185        }
17186
17187        return packageName;
17188    }
17189
17190    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17191        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17192              || callingUid == Process.SYSTEM_UID) {
17193            return true;
17194        }
17195        final int callingUserId = UserHandle.getUserId(callingUid);
17196        // If the caller installed the pkgName, then allow it to silently uninstall.
17197        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17198            return true;
17199        }
17200
17201        // Allow package verifier to silently uninstall.
17202        if (mRequiredVerifierPackage != null &&
17203                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17204            return true;
17205        }
17206
17207        // Allow package uninstaller to silently uninstall.
17208        if (mRequiredUninstallerPackage != null &&
17209                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17210            return true;
17211        }
17212
17213        // Allow storage manager to silently uninstall.
17214        if (mStorageManagerPackage != null &&
17215                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17216            return true;
17217        }
17218        return false;
17219    }
17220
17221    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17222        int[] result = EMPTY_INT_ARRAY;
17223        for (int userId : userIds) {
17224            if (getBlockUninstallForUser(packageName, userId)) {
17225                result = ArrayUtils.appendInt(result, userId);
17226            }
17227        }
17228        return result;
17229    }
17230
17231    @Override
17232    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17233        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17234    }
17235
17236    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17237        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17238                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17239        try {
17240            if (dpm != null) {
17241                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17242                        /* callingUserOnly =*/ false);
17243                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17244                        : deviceOwnerComponentName.getPackageName();
17245                // Does the package contains the device owner?
17246                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17247                // this check is probably not needed, since DO should be registered as a device
17248                // admin on some user too. (Original bug for this: b/17657954)
17249                if (packageName.equals(deviceOwnerPackageName)) {
17250                    return true;
17251                }
17252                // Does it contain a device admin for any user?
17253                int[] users;
17254                if (userId == UserHandle.USER_ALL) {
17255                    users = sUserManager.getUserIds();
17256                } else {
17257                    users = new int[]{userId};
17258                }
17259                for (int i = 0; i < users.length; ++i) {
17260                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17261                        return true;
17262                    }
17263                }
17264            }
17265        } catch (RemoteException e) {
17266        }
17267        return false;
17268    }
17269
17270    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17271        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17272    }
17273
17274    /**
17275     *  This method is an internal method that could be get invoked either
17276     *  to delete an installed package or to clean up a failed installation.
17277     *  After deleting an installed package, a broadcast is sent to notify any
17278     *  listeners that the package has been removed. For cleaning up a failed
17279     *  installation, the broadcast is not necessary since the package's
17280     *  installation wouldn't have sent the initial broadcast either
17281     *  The key steps in deleting a package are
17282     *  deleting the package information in internal structures like mPackages,
17283     *  deleting the packages base directories through installd
17284     *  updating mSettings to reflect current status
17285     *  persisting settings for later use
17286     *  sending a broadcast if necessary
17287     */
17288    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17289        final PackageRemovedInfo info = new PackageRemovedInfo();
17290        final boolean res;
17291
17292        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17293                ? UserHandle.USER_ALL : userId;
17294
17295        if (isPackageDeviceAdmin(packageName, removeUser)) {
17296            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17297            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17298        }
17299
17300        PackageSetting uninstalledPs = null;
17301
17302        // for the uninstall-updates case and restricted profiles, remember the per-
17303        // user handle installed state
17304        int[] allUsers;
17305        synchronized (mPackages) {
17306            uninstalledPs = mSettings.mPackages.get(packageName);
17307            if (uninstalledPs == null) {
17308                Slog.w(TAG, "Not removing non-existent package " + packageName);
17309                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17310            }
17311
17312            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17313                    && uninstalledPs.versionCode != versionCode) {
17314                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17315                        + uninstalledPs.versionCode + " != " + versionCode);
17316                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17317            }
17318
17319            // Static shared libs can be declared by any package, so let us not
17320            // allow removing a package if it provides a lib others depend on.
17321            PackageParser.Package pkg = mPackages.get(packageName);
17322            if (pkg != null && pkg.staticSharedLibName != null) {
17323                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17324                        pkg.staticSharedLibVersion);
17325                if (libEntry != null) {
17326                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17327                            libEntry.info, 0, userId);
17328                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17329                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17330                                + " hosting lib " + libEntry.info.getName() + " version "
17331                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17332                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17333                    }
17334                }
17335            }
17336
17337            allUsers = sUserManager.getUserIds();
17338            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17339        }
17340
17341        final int freezeUser;
17342        if (isUpdatedSystemApp(uninstalledPs)
17343                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17344            // We're downgrading a system app, which will apply to all users, so
17345            // freeze them all during the downgrade
17346            freezeUser = UserHandle.USER_ALL;
17347        } else {
17348            freezeUser = removeUser;
17349        }
17350
17351        synchronized (mInstallLock) {
17352            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17353            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17354                    deleteFlags, "deletePackageX")) {
17355                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17356                        deleteFlags | REMOVE_CHATTY, info, true, null);
17357            }
17358            synchronized (mPackages) {
17359                if (res) {
17360                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
17361                }
17362            }
17363        }
17364
17365        if (res) {
17366            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17367            info.sendPackageRemovedBroadcasts(killApp);
17368            info.sendSystemPackageUpdatedBroadcasts();
17369            info.sendSystemPackageAppearedBroadcasts();
17370        }
17371        // Force a gc here.
17372        Runtime.getRuntime().gc();
17373        // Delete the resources here after sending the broadcast to let
17374        // other processes clean up before deleting resources.
17375        if (info.args != null) {
17376            synchronized (mInstallLock) {
17377                info.args.doPostDeleteLI(true);
17378            }
17379        }
17380
17381        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17382    }
17383
17384    class PackageRemovedInfo {
17385        String removedPackage;
17386        int uid = -1;
17387        int removedAppId = -1;
17388        int[] origUsers;
17389        int[] removedUsers = null;
17390        SparseArray<Integer> installReasons;
17391        boolean isRemovedPackageSystemUpdate = false;
17392        boolean isUpdate;
17393        boolean dataRemoved;
17394        boolean removedForAllUsers;
17395        boolean isStaticSharedLib;
17396        // Clean up resources deleted packages.
17397        InstallArgs args = null;
17398        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17399        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17400
17401        void sendPackageRemovedBroadcasts(boolean killApp) {
17402            sendPackageRemovedBroadcastInternal(killApp);
17403            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17404            for (int i = 0; i < childCount; i++) {
17405                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17406                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17407            }
17408        }
17409
17410        void sendSystemPackageUpdatedBroadcasts() {
17411            if (isRemovedPackageSystemUpdate) {
17412                sendSystemPackageUpdatedBroadcastsInternal();
17413                final int childCount = (removedChildPackages != null)
17414                        ? removedChildPackages.size() : 0;
17415                for (int i = 0; i < childCount; i++) {
17416                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17417                    if (childInfo.isRemovedPackageSystemUpdate) {
17418                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17419                    }
17420                }
17421            }
17422        }
17423
17424        void sendSystemPackageAppearedBroadcasts() {
17425            final int packageCount = (appearedChildPackages != null)
17426                    ? appearedChildPackages.size() : 0;
17427            for (int i = 0; i < packageCount; i++) {
17428                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17429                sendPackageAddedForNewUsers(installedInfo.name, true,
17430                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17431            }
17432        }
17433
17434        private void sendSystemPackageUpdatedBroadcastsInternal() {
17435            Bundle extras = new Bundle(2);
17436            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17437            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17438            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17439                    extras, 0, null, null, null);
17440            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17441                    extras, 0, null, null, null);
17442            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17443                    null, 0, removedPackage, null, null);
17444        }
17445
17446        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17447            // Don't send static shared library removal broadcasts as these
17448            // libs are visible only the the apps that depend on them an one
17449            // cannot remove the library if it has a dependency.
17450            if (isStaticSharedLib) {
17451                return;
17452            }
17453            Bundle extras = new Bundle(2);
17454            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17455            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17456            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17457            if (isUpdate || isRemovedPackageSystemUpdate) {
17458                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17459            }
17460            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17461            if (removedPackage != null) {
17462                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17463                        extras, 0, null, null, removedUsers);
17464                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17465                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17466                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17467                            null, null, removedUsers);
17468                }
17469            }
17470            if (removedAppId >= 0) {
17471                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17472                        removedUsers);
17473            }
17474        }
17475    }
17476
17477    /*
17478     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17479     * flag is not set, the data directory is removed as well.
17480     * make sure this flag is set for partially installed apps. If not its meaningless to
17481     * delete a partially installed application.
17482     */
17483    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17484            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17485        String packageName = ps.name;
17486        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17487        // Retrieve object to delete permissions for shared user later on
17488        final PackageParser.Package deletedPkg;
17489        final PackageSetting deletedPs;
17490        // reader
17491        synchronized (mPackages) {
17492            deletedPkg = mPackages.get(packageName);
17493            deletedPs = mSettings.mPackages.get(packageName);
17494            if (outInfo != null) {
17495                outInfo.removedPackage = packageName;
17496                outInfo.isStaticSharedLib = deletedPkg != null
17497                        && deletedPkg.staticSharedLibName != null;
17498                outInfo.removedUsers = deletedPs != null
17499                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17500                        : null;
17501            }
17502        }
17503
17504        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17505
17506        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17507            final PackageParser.Package resolvedPkg;
17508            if (deletedPkg != null) {
17509                resolvedPkg = deletedPkg;
17510            } else {
17511                // We don't have a parsed package when it lives on an ejected
17512                // adopted storage device, so fake something together
17513                resolvedPkg = new PackageParser.Package(ps.name);
17514                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17515            }
17516            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17517                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17518            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17519            if (outInfo != null) {
17520                outInfo.dataRemoved = true;
17521            }
17522            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17523        }
17524
17525        int removedAppId = -1;
17526
17527        // writer
17528        synchronized (mPackages) {
17529            if (deletedPs != null) {
17530                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17531                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17532                    clearDefaultBrowserIfNeeded(packageName);
17533                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17534                    removedAppId = mSettings.removePackageLPw(packageName);
17535                    if (outInfo != null) {
17536                        outInfo.removedAppId = removedAppId;
17537                    }
17538                    updatePermissionsLPw(deletedPs.name, null, 0);
17539                    if (deletedPs.sharedUser != null) {
17540                        // Remove permissions associated with package. Since runtime
17541                        // permissions are per user we have to kill the removed package
17542                        // or packages running under the shared user of the removed
17543                        // package if revoking the permissions requested only by the removed
17544                        // package is successful and this causes a change in gids.
17545                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17546                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17547                                    userId);
17548                            if (userIdToKill == UserHandle.USER_ALL
17549                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17550                                // If gids changed for this user, kill all affected packages.
17551                                mHandler.post(new Runnable() {
17552                                    @Override
17553                                    public void run() {
17554                                        // This has to happen with no lock held.
17555                                        killApplication(deletedPs.name, deletedPs.appId,
17556                                                KILL_APP_REASON_GIDS_CHANGED);
17557                                    }
17558                                });
17559                                break;
17560                            }
17561                        }
17562                    }
17563                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17564                }
17565                // make sure to preserve per-user disabled state if this removal was just
17566                // a downgrade of a system app to the factory package
17567                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17568                    if (DEBUG_REMOVE) {
17569                        Slog.d(TAG, "Propagating install state across downgrade");
17570                    }
17571                    for (int userId : allUserHandles) {
17572                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17573                        if (DEBUG_REMOVE) {
17574                            Slog.d(TAG, "    user " + userId + " => " + installed);
17575                        }
17576                        ps.setInstalled(installed, userId);
17577                    }
17578                }
17579            }
17580            // can downgrade to reader
17581            if (writeSettings) {
17582                // Save settings now
17583                mSettings.writeLPr();
17584            }
17585        }
17586        if (removedAppId != -1) {
17587            // A user ID was deleted here. Go through all users and remove it
17588            // from KeyStore.
17589            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17590        }
17591    }
17592
17593    static boolean locationIsPrivileged(File path) {
17594        try {
17595            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17596                    .getCanonicalPath();
17597            return path.getCanonicalPath().startsWith(privilegedAppDir);
17598        } catch (IOException e) {
17599            Slog.e(TAG, "Unable to access code path " + path);
17600        }
17601        return false;
17602    }
17603
17604    /*
17605     * Tries to delete system package.
17606     */
17607    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17608            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17609            boolean writeSettings) {
17610        if (deletedPs.parentPackageName != null) {
17611            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17612            return false;
17613        }
17614
17615        final boolean applyUserRestrictions
17616                = (allUserHandles != null) && (outInfo.origUsers != null);
17617        final PackageSetting disabledPs;
17618        // Confirm if the system package has been updated
17619        // An updated system app can be deleted. This will also have to restore
17620        // the system pkg from system partition
17621        // reader
17622        synchronized (mPackages) {
17623            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17624        }
17625
17626        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17627                + " disabledPs=" + disabledPs);
17628
17629        if (disabledPs == null) {
17630            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17631            return false;
17632        } else if (DEBUG_REMOVE) {
17633            Slog.d(TAG, "Deleting system pkg from data partition");
17634        }
17635
17636        if (DEBUG_REMOVE) {
17637            if (applyUserRestrictions) {
17638                Slog.d(TAG, "Remembering install states:");
17639                for (int userId : allUserHandles) {
17640                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17641                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17642                }
17643            }
17644        }
17645
17646        // Delete the updated package
17647        outInfo.isRemovedPackageSystemUpdate = true;
17648        if (outInfo.removedChildPackages != null) {
17649            final int childCount = (deletedPs.childPackageNames != null)
17650                    ? deletedPs.childPackageNames.size() : 0;
17651            for (int i = 0; i < childCount; i++) {
17652                String childPackageName = deletedPs.childPackageNames.get(i);
17653                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17654                        .contains(childPackageName)) {
17655                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17656                            childPackageName);
17657                    if (childInfo != null) {
17658                        childInfo.isRemovedPackageSystemUpdate = true;
17659                    }
17660                }
17661            }
17662        }
17663
17664        if (disabledPs.versionCode < deletedPs.versionCode) {
17665            // Delete data for downgrades
17666            flags &= ~PackageManager.DELETE_KEEP_DATA;
17667        } else {
17668            // Preserve data by setting flag
17669            flags |= PackageManager.DELETE_KEEP_DATA;
17670        }
17671
17672        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17673                outInfo, writeSettings, disabledPs.pkg);
17674        if (!ret) {
17675            return false;
17676        }
17677
17678        // writer
17679        synchronized (mPackages) {
17680            // Reinstate the old system package
17681            enableSystemPackageLPw(disabledPs.pkg);
17682            // Remove any native libraries from the upgraded package.
17683            removeNativeBinariesLI(deletedPs);
17684        }
17685
17686        // Install the system package
17687        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17688        int parseFlags = mDefParseFlags
17689                | PackageParser.PARSE_MUST_BE_APK
17690                | PackageParser.PARSE_IS_SYSTEM
17691                | PackageParser.PARSE_IS_SYSTEM_DIR;
17692        if (locationIsPrivileged(disabledPs.codePath)) {
17693            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17694        }
17695
17696        final PackageParser.Package newPkg;
17697        try {
17698            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17699                0 /* currentTime */, null);
17700        } catch (PackageManagerException e) {
17701            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17702                    + e.getMessage());
17703            return false;
17704        }
17705
17706        prepareAppDataAfterInstallLIF(newPkg);
17707
17708        // writer
17709        synchronized (mPackages) {
17710            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17711
17712            // Propagate the permissions state as we do not want to drop on the floor
17713            // runtime permissions. The update permissions method below will take
17714            // care of removing obsolete permissions and grant install permissions.
17715            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17716            updatePermissionsLPw(newPkg.packageName, newPkg,
17717                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17718
17719            if (applyUserRestrictions) {
17720                if (DEBUG_REMOVE) {
17721                    Slog.d(TAG, "Propagating install state across reinstall");
17722                }
17723                for (int userId : allUserHandles) {
17724                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17725                    if (DEBUG_REMOVE) {
17726                        Slog.d(TAG, "    user " + userId + " => " + installed);
17727                    }
17728                    ps.setInstalled(installed, userId);
17729
17730                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17731                }
17732                // Regardless of writeSettings we need to ensure that this restriction
17733                // state propagation is persisted
17734                mSettings.writeAllUsersPackageRestrictionsLPr();
17735            }
17736            // can downgrade to reader here
17737            if (writeSettings) {
17738                mSettings.writeLPr();
17739            }
17740        }
17741        return true;
17742    }
17743
17744    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17745            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17746            PackageRemovedInfo outInfo, boolean writeSettings,
17747            PackageParser.Package replacingPackage) {
17748        synchronized (mPackages) {
17749            if (outInfo != null) {
17750                outInfo.uid = ps.appId;
17751            }
17752
17753            if (outInfo != null && outInfo.removedChildPackages != null) {
17754                final int childCount = (ps.childPackageNames != null)
17755                        ? ps.childPackageNames.size() : 0;
17756                for (int i = 0; i < childCount; i++) {
17757                    String childPackageName = ps.childPackageNames.get(i);
17758                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17759                    if (childPs == null) {
17760                        return false;
17761                    }
17762                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17763                            childPackageName);
17764                    if (childInfo != null) {
17765                        childInfo.uid = childPs.appId;
17766                    }
17767                }
17768            }
17769        }
17770
17771        // Delete package data from internal structures and also remove data if flag is set
17772        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17773
17774        // Delete the child packages data
17775        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17776        for (int i = 0; i < childCount; i++) {
17777            PackageSetting childPs;
17778            synchronized (mPackages) {
17779                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17780            }
17781            if (childPs != null) {
17782                PackageRemovedInfo childOutInfo = (outInfo != null
17783                        && outInfo.removedChildPackages != null)
17784                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17785                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17786                        && (replacingPackage != null
17787                        && !replacingPackage.hasChildPackage(childPs.name))
17788                        ? flags & ~DELETE_KEEP_DATA : flags;
17789                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17790                        deleteFlags, writeSettings);
17791            }
17792        }
17793
17794        // Delete application code and resources only for parent packages
17795        if (ps.parentPackageName == null) {
17796            if (deleteCodeAndResources && (outInfo != null)) {
17797                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17798                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17799                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17800            }
17801        }
17802
17803        return true;
17804    }
17805
17806    @Override
17807    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17808            int userId) {
17809        mContext.enforceCallingOrSelfPermission(
17810                android.Manifest.permission.DELETE_PACKAGES, null);
17811        synchronized (mPackages) {
17812            PackageSetting ps = mSettings.mPackages.get(packageName);
17813            if (ps == null) {
17814                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17815                return false;
17816            }
17817            // Cannot block uninstall of static shared libs as they are
17818            // considered a part of the using app (emulating static linking).
17819            // Also static libs are installed always on internal storage.
17820            PackageParser.Package pkg = mPackages.get(packageName);
17821            if (pkg != null && pkg.staticSharedLibName != null) {
17822                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17823                        + " providing static shared library: " + pkg.staticSharedLibName);
17824                return false;
17825            }
17826            if (!ps.getInstalled(userId)) {
17827                // Can't block uninstall for an app that is not installed or enabled.
17828                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17829                return false;
17830            }
17831            ps.setBlockUninstall(blockUninstall, userId);
17832            mSettings.writePackageRestrictionsLPr(userId);
17833        }
17834        return true;
17835    }
17836
17837    @Override
17838    public boolean getBlockUninstallForUser(String packageName, int userId) {
17839        synchronized (mPackages) {
17840            PackageSetting ps = mSettings.mPackages.get(packageName);
17841            if (ps == null) {
17842                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17843                return false;
17844            }
17845            return ps.getBlockUninstall(userId);
17846        }
17847    }
17848
17849    @Override
17850    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17851        int callingUid = Binder.getCallingUid();
17852        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17853            throw new SecurityException(
17854                    "setRequiredForSystemUser can only be run by the system or root");
17855        }
17856        synchronized (mPackages) {
17857            PackageSetting ps = mSettings.mPackages.get(packageName);
17858            if (ps == null) {
17859                Log.w(TAG, "Package doesn't exist: " + packageName);
17860                return false;
17861            }
17862            if (systemUserApp) {
17863                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17864            } else {
17865                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17866            }
17867            mSettings.writeLPr();
17868        }
17869        return true;
17870    }
17871
17872    /*
17873     * This method handles package deletion in general
17874     */
17875    private boolean deletePackageLIF(String packageName, UserHandle user,
17876            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17877            PackageRemovedInfo outInfo, boolean writeSettings,
17878            PackageParser.Package replacingPackage) {
17879        if (packageName == null) {
17880            Slog.w(TAG, "Attempt to delete null packageName.");
17881            return false;
17882        }
17883
17884        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17885
17886        PackageSetting ps;
17887        synchronized (mPackages) {
17888            ps = mSettings.mPackages.get(packageName);
17889            if (ps == null) {
17890                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17891                return false;
17892            }
17893
17894            if (ps.parentPackageName != null && (!isSystemApp(ps)
17895                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17896                if (DEBUG_REMOVE) {
17897                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17898                            + ((user == null) ? UserHandle.USER_ALL : user));
17899                }
17900                final int removedUserId = (user != null) ? user.getIdentifier()
17901                        : UserHandle.USER_ALL;
17902                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17903                    return false;
17904                }
17905                markPackageUninstalledForUserLPw(ps, user);
17906                scheduleWritePackageRestrictionsLocked(user);
17907                return true;
17908            }
17909        }
17910
17911        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17912                && user.getIdentifier() != UserHandle.USER_ALL)) {
17913            // The caller is asking that the package only be deleted for a single
17914            // user.  To do this, we just mark its uninstalled state and delete
17915            // its data. If this is a system app, we only allow this to happen if
17916            // they have set the special DELETE_SYSTEM_APP which requests different
17917            // semantics than normal for uninstalling system apps.
17918            markPackageUninstalledForUserLPw(ps, user);
17919
17920            if (!isSystemApp(ps)) {
17921                // Do not uninstall the APK if an app should be cached
17922                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17923                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17924                    // Other user still have this package installed, so all
17925                    // we need to do is clear this user's data and save that
17926                    // it is uninstalled.
17927                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17928                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17929                        return false;
17930                    }
17931                    scheduleWritePackageRestrictionsLocked(user);
17932                    return true;
17933                } else {
17934                    // We need to set it back to 'installed' so the uninstall
17935                    // broadcasts will be sent correctly.
17936                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17937                    ps.setInstalled(true, user.getIdentifier());
17938                }
17939            } else {
17940                // This is a system app, so we assume that the
17941                // other users still have this package installed, so all
17942                // we need to do is clear this user's data and save that
17943                // it is uninstalled.
17944                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17945                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17946                    return false;
17947                }
17948                scheduleWritePackageRestrictionsLocked(user);
17949                return true;
17950            }
17951        }
17952
17953        // If we are deleting a composite package for all users, keep track
17954        // of result for each child.
17955        if (ps.childPackageNames != null && outInfo != null) {
17956            synchronized (mPackages) {
17957                final int childCount = ps.childPackageNames.size();
17958                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17959                for (int i = 0; i < childCount; i++) {
17960                    String childPackageName = ps.childPackageNames.get(i);
17961                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17962                    childInfo.removedPackage = childPackageName;
17963                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17964                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17965                    if (childPs != null) {
17966                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17967                    }
17968                }
17969            }
17970        }
17971
17972        boolean ret = false;
17973        if (isSystemApp(ps)) {
17974            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17975            // When an updated system application is deleted we delete the existing resources
17976            // as well and fall back to existing code in system partition
17977            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17978        } else {
17979            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17980            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17981                    outInfo, writeSettings, replacingPackage);
17982        }
17983
17984        // Take a note whether we deleted the package for all users
17985        if (outInfo != null) {
17986            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17987            if (outInfo.removedChildPackages != null) {
17988                synchronized (mPackages) {
17989                    final int childCount = outInfo.removedChildPackages.size();
17990                    for (int i = 0; i < childCount; i++) {
17991                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17992                        if (childInfo != null) {
17993                            childInfo.removedForAllUsers = mPackages.get(
17994                                    childInfo.removedPackage) == null;
17995                        }
17996                    }
17997                }
17998            }
17999            // If we uninstalled an update to a system app there may be some
18000            // child packages that appeared as they are declared in the system
18001            // app but were not declared in the update.
18002            if (isSystemApp(ps)) {
18003                synchronized (mPackages) {
18004                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18005                    final int childCount = (updatedPs.childPackageNames != null)
18006                            ? updatedPs.childPackageNames.size() : 0;
18007                    for (int i = 0; i < childCount; i++) {
18008                        String childPackageName = updatedPs.childPackageNames.get(i);
18009                        if (outInfo.removedChildPackages == null
18010                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18011                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18012                            if (childPs == null) {
18013                                continue;
18014                            }
18015                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18016                            installRes.name = childPackageName;
18017                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18018                            installRes.pkg = mPackages.get(childPackageName);
18019                            installRes.uid = childPs.pkg.applicationInfo.uid;
18020                            if (outInfo.appearedChildPackages == null) {
18021                                outInfo.appearedChildPackages = new ArrayMap<>();
18022                            }
18023                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18024                        }
18025                    }
18026                }
18027            }
18028        }
18029
18030        return ret;
18031    }
18032
18033    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18034        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18035                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18036        for (int nextUserId : userIds) {
18037            if (DEBUG_REMOVE) {
18038                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18039            }
18040            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18041                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18042                    false /*hidden*/, false /*suspended*/, null, null, null,
18043                    false /*blockUninstall*/,
18044                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18045                    PackageManager.INSTALL_REASON_UNKNOWN);
18046        }
18047    }
18048
18049    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18050            PackageRemovedInfo outInfo) {
18051        final PackageParser.Package pkg;
18052        synchronized (mPackages) {
18053            pkg = mPackages.get(ps.name);
18054        }
18055
18056        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18057                : new int[] {userId};
18058        for (int nextUserId : userIds) {
18059            if (DEBUG_REMOVE) {
18060                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18061                        + nextUserId);
18062            }
18063
18064            destroyAppDataLIF(pkg, userId,
18065                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18066            destroyAppProfilesLIF(pkg, userId);
18067            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18068            schedulePackageCleaning(ps.name, nextUserId, false);
18069            synchronized (mPackages) {
18070                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18071                    scheduleWritePackageRestrictionsLocked(nextUserId);
18072                }
18073                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18074            }
18075        }
18076
18077        if (outInfo != null) {
18078            outInfo.removedPackage = ps.name;
18079            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18080            outInfo.removedAppId = ps.appId;
18081            outInfo.removedUsers = userIds;
18082        }
18083
18084        return true;
18085    }
18086
18087    private final class ClearStorageConnection implements ServiceConnection {
18088        IMediaContainerService mContainerService;
18089
18090        @Override
18091        public void onServiceConnected(ComponentName name, IBinder service) {
18092            synchronized (this) {
18093                mContainerService = IMediaContainerService.Stub
18094                        .asInterface(Binder.allowBlocking(service));
18095                notifyAll();
18096            }
18097        }
18098
18099        @Override
18100        public void onServiceDisconnected(ComponentName name) {
18101        }
18102    }
18103
18104    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18105        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18106
18107        final boolean mounted;
18108        if (Environment.isExternalStorageEmulated()) {
18109            mounted = true;
18110        } else {
18111            final String status = Environment.getExternalStorageState();
18112
18113            mounted = status.equals(Environment.MEDIA_MOUNTED)
18114                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18115        }
18116
18117        if (!mounted) {
18118            return;
18119        }
18120
18121        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18122        int[] users;
18123        if (userId == UserHandle.USER_ALL) {
18124            users = sUserManager.getUserIds();
18125        } else {
18126            users = new int[] { userId };
18127        }
18128        final ClearStorageConnection conn = new ClearStorageConnection();
18129        if (mContext.bindServiceAsUser(
18130                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18131            try {
18132                for (int curUser : users) {
18133                    long timeout = SystemClock.uptimeMillis() + 5000;
18134                    synchronized (conn) {
18135                        long now;
18136                        while (conn.mContainerService == null &&
18137                                (now = SystemClock.uptimeMillis()) < timeout) {
18138                            try {
18139                                conn.wait(timeout - now);
18140                            } catch (InterruptedException e) {
18141                            }
18142                        }
18143                    }
18144                    if (conn.mContainerService == null) {
18145                        return;
18146                    }
18147
18148                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18149                    clearDirectory(conn.mContainerService,
18150                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18151                    if (allData) {
18152                        clearDirectory(conn.mContainerService,
18153                                userEnv.buildExternalStorageAppDataDirs(packageName));
18154                        clearDirectory(conn.mContainerService,
18155                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18156                    }
18157                }
18158            } finally {
18159                mContext.unbindService(conn);
18160            }
18161        }
18162    }
18163
18164    @Override
18165    public void clearApplicationProfileData(String packageName) {
18166        enforceSystemOrRoot("Only the system can clear all profile data");
18167
18168        final PackageParser.Package pkg;
18169        synchronized (mPackages) {
18170            pkg = mPackages.get(packageName);
18171        }
18172
18173        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18174            synchronized (mInstallLock) {
18175                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18176                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18177                        true /* removeBaseMarker */);
18178            }
18179        }
18180    }
18181
18182    @Override
18183    public void clearApplicationUserData(final String packageName,
18184            final IPackageDataObserver observer, final int userId) {
18185        mContext.enforceCallingOrSelfPermission(
18186                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18187
18188        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18189                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18190
18191        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18192            throw new SecurityException("Cannot clear data for a protected package: "
18193                    + packageName);
18194        }
18195        // Queue up an async operation since the package deletion may take a little while.
18196        mHandler.post(new Runnable() {
18197            public void run() {
18198                mHandler.removeCallbacks(this);
18199                final boolean succeeded;
18200                try (PackageFreezer freezer = freezePackage(packageName,
18201                        "clearApplicationUserData")) {
18202                    synchronized (mInstallLock) {
18203                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18204                    }
18205                    clearExternalStorageDataSync(packageName, userId, true);
18206                }
18207                if (succeeded) {
18208                    // invoke DeviceStorageMonitor's update method to clear any notifications
18209                    DeviceStorageMonitorInternal dsm = LocalServices
18210                            .getService(DeviceStorageMonitorInternal.class);
18211                    if (dsm != null) {
18212                        dsm.checkMemory();
18213                    }
18214                }
18215                if(observer != null) {
18216                    try {
18217                        observer.onRemoveCompleted(packageName, succeeded);
18218                    } catch (RemoteException e) {
18219                        Log.i(TAG, "Observer no longer exists.");
18220                    }
18221                } //end if observer
18222            } //end run
18223        });
18224    }
18225
18226    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18227        if (packageName == null) {
18228            Slog.w(TAG, "Attempt to delete null packageName.");
18229            return false;
18230        }
18231
18232        // Try finding details about the requested package
18233        PackageParser.Package pkg;
18234        synchronized (mPackages) {
18235            pkg = mPackages.get(packageName);
18236            if (pkg == null) {
18237                final PackageSetting ps = mSettings.mPackages.get(packageName);
18238                if (ps != null) {
18239                    pkg = ps.pkg;
18240                }
18241            }
18242
18243            if (pkg == null) {
18244                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18245                return false;
18246            }
18247
18248            PackageSetting ps = (PackageSetting) pkg.mExtras;
18249            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18250        }
18251
18252        clearAppDataLIF(pkg, userId,
18253                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18254
18255        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18256        removeKeystoreDataIfNeeded(userId, appId);
18257
18258        UserManagerInternal umInternal = getUserManagerInternal();
18259        final int flags;
18260        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18261            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18262        } else if (umInternal.isUserRunning(userId)) {
18263            flags = StorageManager.FLAG_STORAGE_DE;
18264        } else {
18265            flags = 0;
18266        }
18267        prepareAppDataContentsLIF(pkg, userId, flags);
18268
18269        return true;
18270    }
18271
18272    /**
18273     * Reverts user permission state changes (permissions and flags) in
18274     * all packages for a given user.
18275     *
18276     * @param userId The device user for which to do a reset.
18277     */
18278    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18279        final int packageCount = mPackages.size();
18280        for (int i = 0; i < packageCount; i++) {
18281            PackageParser.Package pkg = mPackages.valueAt(i);
18282            PackageSetting ps = (PackageSetting) pkg.mExtras;
18283            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18284        }
18285    }
18286
18287    private void resetNetworkPolicies(int userId) {
18288        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18289    }
18290
18291    /**
18292     * Reverts user permission state changes (permissions and flags).
18293     *
18294     * @param ps The package for which to reset.
18295     * @param userId The device user for which to do a reset.
18296     */
18297    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18298            final PackageSetting ps, final int userId) {
18299        if (ps.pkg == null) {
18300            return;
18301        }
18302
18303        // These are flags that can change base on user actions.
18304        final int userSettableMask = FLAG_PERMISSION_USER_SET
18305                | FLAG_PERMISSION_USER_FIXED
18306                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18307                | FLAG_PERMISSION_REVIEW_REQUIRED;
18308
18309        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18310                | FLAG_PERMISSION_POLICY_FIXED;
18311
18312        boolean writeInstallPermissions = false;
18313        boolean writeRuntimePermissions = false;
18314
18315        final int permissionCount = ps.pkg.requestedPermissions.size();
18316        for (int i = 0; i < permissionCount; i++) {
18317            String permission = ps.pkg.requestedPermissions.get(i);
18318
18319            BasePermission bp = mSettings.mPermissions.get(permission);
18320            if (bp == null) {
18321                continue;
18322            }
18323
18324            // If shared user we just reset the state to which only this app contributed.
18325            if (ps.sharedUser != null) {
18326                boolean used = false;
18327                final int packageCount = ps.sharedUser.packages.size();
18328                for (int j = 0; j < packageCount; j++) {
18329                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18330                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18331                            && pkg.pkg.requestedPermissions.contains(permission)) {
18332                        used = true;
18333                        break;
18334                    }
18335                }
18336                if (used) {
18337                    continue;
18338                }
18339            }
18340
18341            PermissionsState permissionsState = ps.getPermissionsState();
18342
18343            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18344
18345            // Always clear the user settable flags.
18346            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18347                    bp.name) != null;
18348            // If permission review is enabled and this is a legacy app, mark the
18349            // permission as requiring a review as this is the initial state.
18350            int flags = 0;
18351            if (mPermissionReviewRequired
18352                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18353                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18354            }
18355            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18356                if (hasInstallState) {
18357                    writeInstallPermissions = true;
18358                } else {
18359                    writeRuntimePermissions = true;
18360                }
18361            }
18362
18363            // Below is only runtime permission handling.
18364            if (!bp.isRuntime()) {
18365                continue;
18366            }
18367
18368            // Never clobber system or policy.
18369            if ((oldFlags & policyOrSystemFlags) != 0) {
18370                continue;
18371            }
18372
18373            // If this permission was granted by default, make sure it is.
18374            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18375                if (permissionsState.grantRuntimePermission(bp, userId)
18376                        != PERMISSION_OPERATION_FAILURE) {
18377                    writeRuntimePermissions = true;
18378                }
18379            // If permission review is enabled the permissions for a legacy apps
18380            // are represented as constantly granted runtime ones, so don't revoke.
18381            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18382                // Otherwise, reset the permission.
18383                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18384                switch (revokeResult) {
18385                    case PERMISSION_OPERATION_SUCCESS:
18386                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18387                        writeRuntimePermissions = true;
18388                        final int appId = ps.appId;
18389                        mHandler.post(new Runnable() {
18390                            @Override
18391                            public void run() {
18392                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18393                            }
18394                        });
18395                    } break;
18396                }
18397            }
18398        }
18399
18400        // Synchronously write as we are taking permissions away.
18401        if (writeRuntimePermissions) {
18402            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18403        }
18404
18405        // Synchronously write as we are taking permissions away.
18406        if (writeInstallPermissions) {
18407            mSettings.writeLPr();
18408        }
18409    }
18410
18411    /**
18412     * Remove entries from the keystore daemon. Will only remove it if the
18413     * {@code appId} is valid.
18414     */
18415    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18416        if (appId < 0) {
18417            return;
18418        }
18419
18420        final KeyStore keyStore = KeyStore.getInstance();
18421        if (keyStore != null) {
18422            if (userId == UserHandle.USER_ALL) {
18423                for (final int individual : sUserManager.getUserIds()) {
18424                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18425                }
18426            } else {
18427                keyStore.clearUid(UserHandle.getUid(userId, appId));
18428            }
18429        } else {
18430            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18431        }
18432    }
18433
18434    @Override
18435    public void deleteApplicationCacheFiles(final String packageName,
18436            final IPackageDataObserver observer) {
18437        final int userId = UserHandle.getCallingUserId();
18438        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18439    }
18440
18441    @Override
18442    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18443            final IPackageDataObserver observer) {
18444        mContext.enforceCallingOrSelfPermission(
18445                android.Manifest.permission.DELETE_CACHE_FILES, null);
18446        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18447                /* requireFullPermission= */ true, /* checkShell= */ false,
18448                "delete application cache files");
18449
18450        final PackageParser.Package pkg;
18451        synchronized (mPackages) {
18452            pkg = mPackages.get(packageName);
18453        }
18454
18455        // Queue up an async operation since the package deletion may take a little while.
18456        mHandler.post(new Runnable() {
18457            public void run() {
18458                synchronized (mInstallLock) {
18459                    final int flags = StorageManager.FLAG_STORAGE_DE
18460                            | StorageManager.FLAG_STORAGE_CE;
18461                    // We're only clearing cache files, so we don't care if the
18462                    // app is unfrozen and still able to run
18463                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18464                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18465                }
18466                clearExternalStorageDataSync(packageName, userId, false);
18467                if (observer != null) {
18468                    try {
18469                        observer.onRemoveCompleted(packageName, true);
18470                    } catch (RemoteException e) {
18471                        Log.i(TAG, "Observer no longer exists.");
18472                    }
18473                }
18474            }
18475        });
18476    }
18477
18478    @Override
18479    public void getPackageSizeInfo(final String packageName, int userHandle,
18480            final IPackageStatsObserver observer) {
18481        mContext.enforceCallingOrSelfPermission(
18482                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18483        if (packageName == null) {
18484            throw new IllegalArgumentException("Attempt to get size of null packageName");
18485        }
18486
18487        PackageStats stats = new PackageStats(packageName, userHandle);
18488
18489        /*
18490         * Queue up an async operation since the package measurement may take a
18491         * little while.
18492         */
18493        Message msg = mHandler.obtainMessage(INIT_COPY);
18494        msg.obj = new MeasureParams(stats, observer);
18495        mHandler.sendMessage(msg);
18496    }
18497
18498    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18499        final PackageSetting ps;
18500        synchronized (mPackages) {
18501            ps = mSettings.mPackages.get(packageName);
18502            if (ps == null) {
18503                Slog.w(TAG, "Failed to find settings for " + packageName);
18504                return false;
18505            }
18506        }
18507
18508        final String[] packageNames = { packageName };
18509        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18510        final String[] codePaths = { ps.codePathString };
18511
18512        try {
18513            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18514                    ps.appId, ceDataInodes, codePaths, stats);
18515
18516            // For now, ignore code size of packages on system partition
18517            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18518                stats.codeSize = 0;
18519            }
18520
18521            // External clients expect these to be tracked separately
18522            stats.dataSize -= stats.cacheSize;
18523
18524        } catch (InstallerException e) {
18525            Slog.w(TAG, String.valueOf(e));
18526            return false;
18527        }
18528
18529        return true;
18530    }
18531
18532    private int getUidTargetSdkVersionLockedLPr(int uid) {
18533        Object obj = mSettings.getUserIdLPr(uid);
18534        if (obj instanceof SharedUserSetting) {
18535            final SharedUserSetting sus = (SharedUserSetting) obj;
18536            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18537            final Iterator<PackageSetting> it = sus.packages.iterator();
18538            while (it.hasNext()) {
18539                final PackageSetting ps = it.next();
18540                if (ps.pkg != null) {
18541                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18542                    if (v < vers) vers = v;
18543                }
18544            }
18545            return vers;
18546        } else if (obj instanceof PackageSetting) {
18547            final PackageSetting ps = (PackageSetting) obj;
18548            if (ps.pkg != null) {
18549                return ps.pkg.applicationInfo.targetSdkVersion;
18550            }
18551        }
18552        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18553    }
18554
18555    @Override
18556    public void addPreferredActivity(IntentFilter filter, int match,
18557            ComponentName[] set, ComponentName activity, int userId) {
18558        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18559                "Adding preferred");
18560    }
18561
18562    private void addPreferredActivityInternal(IntentFilter filter, int match,
18563            ComponentName[] set, ComponentName activity, boolean always, int userId,
18564            String opname) {
18565        // writer
18566        int callingUid = Binder.getCallingUid();
18567        enforceCrossUserPermission(callingUid, userId,
18568                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18569        if (filter.countActions() == 0) {
18570            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18571            return;
18572        }
18573        synchronized (mPackages) {
18574            if (mContext.checkCallingOrSelfPermission(
18575                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18576                    != PackageManager.PERMISSION_GRANTED) {
18577                if (getUidTargetSdkVersionLockedLPr(callingUid)
18578                        < Build.VERSION_CODES.FROYO) {
18579                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18580                            + callingUid);
18581                    return;
18582                }
18583                mContext.enforceCallingOrSelfPermission(
18584                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18585            }
18586
18587            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18588            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18589                    + userId + ":");
18590            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18591            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18592            scheduleWritePackageRestrictionsLocked(userId);
18593            postPreferredActivityChangedBroadcast(userId);
18594        }
18595    }
18596
18597    private void postPreferredActivityChangedBroadcast(int userId) {
18598        mHandler.post(() -> {
18599            final IActivityManager am = ActivityManager.getService();
18600            if (am == null) {
18601                return;
18602            }
18603
18604            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18605            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18606            try {
18607                am.broadcastIntent(null, intent, null, null,
18608                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18609                        null, false, false, userId);
18610            } catch (RemoteException e) {
18611            }
18612        });
18613    }
18614
18615    @Override
18616    public void replacePreferredActivity(IntentFilter filter, int match,
18617            ComponentName[] set, ComponentName activity, int userId) {
18618        if (filter.countActions() != 1) {
18619            throw new IllegalArgumentException(
18620                    "replacePreferredActivity expects filter to have only 1 action.");
18621        }
18622        if (filter.countDataAuthorities() != 0
18623                || filter.countDataPaths() != 0
18624                || filter.countDataSchemes() > 1
18625                || filter.countDataTypes() != 0) {
18626            throw new IllegalArgumentException(
18627                    "replacePreferredActivity expects filter to have no data authorities, " +
18628                    "paths, or types; and at most one scheme.");
18629        }
18630
18631        final int callingUid = Binder.getCallingUid();
18632        enforceCrossUserPermission(callingUid, userId,
18633                true /* requireFullPermission */, false /* checkShell */,
18634                "replace preferred activity");
18635        synchronized (mPackages) {
18636            if (mContext.checkCallingOrSelfPermission(
18637                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18638                    != PackageManager.PERMISSION_GRANTED) {
18639                if (getUidTargetSdkVersionLockedLPr(callingUid)
18640                        < Build.VERSION_CODES.FROYO) {
18641                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18642                            + Binder.getCallingUid());
18643                    return;
18644                }
18645                mContext.enforceCallingOrSelfPermission(
18646                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18647            }
18648
18649            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18650            if (pir != null) {
18651                // Get all of the existing entries that exactly match this filter.
18652                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18653                if (existing != null && existing.size() == 1) {
18654                    PreferredActivity cur = existing.get(0);
18655                    if (DEBUG_PREFERRED) {
18656                        Slog.i(TAG, "Checking replace of preferred:");
18657                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18658                        if (!cur.mPref.mAlways) {
18659                            Slog.i(TAG, "  -- CUR; not mAlways!");
18660                        } else {
18661                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18662                            Slog.i(TAG, "  -- CUR: mSet="
18663                                    + Arrays.toString(cur.mPref.mSetComponents));
18664                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18665                            Slog.i(TAG, "  -- NEW: mMatch="
18666                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18667                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18668                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18669                        }
18670                    }
18671                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18672                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18673                            && cur.mPref.sameSet(set)) {
18674                        // Setting the preferred activity to what it happens to be already
18675                        if (DEBUG_PREFERRED) {
18676                            Slog.i(TAG, "Replacing with same preferred activity "
18677                                    + cur.mPref.mShortComponent + " for user "
18678                                    + userId + ":");
18679                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18680                        }
18681                        return;
18682                    }
18683                }
18684
18685                if (existing != null) {
18686                    if (DEBUG_PREFERRED) {
18687                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18688                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18689                    }
18690                    for (int i = 0; i < existing.size(); i++) {
18691                        PreferredActivity pa = existing.get(i);
18692                        if (DEBUG_PREFERRED) {
18693                            Slog.i(TAG, "Removing existing preferred activity "
18694                                    + pa.mPref.mComponent + ":");
18695                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18696                        }
18697                        pir.removeFilter(pa);
18698                    }
18699                }
18700            }
18701            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18702                    "Replacing preferred");
18703        }
18704    }
18705
18706    @Override
18707    public void clearPackagePreferredActivities(String packageName) {
18708        final int uid = Binder.getCallingUid();
18709        // writer
18710        synchronized (mPackages) {
18711            PackageParser.Package pkg = mPackages.get(packageName);
18712            if (pkg == null || pkg.applicationInfo.uid != uid) {
18713                if (mContext.checkCallingOrSelfPermission(
18714                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18715                        != PackageManager.PERMISSION_GRANTED) {
18716                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18717                            < Build.VERSION_CODES.FROYO) {
18718                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18719                                + Binder.getCallingUid());
18720                        return;
18721                    }
18722                    mContext.enforceCallingOrSelfPermission(
18723                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18724                }
18725            }
18726
18727            int user = UserHandle.getCallingUserId();
18728            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18729                scheduleWritePackageRestrictionsLocked(user);
18730            }
18731        }
18732    }
18733
18734    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18735    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18736        ArrayList<PreferredActivity> removed = null;
18737        boolean changed = false;
18738        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18739            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18740            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18741            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18742                continue;
18743            }
18744            Iterator<PreferredActivity> it = pir.filterIterator();
18745            while (it.hasNext()) {
18746                PreferredActivity pa = it.next();
18747                // Mark entry for removal only if it matches the package name
18748                // and the entry is of type "always".
18749                if (packageName == null ||
18750                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18751                                && pa.mPref.mAlways)) {
18752                    if (removed == null) {
18753                        removed = new ArrayList<PreferredActivity>();
18754                    }
18755                    removed.add(pa);
18756                }
18757            }
18758            if (removed != null) {
18759                for (int j=0; j<removed.size(); j++) {
18760                    PreferredActivity pa = removed.get(j);
18761                    pir.removeFilter(pa);
18762                }
18763                changed = true;
18764            }
18765        }
18766        if (changed) {
18767            postPreferredActivityChangedBroadcast(userId);
18768        }
18769        return changed;
18770    }
18771
18772    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18773    private void clearIntentFilterVerificationsLPw(int userId) {
18774        final int packageCount = mPackages.size();
18775        for (int i = 0; i < packageCount; i++) {
18776            PackageParser.Package pkg = mPackages.valueAt(i);
18777            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18778        }
18779    }
18780
18781    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18782    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18783        if (userId == UserHandle.USER_ALL) {
18784            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18785                    sUserManager.getUserIds())) {
18786                for (int oneUserId : sUserManager.getUserIds()) {
18787                    scheduleWritePackageRestrictionsLocked(oneUserId);
18788                }
18789            }
18790        } else {
18791            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18792                scheduleWritePackageRestrictionsLocked(userId);
18793            }
18794        }
18795    }
18796
18797    void clearDefaultBrowserIfNeeded(String packageName) {
18798        for (int oneUserId : sUserManager.getUserIds()) {
18799            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18800            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18801            if (packageName.equals(defaultBrowserPackageName)) {
18802                setDefaultBrowserPackageName(null, oneUserId);
18803            }
18804        }
18805    }
18806
18807    @Override
18808    public void resetApplicationPreferences(int userId) {
18809        mContext.enforceCallingOrSelfPermission(
18810                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18811        final long identity = Binder.clearCallingIdentity();
18812        // writer
18813        try {
18814            synchronized (mPackages) {
18815                clearPackagePreferredActivitiesLPw(null, userId);
18816                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18817                // TODO: We have to reset the default SMS and Phone. This requires
18818                // significant refactoring to keep all default apps in the package
18819                // manager (cleaner but more work) or have the services provide
18820                // callbacks to the package manager to request a default app reset.
18821                applyFactoryDefaultBrowserLPw(userId);
18822                clearIntentFilterVerificationsLPw(userId);
18823                primeDomainVerificationsLPw(userId);
18824                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18825                scheduleWritePackageRestrictionsLocked(userId);
18826            }
18827            resetNetworkPolicies(userId);
18828        } finally {
18829            Binder.restoreCallingIdentity(identity);
18830        }
18831    }
18832
18833    @Override
18834    public int getPreferredActivities(List<IntentFilter> outFilters,
18835            List<ComponentName> outActivities, String packageName) {
18836
18837        int num = 0;
18838        final int userId = UserHandle.getCallingUserId();
18839        // reader
18840        synchronized (mPackages) {
18841            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18842            if (pir != null) {
18843                final Iterator<PreferredActivity> it = pir.filterIterator();
18844                while (it.hasNext()) {
18845                    final PreferredActivity pa = it.next();
18846                    if (packageName == null
18847                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18848                                    && pa.mPref.mAlways)) {
18849                        if (outFilters != null) {
18850                            outFilters.add(new IntentFilter(pa));
18851                        }
18852                        if (outActivities != null) {
18853                            outActivities.add(pa.mPref.mComponent);
18854                        }
18855                    }
18856                }
18857            }
18858        }
18859
18860        return num;
18861    }
18862
18863    @Override
18864    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18865            int userId) {
18866        int callingUid = Binder.getCallingUid();
18867        if (callingUid != Process.SYSTEM_UID) {
18868            throw new SecurityException(
18869                    "addPersistentPreferredActivity can only be run by the system");
18870        }
18871        if (filter.countActions() == 0) {
18872            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18873            return;
18874        }
18875        synchronized (mPackages) {
18876            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18877                    ":");
18878            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18879            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18880                    new PersistentPreferredActivity(filter, activity));
18881            scheduleWritePackageRestrictionsLocked(userId);
18882            postPreferredActivityChangedBroadcast(userId);
18883        }
18884    }
18885
18886    @Override
18887    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18888        int callingUid = Binder.getCallingUid();
18889        if (callingUid != Process.SYSTEM_UID) {
18890            throw new SecurityException(
18891                    "clearPackagePersistentPreferredActivities can only be run by the system");
18892        }
18893        ArrayList<PersistentPreferredActivity> removed = null;
18894        boolean changed = false;
18895        synchronized (mPackages) {
18896            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18897                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18898                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18899                        .valueAt(i);
18900                if (userId != thisUserId) {
18901                    continue;
18902                }
18903                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18904                while (it.hasNext()) {
18905                    PersistentPreferredActivity ppa = it.next();
18906                    // Mark entry for removal only if it matches the package name.
18907                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18908                        if (removed == null) {
18909                            removed = new ArrayList<PersistentPreferredActivity>();
18910                        }
18911                        removed.add(ppa);
18912                    }
18913                }
18914                if (removed != null) {
18915                    for (int j=0; j<removed.size(); j++) {
18916                        PersistentPreferredActivity ppa = removed.get(j);
18917                        ppir.removeFilter(ppa);
18918                    }
18919                    changed = true;
18920                }
18921            }
18922
18923            if (changed) {
18924                scheduleWritePackageRestrictionsLocked(userId);
18925                postPreferredActivityChangedBroadcast(userId);
18926            }
18927        }
18928    }
18929
18930    /**
18931     * Common machinery for picking apart a restored XML blob and passing
18932     * it to a caller-supplied functor to be applied to the running system.
18933     */
18934    private void restoreFromXml(XmlPullParser parser, int userId,
18935            String expectedStartTag, BlobXmlRestorer functor)
18936            throws IOException, XmlPullParserException {
18937        int type;
18938        while ((type = parser.next()) != XmlPullParser.START_TAG
18939                && type != XmlPullParser.END_DOCUMENT) {
18940        }
18941        if (type != XmlPullParser.START_TAG) {
18942            // oops didn't find a start tag?!
18943            if (DEBUG_BACKUP) {
18944                Slog.e(TAG, "Didn't find start tag during restore");
18945            }
18946            return;
18947        }
18948Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18949        // this is supposed to be TAG_PREFERRED_BACKUP
18950        if (!expectedStartTag.equals(parser.getName())) {
18951            if (DEBUG_BACKUP) {
18952                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18953            }
18954            return;
18955        }
18956
18957        // skip interfering stuff, then we're aligned with the backing implementation
18958        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18959Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18960        functor.apply(parser, userId);
18961    }
18962
18963    private interface BlobXmlRestorer {
18964        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18965    }
18966
18967    /**
18968     * Non-Binder method, support for the backup/restore mechanism: write the
18969     * full set of preferred activities in its canonical XML format.  Returns the
18970     * XML output as a byte array, or null if there is none.
18971     */
18972    @Override
18973    public byte[] getPreferredActivityBackup(int userId) {
18974        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18975            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18976        }
18977
18978        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18979        try {
18980            final XmlSerializer serializer = new FastXmlSerializer();
18981            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18982            serializer.startDocument(null, true);
18983            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18984
18985            synchronized (mPackages) {
18986                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18987            }
18988
18989            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18990            serializer.endDocument();
18991            serializer.flush();
18992        } catch (Exception e) {
18993            if (DEBUG_BACKUP) {
18994                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18995            }
18996            return null;
18997        }
18998
18999        return dataStream.toByteArray();
19000    }
19001
19002    @Override
19003    public void restorePreferredActivities(byte[] backup, int userId) {
19004        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19005            throw new SecurityException("Only the system may call restorePreferredActivities()");
19006        }
19007
19008        try {
19009            final XmlPullParser parser = Xml.newPullParser();
19010            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19011            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19012                    new BlobXmlRestorer() {
19013                        @Override
19014                        public void apply(XmlPullParser parser, int userId)
19015                                throws XmlPullParserException, IOException {
19016                            synchronized (mPackages) {
19017                                mSettings.readPreferredActivitiesLPw(parser, userId);
19018                            }
19019                        }
19020                    } );
19021        } catch (Exception e) {
19022            if (DEBUG_BACKUP) {
19023                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19024            }
19025        }
19026    }
19027
19028    /**
19029     * Non-Binder method, support for the backup/restore mechanism: write the
19030     * default browser (etc) settings in its canonical XML format.  Returns the default
19031     * browser XML representation as a byte array, or null if there is none.
19032     */
19033    @Override
19034    public byte[] getDefaultAppsBackup(int userId) {
19035        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19036            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19037        }
19038
19039        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19040        try {
19041            final XmlSerializer serializer = new FastXmlSerializer();
19042            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19043            serializer.startDocument(null, true);
19044            serializer.startTag(null, TAG_DEFAULT_APPS);
19045
19046            synchronized (mPackages) {
19047                mSettings.writeDefaultAppsLPr(serializer, userId);
19048            }
19049
19050            serializer.endTag(null, TAG_DEFAULT_APPS);
19051            serializer.endDocument();
19052            serializer.flush();
19053        } catch (Exception e) {
19054            if (DEBUG_BACKUP) {
19055                Slog.e(TAG, "Unable to write default apps for backup", e);
19056            }
19057            return null;
19058        }
19059
19060        return dataStream.toByteArray();
19061    }
19062
19063    @Override
19064    public void restoreDefaultApps(byte[] backup, int userId) {
19065        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19066            throw new SecurityException("Only the system may call restoreDefaultApps()");
19067        }
19068
19069        try {
19070            final XmlPullParser parser = Xml.newPullParser();
19071            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19072            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19073                    new BlobXmlRestorer() {
19074                        @Override
19075                        public void apply(XmlPullParser parser, int userId)
19076                                throws XmlPullParserException, IOException {
19077                            synchronized (mPackages) {
19078                                mSettings.readDefaultAppsLPw(parser, userId);
19079                            }
19080                        }
19081                    } );
19082        } catch (Exception e) {
19083            if (DEBUG_BACKUP) {
19084                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19085            }
19086        }
19087    }
19088
19089    @Override
19090    public byte[] getIntentFilterVerificationBackup(int userId) {
19091        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19092            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19093        }
19094
19095        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19096        try {
19097            final XmlSerializer serializer = new FastXmlSerializer();
19098            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19099            serializer.startDocument(null, true);
19100            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19101
19102            synchronized (mPackages) {
19103                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19104            }
19105
19106            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19107            serializer.endDocument();
19108            serializer.flush();
19109        } catch (Exception e) {
19110            if (DEBUG_BACKUP) {
19111                Slog.e(TAG, "Unable to write default apps for backup", e);
19112            }
19113            return null;
19114        }
19115
19116        return dataStream.toByteArray();
19117    }
19118
19119    @Override
19120    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19121        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19122            throw new SecurityException("Only the system may call restorePreferredActivities()");
19123        }
19124
19125        try {
19126            final XmlPullParser parser = Xml.newPullParser();
19127            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19128            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19129                    new BlobXmlRestorer() {
19130                        @Override
19131                        public void apply(XmlPullParser parser, int userId)
19132                                throws XmlPullParserException, IOException {
19133                            synchronized (mPackages) {
19134                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19135                                mSettings.writeLPr();
19136                            }
19137                        }
19138                    } );
19139        } catch (Exception e) {
19140            if (DEBUG_BACKUP) {
19141                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19142            }
19143        }
19144    }
19145
19146    @Override
19147    public byte[] getPermissionGrantBackup(int userId) {
19148        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19149            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19150        }
19151
19152        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19153        try {
19154            final XmlSerializer serializer = new FastXmlSerializer();
19155            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19156            serializer.startDocument(null, true);
19157            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19158
19159            synchronized (mPackages) {
19160                serializeRuntimePermissionGrantsLPr(serializer, userId);
19161            }
19162
19163            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19164            serializer.endDocument();
19165            serializer.flush();
19166        } catch (Exception e) {
19167            if (DEBUG_BACKUP) {
19168                Slog.e(TAG, "Unable to write default apps for backup", e);
19169            }
19170            return null;
19171        }
19172
19173        return dataStream.toByteArray();
19174    }
19175
19176    @Override
19177    public void restorePermissionGrants(byte[] backup, int userId) {
19178        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19179            throw new SecurityException("Only the system may call restorePermissionGrants()");
19180        }
19181
19182        try {
19183            final XmlPullParser parser = Xml.newPullParser();
19184            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19185            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19186                    new BlobXmlRestorer() {
19187                        @Override
19188                        public void apply(XmlPullParser parser, int userId)
19189                                throws XmlPullParserException, IOException {
19190                            synchronized (mPackages) {
19191                                processRestoredPermissionGrantsLPr(parser, userId);
19192                            }
19193                        }
19194                    } );
19195        } catch (Exception e) {
19196            if (DEBUG_BACKUP) {
19197                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19198            }
19199        }
19200    }
19201
19202    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19203            throws IOException {
19204        serializer.startTag(null, TAG_ALL_GRANTS);
19205
19206        final int N = mSettings.mPackages.size();
19207        for (int i = 0; i < N; i++) {
19208            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19209            boolean pkgGrantsKnown = false;
19210
19211            PermissionsState packagePerms = ps.getPermissionsState();
19212
19213            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19214                final int grantFlags = state.getFlags();
19215                // only look at grants that are not system/policy fixed
19216                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19217                    final boolean isGranted = state.isGranted();
19218                    // And only back up the user-twiddled state bits
19219                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19220                        final String packageName = mSettings.mPackages.keyAt(i);
19221                        if (!pkgGrantsKnown) {
19222                            serializer.startTag(null, TAG_GRANT);
19223                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19224                            pkgGrantsKnown = true;
19225                        }
19226
19227                        final boolean userSet =
19228                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19229                        final boolean userFixed =
19230                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19231                        final boolean revoke =
19232                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19233
19234                        serializer.startTag(null, TAG_PERMISSION);
19235                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19236                        if (isGranted) {
19237                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19238                        }
19239                        if (userSet) {
19240                            serializer.attribute(null, ATTR_USER_SET, "true");
19241                        }
19242                        if (userFixed) {
19243                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19244                        }
19245                        if (revoke) {
19246                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19247                        }
19248                        serializer.endTag(null, TAG_PERMISSION);
19249                    }
19250                }
19251            }
19252
19253            if (pkgGrantsKnown) {
19254                serializer.endTag(null, TAG_GRANT);
19255            }
19256        }
19257
19258        serializer.endTag(null, TAG_ALL_GRANTS);
19259    }
19260
19261    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19262            throws XmlPullParserException, IOException {
19263        String pkgName = null;
19264        int outerDepth = parser.getDepth();
19265        int type;
19266        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19267                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19268            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19269                continue;
19270            }
19271
19272            final String tagName = parser.getName();
19273            if (tagName.equals(TAG_GRANT)) {
19274                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19275                if (DEBUG_BACKUP) {
19276                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19277                }
19278            } else if (tagName.equals(TAG_PERMISSION)) {
19279
19280                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19281                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19282
19283                int newFlagSet = 0;
19284                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19285                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19286                }
19287                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19288                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19289                }
19290                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19291                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19292                }
19293                if (DEBUG_BACKUP) {
19294                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19295                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19296                }
19297                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19298                if (ps != null) {
19299                    // Already installed so we apply the grant immediately
19300                    if (DEBUG_BACKUP) {
19301                        Slog.v(TAG, "        + already installed; applying");
19302                    }
19303                    PermissionsState perms = ps.getPermissionsState();
19304                    BasePermission bp = mSettings.mPermissions.get(permName);
19305                    if (bp != null) {
19306                        if (isGranted) {
19307                            perms.grantRuntimePermission(bp, userId);
19308                        }
19309                        if (newFlagSet != 0) {
19310                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19311                        }
19312                    }
19313                } else {
19314                    // Need to wait for post-restore install to apply the grant
19315                    if (DEBUG_BACKUP) {
19316                        Slog.v(TAG, "        - not yet installed; saving for later");
19317                    }
19318                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19319                            isGranted, newFlagSet, userId);
19320                }
19321            } else {
19322                PackageManagerService.reportSettingsProblem(Log.WARN,
19323                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19324                XmlUtils.skipCurrentTag(parser);
19325            }
19326        }
19327
19328        scheduleWriteSettingsLocked();
19329        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19330    }
19331
19332    @Override
19333    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19334            int sourceUserId, int targetUserId, int flags) {
19335        mContext.enforceCallingOrSelfPermission(
19336                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19337        int callingUid = Binder.getCallingUid();
19338        enforceOwnerRights(ownerPackage, callingUid);
19339        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19340        if (intentFilter.countActions() == 0) {
19341            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19342            return;
19343        }
19344        synchronized (mPackages) {
19345            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19346                    ownerPackage, targetUserId, flags);
19347            CrossProfileIntentResolver resolver =
19348                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19349            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19350            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19351            if (existing != null) {
19352                int size = existing.size();
19353                for (int i = 0; i < size; i++) {
19354                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19355                        return;
19356                    }
19357                }
19358            }
19359            resolver.addFilter(newFilter);
19360            scheduleWritePackageRestrictionsLocked(sourceUserId);
19361        }
19362    }
19363
19364    @Override
19365    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19366        mContext.enforceCallingOrSelfPermission(
19367                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19368        int callingUid = Binder.getCallingUid();
19369        enforceOwnerRights(ownerPackage, callingUid);
19370        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19371        synchronized (mPackages) {
19372            CrossProfileIntentResolver resolver =
19373                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19374            ArraySet<CrossProfileIntentFilter> set =
19375                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19376            for (CrossProfileIntentFilter filter : set) {
19377                if (filter.getOwnerPackage().equals(ownerPackage)) {
19378                    resolver.removeFilter(filter);
19379                }
19380            }
19381            scheduleWritePackageRestrictionsLocked(sourceUserId);
19382        }
19383    }
19384
19385    // Enforcing that callingUid is owning pkg on userId
19386    private void enforceOwnerRights(String pkg, int callingUid) {
19387        // The system owns everything.
19388        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19389            return;
19390        }
19391        int callingUserId = UserHandle.getUserId(callingUid);
19392        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19393        if (pi == null) {
19394            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19395                    + callingUserId);
19396        }
19397        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19398            throw new SecurityException("Calling uid " + callingUid
19399                    + " does not own package " + pkg);
19400        }
19401    }
19402
19403    @Override
19404    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19405        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19406    }
19407
19408    private Intent getHomeIntent() {
19409        Intent intent = new Intent(Intent.ACTION_MAIN);
19410        intent.addCategory(Intent.CATEGORY_HOME);
19411        intent.addCategory(Intent.CATEGORY_DEFAULT);
19412        return intent;
19413    }
19414
19415    private IntentFilter getHomeFilter() {
19416        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19417        filter.addCategory(Intent.CATEGORY_HOME);
19418        filter.addCategory(Intent.CATEGORY_DEFAULT);
19419        return filter;
19420    }
19421
19422    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19423            int userId) {
19424        Intent intent  = getHomeIntent();
19425        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19426                PackageManager.GET_META_DATA, userId);
19427        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19428                true, false, false, userId);
19429
19430        allHomeCandidates.clear();
19431        if (list != null) {
19432            for (ResolveInfo ri : list) {
19433                allHomeCandidates.add(ri);
19434            }
19435        }
19436        return (preferred == null || preferred.activityInfo == null)
19437                ? null
19438                : new ComponentName(preferred.activityInfo.packageName,
19439                        preferred.activityInfo.name);
19440    }
19441
19442    @Override
19443    public void setHomeActivity(ComponentName comp, int userId) {
19444        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19445        getHomeActivitiesAsUser(homeActivities, userId);
19446
19447        boolean found = false;
19448
19449        final int size = homeActivities.size();
19450        final ComponentName[] set = new ComponentName[size];
19451        for (int i = 0; i < size; i++) {
19452            final ResolveInfo candidate = homeActivities.get(i);
19453            final ActivityInfo info = candidate.activityInfo;
19454            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19455            set[i] = activityName;
19456            if (!found && activityName.equals(comp)) {
19457                found = true;
19458            }
19459        }
19460        if (!found) {
19461            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19462                    + userId);
19463        }
19464        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19465                set, comp, userId);
19466    }
19467
19468    private @Nullable String getSetupWizardPackageName() {
19469        final Intent intent = new Intent(Intent.ACTION_MAIN);
19470        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19471
19472        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19473                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19474                        | MATCH_DISABLED_COMPONENTS,
19475                UserHandle.myUserId());
19476        if (matches.size() == 1) {
19477            return matches.get(0).getComponentInfo().packageName;
19478        } else {
19479            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19480                    + ": matches=" + matches);
19481            return null;
19482        }
19483    }
19484
19485    private @Nullable String getStorageManagerPackageName() {
19486        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19487
19488        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19489                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19490                        | MATCH_DISABLED_COMPONENTS,
19491                UserHandle.myUserId());
19492        if (matches.size() == 1) {
19493            return matches.get(0).getComponentInfo().packageName;
19494        } else {
19495            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19496                    + matches.size() + ": matches=" + matches);
19497            return null;
19498        }
19499    }
19500
19501    @Override
19502    public void setApplicationEnabledSetting(String appPackageName,
19503            int newState, int flags, int userId, String callingPackage) {
19504        if (!sUserManager.exists(userId)) return;
19505        if (callingPackage == null) {
19506            callingPackage = Integer.toString(Binder.getCallingUid());
19507        }
19508        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19509    }
19510
19511    @Override
19512    public void setComponentEnabledSetting(ComponentName componentName,
19513            int newState, int flags, int userId) {
19514        if (!sUserManager.exists(userId)) return;
19515        setEnabledSetting(componentName.getPackageName(),
19516                componentName.getClassName(), newState, flags, userId, null);
19517    }
19518
19519    private void setEnabledSetting(final String packageName, String className, int newState,
19520            final int flags, int userId, String callingPackage) {
19521        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19522              || newState == COMPONENT_ENABLED_STATE_ENABLED
19523              || newState == COMPONENT_ENABLED_STATE_DISABLED
19524              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19525              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19526            throw new IllegalArgumentException("Invalid new component state: "
19527                    + newState);
19528        }
19529        PackageSetting pkgSetting;
19530        final int uid = Binder.getCallingUid();
19531        final int permission;
19532        if (uid == Process.SYSTEM_UID) {
19533            permission = PackageManager.PERMISSION_GRANTED;
19534        } else {
19535            permission = mContext.checkCallingOrSelfPermission(
19536                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19537        }
19538        enforceCrossUserPermission(uid, userId,
19539                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19540        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19541        boolean sendNow = false;
19542        boolean isApp = (className == null);
19543        String componentName = isApp ? packageName : className;
19544        int packageUid = -1;
19545        ArrayList<String> components;
19546
19547        // writer
19548        synchronized (mPackages) {
19549            pkgSetting = mSettings.mPackages.get(packageName);
19550            if (pkgSetting == null) {
19551                if (className == null) {
19552                    throw new IllegalArgumentException("Unknown package: " + packageName);
19553                }
19554                throw new IllegalArgumentException(
19555                        "Unknown component: " + packageName + "/" + className);
19556            }
19557        }
19558
19559        // Limit who can change which apps
19560        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19561            // Don't allow apps that don't have permission to modify other apps
19562            if (!allowedByPermission) {
19563                throw new SecurityException(
19564                        "Permission Denial: attempt to change component state from pid="
19565                        + Binder.getCallingPid()
19566                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19567            }
19568            // Don't allow changing protected packages.
19569            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19570                throw new SecurityException("Cannot disable a protected package: " + packageName);
19571            }
19572        }
19573
19574        synchronized (mPackages) {
19575            if (uid == Process.SHELL_UID
19576                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19577                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19578                // unless it is a test package.
19579                int oldState = pkgSetting.getEnabled(userId);
19580                if (className == null
19581                    &&
19582                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19583                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19584                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19585                    &&
19586                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19587                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19588                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19589                    // ok
19590                } else {
19591                    throw new SecurityException(
19592                            "Shell cannot change component state for " + packageName + "/"
19593                            + className + " to " + newState);
19594                }
19595            }
19596            if (className == null) {
19597                // We're dealing with an application/package level state change
19598                if (pkgSetting.getEnabled(userId) == newState) {
19599                    // Nothing to do
19600                    return;
19601                }
19602                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19603                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19604                    // Don't care about who enables an app.
19605                    callingPackage = null;
19606                }
19607                pkgSetting.setEnabled(newState, userId, callingPackage);
19608                // pkgSetting.pkg.mSetEnabled = newState;
19609            } else {
19610                // We're dealing with a component level state change
19611                // First, verify that this is a valid class name.
19612                PackageParser.Package pkg = pkgSetting.pkg;
19613                if (pkg == null || !pkg.hasComponentClassName(className)) {
19614                    if (pkg != null &&
19615                            pkg.applicationInfo.targetSdkVersion >=
19616                                    Build.VERSION_CODES.JELLY_BEAN) {
19617                        throw new IllegalArgumentException("Component class " + className
19618                                + " does not exist in " + packageName);
19619                    } else {
19620                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19621                                + className + " does not exist in " + packageName);
19622                    }
19623                }
19624                switch (newState) {
19625                case COMPONENT_ENABLED_STATE_ENABLED:
19626                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19627                        return;
19628                    }
19629                    break;
19630                case COMPONENT_ENABLED_STATE_DISABLED:
19631                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19632                        return;
19633                    }
19634                    break;
19635                case COMPONENT_ENABLED_STATE_DEFAULT:
19636                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19637                        return;
19638                    }
19639                    break;
19640                default:
19641                    Slog.e(TAG, "Invalid new component state: " + newState);
19642                    return;
19643                }
19644            }
19645            scheduleWritePackageRestrictionsLocked(userId);
19646            components = mPendingBroadcasts.get(userId, packageName);
19647            final boolean newPackage = components == null;
19648            if (newPackage) {
19649                components = new ArrayList<String>();
19650            }
19651            if (!components.contains(componentName)) {
19652                components.add(componentName);
19653            }
19654            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19655                sendNow = true;
19656                // Purge entry from pending broadcast list if another one exists already
19657                // since we are sending one right away.
19658                mPendingBroadcasts.remove(userId, packageName);
19659            } else {
19660                if (newPackage) {
19661                    mPendingBroadcasts.put(userId, packageName, components);
19662                }
19663                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19664                    // Schedule a message
19665                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19666                }
19667            }
19668        }
19669
19670        long callingId = Binder.clearCallingIdentity();
19671        try {
19672            if (sendNow) {
19673                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19674                sendPackageChangedBroadcast(packageName,
19675                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19676            }
19677        } finally {
19678            Binder.restoreCallingIdentity(callingId);
19679        }
19680    }
19681
19682    @Override
19683    public void flushPackageRestrictionsAsUser(int userId) {
19684        if (!sUserManager.exists(userId)) {
19685            return;
19686        }
19687        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19688                false /* checkShell */, "flushPackageRestrictions");
19689        synchronized (mPackages) {
19690            mSettings.writePackageRestrictionsLPr(userId);
19691            mDirtyUsers.remove(userId);
19692            if (mDirtyUsers.isEmpty()) {
19693                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19694            }
19695        }
19696    }
19697
19698    private void sendPackageChangedBroadcast(String packageName,
19699            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19700        if (DEBUG_INSTALL)
19701            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19702                    + componentNames);
19703        Bundle extras = new Bundle(4);
19704        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19705        String nameList[] = new String[componentNames.size()];
19706        componentNames.toArray(nameList);
19707        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19708        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19709        extras.putInt(Intent.EXTRA_UID, packageUid);
19710        // If this is not reporting a change of the overall package, then only send it
19711        // to registered receivers.  We don't want to launch a swath of apps for every
19712        // little component state change.
19713        final int flags = !componentNames.contains(packageName)
19714                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19715        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19716                new int[] {UserHandle.getUserId(packageUid)});
19717    }
19718
19719    @Override
19720    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19721        if (!sUserManager.exists(userId)) return;
19722        final int uid = Binder.getCallingUid();
19723        final int permission = mContext.checkCallingOrSelfPermission(
19724                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19725        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19726        enforceCrossUserPermission(uid, userId,
19727                true /* requireFullPermission */, true /* checkShell */, "stop package");
19728        // writer
19729        synchronized (mPackages) {
19730            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19731                    allowedByPermission, uid, userId)) {
19732                scheduleWritePackageRestrictionsLocked(userId);
19733            }
19734        }
19735    }
19736
19737    @Override
19738    public String getInstallerPackageName(String packageName) {
19739        // reader
19740        synchronized (mPackages) {
19741            return mSettings.getInstallerPackageNameLPr(packageName);
19742        }
19743    }
19744
19745    public boolean isOrphaned(String packageName) {
19746        // reader
19747        synchronized (mPackages) {
19748            return mSettings.isOrphaned(packageName);
19749        }
19750    }
19751
19752    @Override
19753    public int getApplicationEnabledSetting(String packageName, int userId) {
19754        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19755        int uid = Binder.getCallingUid();
19756        enforceCrossUserPermission(uid, userId,
19757                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19758        // reader
19759        synchronized (mPackages) {
19760            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19761        }
19762    }
19763
19764    @Override
19765    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19766        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19767        int uid = Binder.getCallingUid();
19768        enforceCrossUserPermission(uid, userId,
19769                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19770        // reader
19771        synchronized (mPackages) {
19772            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19773        }
19774    }
19775
19776    @Override
19777    public void enterSafeMode() {
19778        enforceSystemOrRoot("Only the system can request entering safe mode");
19779
19780        if (!mSystemReady) {
19781            mSafeMode = true;
19782        }
19783    }
19784
19785    @Override
19786    public void systemReady() {
19787        mSystemReady = true;
19788
19789        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19790        // disabled after already being started.
19791        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19792                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19793
19794        // Read the compatibilty setting when the system is ready.
19795        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19796                mContext.getContentResolver(),
19797                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19798        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19799        if (DEBUG_SETTINGS) {
19800            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19801        }
19802
19803        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19804
19805        synchronized (mPackages) {
19806            // Verify that all of the preferred activity components actually
19807            // exist.  It is possible for applications to be updated and at
19808            // that point remove a previously declared activity component that
19809            // had been set as a preferred activity.  We try to clean this up
19810            // the next time we encounter that preferred activity, but it is
19811            // possible for the user flow to never be able to return to that
19812            // situation so here we do a sanity check to make sure we haven't
19813            // left any junk around.
19814            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19815            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19816                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19817                removed.clear();
19818                for (PreferredActivity pa : pir.filterSet()) {
19819                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19820                        removed.add(pa);
19821                    }
19822                }
19823                if (removed.size() > 0) {
19824                    for (int r=0; r<removed.size(); r++) {
19825                        PreferredActivity pa = removed.get(r);
19826                        Slog.w(TAG, "Removing dangling preferred activity: "
19827                                + pa.mPref.mComponent);
19828                        pir.removeFilter(pa);
19829                    }
19830                    mSettings.writePackageRestrictionsLPr(
19831                            mSettings.mPreferredActivities.keyAt(i));
19832                }
19833            }
19834
19835            for (int userId : UserManagerService.getInstance().getUserIds()) {
19836                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19837                    grantPermissionsUserIds = ArrayUtils.appendInt(
19838                            grantPermissionsUserIds, userId);
19839                }
19840            }
19841        }
19842        sUserManager.systemReady();
19843
19844        // If we upgraded grant all default permissions before kicking off.
19845        for (int userId : grantPermissionsUserIds) {
19846            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19847        }
19848
19849        // If we did not grant default permissions, we preload from this the
19850        // default permission exceptions lazily to ensure we don't hit the
19851        // disk on a new user creation.
19852        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19853            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19854        }
19855
19856        // Kick off any messages waiting for system ready
19857        if (mPostSystemReadyMessages != null) {
19858            for (Message msg : mPostSystemReadyMessages) {
19859                msg.sendToTarget();
19860            }
19861            mPostSystemReadyMessages = null;
19862        }
19863
19864        // Watch for external volumes that come and go over time
19865        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19866        storage.registerListener(mStorageListener);
19867
19868        mInstallerService.systemReady();
19869        mPackageDexOptimizer.systemReady();
19870
19871        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19872                StorageManagerInternal.class);
19873        StorageManagerInternal.addExternalStoragePolicy(
19874                new StorageManagerInternal.ExternalStorageMountPolicy() {
19875            @Override
19876            public int getMountMode(int uid, String packageName) {
19877                if (Process.isIsolated(uid)) {
19878                    return Zygote.MOUNT_EXTERNAL_NONE;
19879                }
19880                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19881                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19882                }
19883                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19884                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19885                }
19886                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19887                    return Zygote.MOUNT_EXTERNAL_READ;
19888                }
19889                return Zygote.MOUNT_EXTERNAL_WRITE;
19890            }
19891
19892            @Override
19893            public boolean hasExternalStorage(int uid, String packageName) {
19894                return true;
19895            }
19896        });
19897
19898        // Now that we're mostly running, clean up stale users and apps
19899        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19900        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19901    }
19902
19903    @Override
19904    public boolean isSafeMode() {
19905        return mSafeMode;
19906    }
19907
19908    @Override
19909    public boolean hasSystemUidErrors() {
19910        return mHasSystemUidErrors;
19911    }
19912
19913    static String arrayToString(int[] array) {
19914        StringBuffer buf = new StringBuffer(128);
19915        buf.append('[');
19916        if (array != null) {
19917            for (int i=0; i<array.length; i++) {
19918                if (i > 0) buf.append(", ");
19919                buf.append(array[i]);
19920            }
19921        }
19922        buf.append(']');
19923        return buf.toString();
19924    }
19925
19926    static class DumpState {
19927        public static final int DUMP_LIBS = 1 << 0;
19928        public static final int DUMP_FEATURES = 1 << 1;
19929        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19930        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19931        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19932        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19933        public static final int DUMP_PERMISSIONS = 1 << 6;
19934        public static final int DUMP_PACKAGES = 1 << 7;
19935        public static final int DUMP_SHARED_USERS = 1 << 8;
19936        public static final int DUMP_MESSAGES = 1 << 9;
19937        public static final int DUMP_PROVIDERS = 1 << 10;
19938        public static final int DUMP_VERIFIERS = 1 << 11;
19939        public static final int DUMP_PREFERRED = 1 << 12;
19940        public static final int DUMP_PREFERRED_XML = 1 << 13;
19941        public static final int DUMP_KEYSETS = 1 << 14;
19942        public static final int DUMP_VERSION = 1 << 15;
19943        public static final int DUMP_INSTALLS = 1 << 16;
19944        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19945        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19946        public static final int DUMP_FROZEN = 1 << 19;
19947        public static final int DUMP_DEXOPT = 1 << 20;
19948        public static final int DUMP_COMPILER_STATS = 1 << 21;
19949
19950        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19951
19952        private int mTypes;
19953
19954        private int mOptions;
19955
19956        private boolean mTitlePrinted;
19957
19958        private SharedUserSetting mSharedUser;
19959
19960        public boolean isDumping(int type) {
19961            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19962                return true;
19963            }
19964
19965            return (mTypes & type) != 0;
19966        }
19967
19968        public void setDump(int type) {
19969            mTypes |= type;
19970        }
19971
19972        public boolean isOptionEnabled(int option) {
19973            return (mOptions & option) != 0;
19974        }
19975
19976        public void setOptionEnabled(int option) {
19977            mOptions |= option;
19978        }
19979
19980        public boolean onTitlePrinted() {
19981            final boolean printed = mTitlePrinted;
19982            mTitlePrinted = true;
19983            return printed;
19984        }
19985
19986        public boolean getTitlePrinted() {
19987            return mTitlePrinted;
19988        }
19989
19990        public void setTitlePrinted(boolean enabled) {
19991            mTitlePrinted = enabled;
19992        }
19993
19994        public SharedUserSetting getSharedUser() {
19995            return mSharedUser;
19996        }
19997
19998        public void setSharedUser(SharedUserSetting user) {
19999            mSharedUser = user;
20000        }
20001    }
20002
20003    @Override
20004    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20005            FileDescriptor err, String[] args, ShellCallback callback,
20006            ResultReceiver resultReceiver) {
20007        (new PackageManagerShellCommand(this)).exec(
20008                this, in, out, err, args, callback, resultReceiver);
20009    }
20010
20011    @Override
20012    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20013        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20014                != PackageManager.PERMISSION_GRANTED) {
20015            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20016                    + Binder.getCallingPid()
20017                    + ", uid=" + Binder.getCallingUid()
20018                    + " without permission "
20019                    + android.Manifest.permission.DUMP);
20020            return;
20021        }
20022
20023        DumpState dumpState = new DumpState();
20024        boolean fullPreferred = false;
20025        boolean checkin = false;
20026
20027        String packageName = null;
20028        ArraySet<String> permissionNames = null;
20029
20030        int opti = 0;
20031        while (opti < args.length) {
20032            String opt = args[opti];
20033            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20034                break;
20035            }
20036            opti++;
20037
20038            if ("-a".equals(opt)) {
20039                // Right now we only know how to print all.
20040            } else if ("-h".equals(opt)) {
20041                pw.println("Package manager dump options:");
20042                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20043                pw.println("    --checkin: dump for a checkin");
20044                pw.println("    -f: print details of intent filters");
20045                pw.println("    -h: print this help");
20046                pw.println("  cmd may be one of:");
20047                pw.println("    l[ibraries]: list known shared libraries");
20048                pw.println("    f[eatures]: list device features");
20049                pw.println("    k[eysets]: print known keysets");
20050                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20051                pw.println("    perm[issions]: dump permissions");
20052                pw.println("    permission [name ...]: dump declaration and use of given permission");
20053                pw.println("    pref[erred]: print preferred package settings");
20054                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20055                pw.println("    prov[iders]: dump content providers");
20056                pw.println("    p[ackages]: dump installed packages");
20057                pw.println("    s[hared-users]: dump shared user IDs");
20058                pw.println("    m[essages]: print collected runtime messages");
20059                pw.println("    v[erifiers]: print package verifier info");
20060                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20061                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20062                pw.println("    version: print database version info");
20063                pw.println("    write: write current settings now");
20064                pw.println("    installs: details about install sessions");
20065                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20066                pw.println("    dexopt: dump dexopt state");
20067                pw.println("    compiler-stats: dump compiler statistics");
20068                pw.println("    <package.name>: info about given package");
20069                return;
20070            } else if ("--checkin".equals(opt)) {
20071                checkin = true;
20072            } else if ("-f".equals(opt)) {
20073                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20074            } else {
20075                pw.println("Unknown argument: " + opt + "; use -h for help");
20076            }
20077        }
20078
20079        // Is the caller requesting to dump a particular piece of data?
20080        if (opti < args.length) {
20081            String cmd = args[opti];
20082            opti++;
20083            // Is this a package name?
20084            if ("android".equals(cmd) || cmd.contains(".")) {
20085                packageName = cmd;
20086                // When dumping a single package, we always dump all of its
20087                // filter information since the amount of data will be reasonable.
20088                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20089            } else if ("check-permission".equals(cmd)) {
20090                if (opti >= args.length) {
20091                    pw.println("Error: check-permission missing permission argument");
20092                    return;
20093                }
20094                String perm = args[opti];
20095                opti++;
20096                if (opti >= args.length) {
20097                    pw.println("Error: check-permission missing package argument");
20098                    return;
20099                }
20100
20101                String pkg = args[opti];
20102                opti++;
20103                int user = UserHandle.getUserId(Binder.getCallingUid());
20104                if (opti < args.length) {
20105                    try {
20106                        user = Integer.parseInt(args[opti]);
20107                    } catch (NumberFormatException e) {
20108                        pw.println("Error: check-permission user argument is not a number: "
20109                                + args[opti]);
20110                        return;
20111                    }
20112                }
20113
20114                // Normalize package name to handle renamed packages and static libs
20115                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20116
20117                pw.println(checkPermission(perm, pkg, user));
20118                return;
20119            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20120                dumpState.setDump(DumpState.DUMP_LIBS);
20121            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20122                dumpState.setDump(DumpState.DUMP_FEATURES);
20123            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20124                if (opti >= args.length) {
20125                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20126                            | DumpState.DUMP_SERVICE_RESOLVERS
20127                            | DumpState.DUMP_RECEIVER_RESOLVERS
20128                            | DumpState.DUMP_CONTENT_RESOLVERS);
20129                } else {
20130                    while (opti < args.length) {
20131                        String name = args[opti];
20132                        if ("a".equals(name) || "activity".equals(name)) {
20133                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20134                        } else if ("s".equals(name) || "service".equals(name)) {
20135                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20136                        } else if ("r".equals(name) || "receiver".equals(name)) {
20137                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20138                        } else if ("c".equals(name) || "content".equals(name)) {
20139                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20140                        } else {
20141                            pw.println("Error: unknown resolver table type: " + name);
20142                            return;
20143                        }
20144                        opti++;
20145                    }
20146                }
20147            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20148                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20149            } else if ("permission".equals(cmd)) {
20150                if (opti >= args.length) {
20151                    pw.println("Error: permission requires permission name");
20152                    return;
20153                }
20154                permissionNames = new ArraySet<>();
20155                while (opti < args.length) {
20156                    permissionNames.add(args[opti]);
20157                    opti++;
20158                }
20159                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20160                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20161            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20162                dumpState.setDump(DumpState.DUMP_PREFERRED);
20163            } else if ("preferred-xml".equals(cmd)) {
20164                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20165                if (opti < args.length && "--full".equals(args[opti])) {
20166                    fullPreferred = true;
20167                    opti++;
20168                }
20169            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20170                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20171            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20172                dumpState.setDump(DumpState.DUMP_PACKAGES);
20173            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20174                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20175            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20176                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20177            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20178                dumpState.setDump(DumpState.DUMP_MESSAGES);
20179            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20180                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20181            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20182                    || "intent-filter-verifiers".equals(cmd)) {
20183                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20184            } else if ("version".equals(cmd)) {
20185                dumpState.setDump(DumpState.DUMP_VERSION);
20186            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20187                dumpState.setDump(DumpState.DUMP_KEYSETS);
20188            } else if ("installs".equals(cmd)) {
20189                dumpState.setDump(DumpState.DUMP_INSTALLS);
20190            } else if ("frozen".equals(cmd)) {
20191                dumpState.setDump(DumpState.DUMP_FROZEN);
20192            } else if ("dexopt".equals(cmd)) {
20193                dumpState.setDump(DumpState.DUMP_DEXOPT);
20194            } else if ("compiler-stats".equals(cmd)) {
20195                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20196            } else if ("write".equals(cmd)) {
20197                synchronized (mPackages) {
20198                    mSettings.writeLPr();
20199                    pw.println("Settings written.");
20200                    return;
20201                }
20202            }
20203        }
20204
20205        if (checkin) {
20206            pw.println("vers,1");
20207        }
20208
20209        // reader
20210        synchronized (mPackages) {
20211            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20212                if (!checkin) {
20213                    if (dumpState.onTitlePrinted())
20214                        pw.println();
20215                    pw.println("Database versions:");
20216                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20217                }
20218            }
20219
20220            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20221                if (!checkin) {
20222                    if (dumpState.onTitlePrinted())
20223                        pw.println();
20224                    pw.println("Verifiers:");
20225                    pw.print("  Required: ");
20226                    pw.print(mRequiredVerifierPackage);
20227                    pw.print(" (uid=");
20228                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20229                            UserHandle.USER_SYSTEM));
20230                    pw.println(")");
20231                } else if (mRequiredVerifierPackage != null) {
20232                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20233                    pw.print(",");
20234                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20235                            UserHandle.USER_SYSTEM));
20236                }
20237            }
20238
20239            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20240                    packageName == null) {
20241                if (mIntentFilterVerifierComponent != null) {
20242                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20243                    if (!checkin) {
20244                        if (dumpState.onTitlePrinted())
20245                            pw.println();
20246                        pw.println("Intent Filter Verifier:");
20247                        pw.print("  Using: ");
20248                        pw.print(verifierPackageName);
20249                        pw.print(" (uid=");
20250                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20251                                UserHandle.USER_SYSTEM));
20252                        pw.println(")");
20253                    } else if (verifierPackageName != null) {
20254                        pw.print("ifv,"); pw.print(verifierPackageName);
20255                        pw.print(",");
20256                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20257                                UserHandle.USER_SYSTEM));
20258                    }
20259                } else {
20260                    pw.println();
20261                    pw.println("No Intent Filter Verifier available!");
20262                }
20263            }
20264
20265            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20266                boolean printedHeader = false;
20267                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20268                while (it.hasNext()) {
20269                    String libName = it.next();
20270                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20271                    if (versionedLib == null) {
20272                        continue;
20273                    }
20274                    final int versionCount = versionedLib.size();
20275                    for (int i = 0; i < versionCount; i++) {
20276                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20277                        if (!checkin) {
20278                            if (!printedHeader) {
20279                                if (dumpState.onTitlePrinted())
20280                                    pw.println();
20281                                pw.println("Libraries:");
20282                                printedHeader = true;
20283                            }
20284                            pw.print("  ");
20285                        } else {
20286                            pw.print("lib,");
20287                        }
20288                        pw.print(libEntry.info.getName());
20289                        if (libEntry.info.isStatic()) {
20290                            pw.print(" version=" + libEntry.info.getVersion());
20291                        }
20292                        if (!checkin) {
20293                            pw.print(" -> ");
20294                        }
20295                        if (libEntry.path != null) {
20296                            pw.print(" (jar) ");
20297                            pw.print(libEntry.path);
20298                        } else {
20299                            pw.print(" (apk) ");
20300                            pw.print(libEntry.apk);
20301                        }
20302                        pw.println();
20303                    }
20304                }
20305            }
20306
20307            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20308                if (dumpState.onTitlePrinted())
20309                    pw.println();
20310                if (!checkin) {
20311                    pw.println("Features:");
20312                }
20313
20314                for (FeatureInfo feat : mAvailableFeatures.values()) {
20315                    if (checkin) {
20316                        pw.print("feat,");
20317                        pw.print(feat.name);
20318                        pw.print(",");
20319                        pw.println(feat.version);
20320                    } else {
20321                        pw.print("  ");
20322                        pw.print(feat.name);
20323                        if (feat.version > 0) {
20324                            pw.print(" version=");
20325                            pw.print(feat.version);
20326                        }
20327                        pw.println();
20328                    }
20329                }
20330            }
20331
20332            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20333                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20334                        : "Activity Resolver Table:", "  ", packageName,
20335                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20336                    dumpState.setTitlePrinted(true);
20337                }
20338            }
20339            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20340                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20341                        : "Receiver Resolver Table:", "  ", packageName,
20342                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20343                    dumpState.setTitlePrinted(true);
20344                }
20345            }
20346            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20347                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20348                        : "Service Resolver Table:", "  ", packageName,
20349                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20350                    dumpState.setTitlePrinted(true);
20351                }
20352            }
20353            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20354                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20355                        : "Provider Resolver Table:", "  ", packageName,
20356                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20357                    dumpState.setTitlePrinted(true);
20358                }
20359            }
20360
20361            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20362                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20363                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20364                    int user = mSettings.mPreferredActivities.keyAt(i);
20365                    if (pir.dump(pw,
20366                            dumpState.getTitlePrinted()
20367                                ? "\nPreferred Activities User " + user + ":"
20368                                : "Preferred Activities User " + user + ":", "  ",
20369                            packageName, true, false)) {
20370                        dumpState.setTitlePrinted(true);
20371                    }
20372                }
20373            }
20374
20375            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20376                pw.flush();
20377                FileOutputStream fout = new FileOutputStream(fd);
20378                BufferedOutputStream str = new BufferedOutputStream(fout);
20379                XmlSerializer serializer = new FastXmlSerializer();
20380                try {
20381                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20382                    serializer.startDocument(null, true);
20383                    serializer.setFeature(
20384                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20385                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20386                    serializer.endDocument();
20387                    serializer.flush();
20388                } catch (IllegalArgumentException e) {
20389                    pw.println("Failed writing: " + e);
20390                } catch (IllegalStateException e) {
20391                    pw.println("Failed writing: " + e);
20392                } catch (IOException e) {
20393                    pw.println("Failed writing: " + e);
20394                }
20395            }
20396
20397            if (!checkin
20398                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20399                    && packageName == null) {
20400                pw.println();
20401                int count = mSettings.mPackages.size();
20402                if (count == 0) {
20403                    pw.println("No applications!");
20404                    pw.println();
20405                } else {
20406                    final String prefix = "  ";
20407                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20408                    if (allPackageSettings.size() == 0) {
20409                        pw.println("No domain preferred apps!");
20410                        pw.println();
20411                    } else {
20412                        pw.println("App verification status:");
20413                        pw.println();
20414                        count = 0;
20415                        for (PackageSetting ps : allPackageSettings) {
20416                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20417                            if (ivi == null || ivi.getPackageName() == null) continue;
20418                            pw.println(prefix + "Package: " + ivi.getPackageName());
20419                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20420                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20421                            pw.println();
20422                            count++;
20423                        }
20424                        if (count == 0) {
20425                            pw.println(prefix + "No app verification established.");
20426                            pw.println();
20427                        }
20428                        for (int userId : sUserManager.getUserIds()) {
20429                            pw.println("App linkages for user " + userId + ":");
20430                            pw.println();
20431                            count = 0;
20432                            for (PackageSetting ps : allPackageSettings) {
20433                                final long status = ps.getDomainVerificationStatusForUser(userId);
20434                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20435                                        && !DEBUG_DOMAIN_VERIFICATION) {
20436                                    continue;
20437                                }
20438                                pw.println(prefix + "Package: " + ps.name);
20439                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20440                                String statusStr = IntentFilterVerificationInfo.
20441                                        getStatusStringFromValue(status);
20442                                pw.println(prefix + "Status:  " + statusStr);
20443                                pw.println();
20444                                count++;
20445                            }
20446                            if (count == 0) {
20447                                pw.println(prefix + "No configured app linkages.");
20448                                pw.println();
20449                            }
20450                        }
20451                    }
20452                }
20453            }
20454
20455            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20456                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20457                if (packageName == null && permissionNames == null) {
20458                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20459                        if (iperm == 0) {
20460                            if (dumpState.onTitlePrinted())
20461                                pw.println();
20462                            pw.println("AppOp Permissions:");
20463                        }
20464                        pw.print("  AppOp Permission ");
20465                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20466                        pw.println(":");
20467                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20468                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20469                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20470                        }
20471                    }
20472                }
20473            }
20474
20475            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20476                boolean printedSomething = false;
20477                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20478                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20479                        continue;
20480                    }
20481                    if (!printedSomething) {
20482                        if (dumpState.onTitlePrinted())
20483                            pw.println();
20484                        pw.println("Registered ContentProviders:");
20485                        printedSomething = true;
20486                    }
20487                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20488                    pw.print("    "); pw.println(p.toString());
20489                }
20490                printedSomething = false;
20491                for (Map.Entry<String, PackageParser.Provider> entry :
20492                        mProvidersByAuthority.entrySet()) {
20493                    PackageParser.Provider p = entry.getValue();
20494                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20495                        continue;
20496                    }
20497                    if (!printedSomething) {
20498                        if (dumpState.onTitlePrinted())
20499                            pw.println();
20500                        pw.println("ContentProvider Authorities:");
20501                        printedSomething = true;
20502                    }
20503                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20504                    pw.print("    "); pw.println(p.toString());
20505                    if (p.info != null && p.info.applicationInfo != null) {
20506                        final String appInfo = p.info.applicationInfo.toString();
20507                        pw.print("      applicationInfo="); pw.println(appInfo);
20508                    }
20509                }
20510            }
20511
20512            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20513                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20514            }
20515
20516            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20517                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20518            }
20519
20520            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20521                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20522            }
20523
20524            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20525                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20526            }
20527
20528            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20529                // XXX should handle packageName != null by dumping only install data that
20530                // the given package is involved with.
20531                if (dumpState.onTitlePrinted()) pw.println();
20532                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20533            }
20534
20535            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20536                // XXX should handle packageName != null by dumping only install data that
20537                // the given package is involved with.
20538                if (dumpState.onTitlePrinted()) pw.println();
20539
20540                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20541                ipw.println();
20542                ipw.println("Frozen packages:");
20543                ipw.increaseIndent();
20544                if (mFrozenPackages.size() == 0) {
20545                    ipw.println("(none)");
20546                } else {
20547                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20548                        ipw.println(mFrozenPackages.valueAt(i));
20549                    }
20550                }
20551                ipw.decreaseIndent();
20552            }
20553
20554            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20555                if (dumpState.onTitlePrinted()) pw.println();
20556                dumpDexoptStateLPr(pw, packageName);
20557            }
20558
20559            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20560                if (dumpState.onTitlePrinted()) pw.println();
20561                dumpCompilerStatsLPr(pw, packageName);
20562            }
20563
20564            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20565                if (dumpState.onTitlePrinted()) pw.println();
20566                mSettings.dumpReadMessagesLPr(pw, dumpState);
20567
20568                pw.println();
20569                pw.println("Package warning messages:");
20570                BufferedReader in = null;
20571                String line = null;
20572                try {
20573                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20574                    while ((line = in.readLine()) != null) {
20575                        if (line.contains("ignored: updated version")) continue;
20576                        pw.println(line);
20577                    }
20578                } catch (IOException ignored) {
20579                } finally {
20580                    IoUtils.closeQuietly(in);
20581                }
20582            }
20583
20584            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20585                BufferedReader in = null;
20586                String line = null;
20587                try {
20588                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20589                    while ((line = in.readLine()) != null) {
20590                        if (line.contains("ignored: updated version")) continue;
20591                        pw.print("msg,");
20592                        pw.println(line);
20593                    }
20594                } catch (IOException ignored) {
20595                } finally {
20596                    IoUtils.closeQuietly(in);
20597                }
20598            }
20599        }
20600    }
20601
20602    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20603        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20604        ipw.println();
20605        ipw.println("Dexopt state:");
20606        ipw.increaseIndent();
20607        Collection<PackageParser.Package> packages = null;
20608        if (packageName != null) {
20609            PackageParser.Package targetPackage = mPackages.get(packageName);
20610            if (targetPackage != null) {
20611                packages = Collections.singletonList(targetPackage);
20612            } else {
20613                ipw.println("Unable to find package: " + packageName);
20614                return;
20615            }
20616        } else {
20617            packages = mPackages.values();
20618        }
20619
20620        for (PackageParser.Package pkg : packages) {
20621            ipw.println("[" + pkg.packageName + "]");
20622            ipw.increaseIndent();
20623            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20624            ipw.decreaseIndent();
20625        }
20626    }
20627
20628    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20629        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20630        ipw.println();
20631        ipw.println("Compiler stats:");
20632        ipw.increaseIndent();
20633        Collection<PackageParser.Package> packages = null;
20634        if (packageName != null) {
20635            PackageParser.Package targetPackage = mPackages.get(packageName);
20636            if (targetPackage != null) {
20637                packages = Collections.singletonList(targetPackage);
20638            } else {
20639                ipw.println("Unable to find package: " + packageName);
20640                return;
20641            }
20642        } else {
20643            packages = mPackages.values();
20644        }
20645
20646        for (PackageParser.Package pkg : packages) {
20647            ipw.println("[" + pkg.packageName + "]");
20648            ipw.increaseIndent();
20649
20650            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20651            if (stats == null) {
20652                ipw.println("(No recorded stats)");
20653            } else {
20654                stats.dump(ipw);
20655            }
20656            ipw.decreaseIndent();
20657        }
20658    }
20659
20660    private String dumpDomainString(String packageName) {
20661        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20662                .getList();
20663        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20664
20665        ArraySet<String> result = new ArraySet<>();
20666        if (iviList.size() > 0) {
20667            for (IntentFilterVerificationInfo ivi : iviList) {
20668                for (String host : ivi.getDomains()) {
20669                    result.add(host);
20670                }
20671            }
20672        }
20673        if (filters != null && filters.size() > 0) {
20674            for (IntentFilter filter : filters) {
20675                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20676                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20677                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20678                    result.addAll(filter.getHostsList());
20679                }
20680            }
20681        }
20682
20683        StringBuilder sb = new StringBuilder(result.size() * 16);
20684        for (String domain : result) {
20685            if (sb.length() > 0) sb.append(" ");
20686            sb.append(domain);
20687        }
20688        return sb.toString();
20689    }
20690
20691    // ------- apps on sdcard specific code -------
20692    static final boolean DEBUG_SD_INSTALL = false;
20693
20694    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20695
20696    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20697
20698    private boolean mMediaMounted = false;
20699
20700    static String getEncryptKey() {
20701        try {
20702            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20703                    SD_ENCRYPTION_KEYSTORE_NAME);
20704            if (sdEncKey == null) {
20705                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20706                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20707                if (sdEncKey == null) {
20708                    Slog.e(TAG, "Failed to create encryption keys");
20709                    return null;
20710                }
20711            }
20712            return sdEncKey;
20713        } catch (NoSuchAlgorithmException nsae) {
20714            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20715            return null;
20716        } catch (IOException ioe) {
20717            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20718            return null;
20719        }
20720    }
20721
20722    /*
20723     * Update media status on PackageManager.
20724     */
20725    @Override
20726    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20727        int callingUid = Binder.getCallingUid();
20728        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20729            throw new SecurityException("Media status can only be updated by the system");
20730        }
20731        // reader; this apparently protects mMediaMounted, but should probably
20732        // be a different lock in that case.
20733        synchronized (mPackages) {
20734            Log.i(TAG, "Updating external media status from "
20735                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20736                    + (mediaStatus ? "mounted" : "unmounted"));
20737            if (DEBUG_SD_INSTALL)
20738                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20739                        + ", mMediaMounted=" + mMediaMounted);
20740            if (mediaStatus == mMediaMounted) {
20741                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20742                        : 0, -1);
20743                mHandler.sendMessage(msg);
20744                return;
20745            }
20746            mMediaMounted = mediaStatus;
20747        }
20748        // Queue up an async operation since the package installation may take a
20749        // little while.
20750        mHandler.post(new Runnable() {
20751            public void run() {
20752                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20753            }
20754        });
20755    }
20756
20757    /**
20758     * Called by StorageManagerService when the initial ASECs to scan are available.
20759     * Should block until all the ASEC containers are finished being scanned.
20760     */
20761    public void scanAvailableAsecs() {
20762        updateExternalMediaStatusInner(true, false, false);
20763    }
20764
20765    /*
20766     * Collect information of applications on external media, map them against
20767     * existing containers and update information based on current mount status.
20768     * Please note that we always have to report status if reportStatus has been
20769     * set to true especially when unloading packages.
20770     */
20771    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20772            boolean externalStorage) {
20773        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20774        int[] uidArr = EmptyArray.INT;
20775
20776        final String[] list = PackageHelper.getSecureContainerList();
20777        if (ArrayUtils.isEmpty(list)) {
20778            Log.i(TAG, "No secure containers found");
20779        } else {
20780            // Process list of secure containers and categorize them
20781            // as active or stale based on their package internal state.
20782
20783            // reader
20784            synchronized (mPackages) {
20785                for (String cid : list) {
20786                    // Leave stages untouched for now; installer service owns them
20787                    if (PackageInstallerService.isStageName(cid)) continue;
20788
20789                    if (DEBUG_SD_INSTALL)
20790                        Log.i(TAG, "Processing container " + cid);
20791                    String pkgName = getAsecPackageName(cid);
20792                    if (pkgName == null) {
20793                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20794                        continue;
20795                    }
20796                    if (DEBUG_SD_INSTALL)
20797                        Log.i(TAG, "Looking for pkg : " + pkgName);
20798
20799                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20800                    if (ps == null) {
20801                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20802                        continue;
20803                    }
20804
20805                    /*
20806                     * Skip packages that are not external if we're unmounting
20807                     * external storage.
20808                     */
20809                    if (externalStorage && !isMounted && !isExternal(ps)) {
20810                        continue;
20811                    }
20812
20813                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20814                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20815                    // The package status is changed only if the code path
20816                    // matches between settings and the container id.
20817                    if (ps.codePathString != null
20818                            && ps.codePathString.startsWith(args.getCodePath())) {
20819                        if (DEBUG_SD_INSTALL) {
20820                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20821                                    + " at code path: " + ps.codePathString);
20822                        }
20823
20824                        // We do have a valid package installed on sdcard
20825                        processCids.put(args, ps.codePathString);
20826                        final int uid = ps.appId;
20827                        if (uid != -1) {
20828                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20829                        }
20830                    } else {
20831                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20832                                + ps.codePathString);
20833                    }
20834                }
20835            }
20836
20837            Arrays.sort(uidArr);
20838        }
20839
20840        // Process packages with valid entries.
20841        if (isMounted) {
20842            if (DEBUG_SD_INSTALL)
20843                Log.i(TAG, "Loading packages");
20844            loadMediaPackages(processCids, uidArr, externalStorage);
20845            startCleaningPackages();
20846            mInstallerService.onSecureContainersAvailable();
20847        } else {
20848            if (DEBUG_SD_INSTALL)
20849                Log.i(TAG, "Unloading packages");
20850            unloadMediaPackages(processCids, uidArr, reportStatus);
20851        }
20852    }
20853
20854    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20855            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20856        final int size = infos.size();
20857        final String[] packageNames = new String[size];
20858        final int[] packageUids = new int[size];
20859        for (int i = 0; i < size; i++) {
20860            final ApplicationInfo info = infos.get(i);
20861            packageNames[i] = info.packageName;
20862            packageUids[i] = info.uid;
20863        }
20864        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20865                finishedReceiver);
20866    }
20867
20868    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20869            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20870        sendResourcesChangedBroadcast(mediaStatus, replacing,
20871                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20872    }
20873
20874    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20875            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20876        int size = pkgList.length;
20877        if (size > 0) {
20878            // Send broadcasts here
20879            Bundle extras = new Bundle();
20880            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20881            if (uidArr != null) {
20882                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20883            }
20884            if (replacing) {
20885                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20886            }
20887            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20888                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20889            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20890        }
20891    }
20892
20893   /*
20894     * Look at potentially valid container ids from processCids If package
20895     * information doesn't match the one on record or package scanning fails,
20896     * the cid is added to list of removeCids. We currently don't delete stale
20897     * containers.
20898     */
20899    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20900            boolean externalStorage) {
20901        ArrayList<String> pkgList = new ArrayList<String>();
20902        Set<AsecInstallArgs> keys = processCids.keySet();
20903
20904        for (AsecInstallArgs args : keys) {
20905            String codePath = processCids.get(args);
20906            if (DEBUG_SD_INSTALL)
20907                Log.i(TAG, "Loading container : " + args.cid);
20908            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20909            try {
20910                // Make sure there are no container errors first.
20911                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20912                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20913                            + " when installing from sdcard");
20914                    continue;
20915                }
20916                // Check code path here.
20917                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20918                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20919                            + " does not match one in settings " + codePath);
20920                    continue;
20921                }
20922                // Parse package
20923                int parseFlags = mDefParseFlags;
20924                if (args.isExternalAsec()) {
20925                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20926                }
20927                if (args.isFwdLocked()) {
20928                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20929                }
20930
20931                synchronized (mInstallLock) {
20932                    PackageParser.Package pkg = null;
20933                    try {
20934                        // Sadly we don't know the package name yet to freeze it
20935                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20936                                SCAN_IGNORE_FROZEN, 0, null);
20937                    } catch (PackageManagerException e) {
20938                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20939                    }
20940                    // Scan the package
20941                    if (pkg != null) {
20942                        /*
20943                         * TODO why is the lock being held? doPostInstall is
20944                         * called in other places without the lock. This needs
20945                         * to be straightened out.
20946                         */
20947                        // writer
20948                        synchronized (mPackages) {
20949                            retCode = PackageManager.INSTALL_SUCCEEDED;
20950                            pkgList.add(pkg.packageName);
20951                            // Post process args
20952                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20953                                    pkg.applicationInfo.uid);
20954                        }
20955                    } else {
20956                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20957                    }
20958                }
20959
20960            } finally {
20961                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20962                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20963                }
20964            }
20965        }
20966        // writer
20967        synchronized (mPackages) {
20968            // If the platform SDK has changed since the last time we booted,
20969            // we need to re-grant app permission to catch any new ones that
20970            // appear. This is really a hack, and means that apps can in some
20971            // cases get permissions that the user didn't initially explicitly
20972            // allow... it would be nice to have some better way to handle
20973            // this situation.
20974            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20975                    : mSettings.getInternalVersion();
20976            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20977                    : StorageManager.UUID_PRIVATE_INTERNAL;
20978
20979            int updateFlags = UPDATE_PERMISSIONS_ALL;
20980            if (ver.sdkVersion != mSdkVersion) {
20981                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20982                        + mSdkVersion + "; regranting permissions for external");
20983                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20984            }
20985            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20986
20987            // Yay, everything is now upgraded
20988            ver.forceCurrent();
20989
20990            // can downgrade to reader
20991            // Persist settings
20992            mSettings.writeLPr();
20993        }
20994        // Send a broadcast to let everyone know we are done processing
20995        if (pkgList.size() > 0) {
20996            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20997        }
20998    }
20999
21000   /*
21001     * Utility method to unload a list of specified containers
21002     */
21003    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21004        // Just unmount all valid containers.
21005        for (AsecInstallArgs arg : cidArgs) {
21006            synchronized (mInstallLock) {
21007                arg.doPostDeleteLI(false);
21008           }
21009       }
21010   }
21011
21012    /*
21013     * Unload packages mounted on external media. This involves deleting package
21014     * data from internal structures, sending broadcasts about disabled packages,
21015     * gc'ing to free up references, unmounting all secure containers
21016     * corresponding to packages on external media, and posting a
21017     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21018     * that we always have to post this message if status has been requested no
21019     * matter what.
21020     */
21021    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21022            final boolean reportStatus) {
21023        if (DEBUG_SD_INSTALL)
21024            Log.i(TAG, "unloading media packages");
21025        ArrayList<String> pkgList = new ArrayList<String>();
21026        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21027        final Set<AsecInstallArgs> keys = processCids.keySet();
21028        for (AsecInstallArgs args : keys) {
21029            String pkgName = args.getPackageName();
21030            if (DEBUG_SD_INSTALL)
21031                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21032            // Delete package internally
21033            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21034            synchronized (mInstallLock) {
21035                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21036                final boolean res;
21037                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21038                        "unloadMediaPackages")) {
21039                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21040                            null);
21041                }
21042                if (res) {
21043                    pkgList.add(pkgName);
21044                } else {
21045                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21046                    failedList.add(args);
21047                }
21048            }
21049        }
21050
21051        // reader
21052        synchronized (mPackages) {
21053            // We didn't update the settings after removing each package;
21054            // write them now for all packages.
21055            mSettings.writeLPr();
21056        }
21057
21058        // We have to absolutely send UPDATED_MEDIA_STATUS only
21059        // after confirming that all the receivers processed the ordered
21060        // broadcast when packages get disabled, force a gc to clean things up.
21061        // and unload all the containers.
21062        if (pkgList.size() > 0) {
21063            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21064                    new IIntentReceiver.Stub() {
21065                public void performReceive(Intent intent, int resultCode, String data,
21066                        Bundle extras, boolean ordered, boolean sticky,
21067                        int sendingUser) throws RemoteException {
21068                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21069                            reportStatus ? 1 : 0, 1, keys);
21070                    mHandler.sendMessage(msg);
21071                }
21072            });
21073        } else {
21074            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21075                    keys);
21076            mHandler.sendMessage(msg);
21077        }
21078    }
21079
21080    private void loadPrivatePackages(final VolumeInfo vol) {
21081        mHandler.post(new Runnable() {
21082            @Override
21083            public void run() {
21084                loadPrivatePackagesInner(vol);
21085            }
21086        });
21087    }
21088
21089    private void loadPrivatePackagesInner(VolumeInfo vol) {
21090        final String volumeUuid = vol.fsUuid;
21091        if (TextUtils.isEmpty(volumeUuid)) {
21092            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21093            return;
21094        }
21095
21096        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21097        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21098        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21099
21100        final VersionInfo ver;
21101        final List<PackageSetting> packages;
21102        synchronized (mPackages) {
21103            ver = mSettings.findOrCreateVersion(volumeUuid);
21104            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21105        }
21106
21107        for (PackageSetting ps : packages) {
21108            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21109            synchronized (mInstallLock) {
21110                final PackageParser.Package pkg;
21111                try {
21112                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21113                    loaded.add(pkg.applicationInfo);
21114
21115                } catch (PackageManagerException e) {
21116                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21117                }
21118
21119                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21120                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21121                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21122                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21123                }
21124            }
21125        }
21126
21127        // Reconcile app data for all started/unlocked users
21128        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21129        final UserManager um = mContext.getSystemService(UserManager.class);
21130        UserManagerInternal umInternal = getUserManagerInternal();
21131        for (UserInfo user : um.getUsers()) {
21132            final int flags;
21133            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21134                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21135            } else if (umInternal.isUserRunning(user.id)) {
21136                flags = StorageManager.FLAG_STORAGE_DE;
21137            } else {
21138                continue;
21139            }
21140
21141            try {
21142                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21143                synchronized (mInstallLock) {
21144                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21145                }
21146            } catch (IllegalStateException e) {
21147                // Device was probably ejected, and we'll process that event momentarily
21148                Slog.w(TAG, "Failed to prepare storage: " + e);
21149            }
21150        }
21151
21152        synchronized (mPackages) {
21153            int updateFlags = UPDATE_PERMISSIONS_ALL;
21154            if (ver.sdkVersion != mSdkVersion) {
21155                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21156                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21157                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21158            }
21159            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21160
21161            // Yay, everything is now upgraded
21162            ver.forceCurrent();
21163
21164            mSettings.writeLPr();
21165        }
21166
21167        for (PackageFreezer freezer : freezers) {
21168            freezer.close();
21169        }
21170
21171        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21172        sendResourcesChangedBroadcast(true, false, loaded, null);
21173    }
21174
21175    private void unloadPrivatePackages(final VolumeInfo vol) {
21176        mHandler.post(new Runnable() {
21177            @Override
21178            public void run() {
21179                unloadPrivatePackagesInner(vol);
21180            }
21181        });
21182    }
21183
21184    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21185        final String volumeUuid = vol.fsUuid;
21186        if (TextUtils.isEmpty(volumeUuid)) {
21187            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21188            return;
21189        }
21190
21191        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21192        synchronized (mInstallLock) {
21193        synchronized (mPackages) {
21194            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21195            for (PackageSetting ps : packages) {
21196                if (ps.pkg == null) continue;
21197
21198                final ApplicationInfo info = ps.pkg.applicationInfo;
21199                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21200                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21201
21202                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21203                        "unloadPrivatePackagesInner")) {
21204                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21205                            false, null)) {
21206                        unloaded.add(info);
21207                    } else {
21208                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21209                    }
21210                }
21211
21212                // Try very hard to release any references to this package
21213                // so we don't risk the system server being killed due to
21214                // open FDs
21215                AttributeCache.instance().removePackage(ps.name);
21216            }
21217
21218            mSettings.writeLPr();
21219        }
21220        }
21221
21222        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21223        sendResourcesChangedBroadcast(false, false, unloaded, null);
21224
21225        // Try very hard to release any references to this path so we don't risk
21226        // the system server being killed due to open FDs
21227        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21228
21229        for (int i = 0; i < 3; i++) {
21230            System.gc();
21231            System.runFinalization();
21232        }
21233    }
21234
21235    /**
21236     * Prepare storage areas for given user on all mounted devices.
21237     */
21238    void prepareUserData(int userId, int userSerial, int flags) {
21239        synchronized (mInstallLock) {
21240            final StorageManager storage = mContext.getSystemService(StorageManager.class);
21241            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21242                final String volumeUuid = vol.getFsUuid();
21243                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
21244            }
21245        }
21246    }
21247
21248    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
21249            boolean allowRecover) {
21250        // Prepare storage and verify that serial numbers are consistent; if
21251        // there's a mismatch we need to destroy to avoid leaking data
21252        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21253        try {
21254            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
21255
21256            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
21257                UserManagerService.enforceSerialNumber(
21258                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
21259                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21260                    UserManagerService.enforceSerialNumber(
21261                            Environment.getDataSystemDeDirectory(userId), userSerial);
21262                }
21263            }
21264            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
21265                UserManagerService.enforceSerialNumber(
21266                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
21267                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21268                    UserManagerService.enforceSerialNumber(
21269                            Environment.getDataSystemCeDirectory(userId), userSerial);
21270                }
21271            }
21272
21273            synchronized (mInstallLock) {
21274                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
21275            }
21276        } catch (Exception e) {
21277            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
21278                    + " because we failed to prepare: " + e);
21279            destroyUserDataLI(volumeUuid, userId,
21280                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21281
21282            if (allowRecover) {
21283                // Try one last time; if we fail again we're really in trouble
21284                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
21285            }
21286        }
21287    }
21288
21289    /**
21290     * Destroy storage areas for given user on all mounted devices.
21291     */
21292    void destroyUserData(int userId, int flags) {
21293        synchronized (mInstallLock) {
21294            final StorageManager storage = mContext.getSystemService(StorageManager.class);
21295            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21296                final String volumeUuid = vol.getFsUuid();
21297                destroyUserDataLI(volumeUuid, userId, flags);
21298            }
21299        }
21300    }
21301
21302    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
21303        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21304        try {
21305            // Clean up app data, profile data, and media data
21306            mInstaller.destroyUserData(volumeUuid, userId, flags);
21307
21308            // Clean up system data
21309            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21310                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21311                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
21312                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
21313                }
21314                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21315                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
21316                }
21317            }
21318
21319            // Data with special labels is now gone, so finish the job
21320            storage.destroyUserStorage(volumeUuid, userId, flags);
21321
21322        } catch (Exception e) {
21323            logCriticalInfo(Log.WARN,
21324                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
21325        }
21326    }
21327
21328    /**
21329     * Examine all users present on given mounted volume, and destroy data
21330     * belonging to users that are no longer valid, or whose user ID has been
21331     * recycled.
21332     */
21333    private void reconcileUsers(String volumeUuid) {
21334        final List<File> files = new ArrayList<>();
21335        Collections.addAll(files, FileUtils
21336                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
21337        Collections.addAll(files, FileUtils
21338                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
21339        Collections.addAll(files, FileUtils
21340                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
21341        Collections.addAll(files, FileUtils
21342                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
21343        for (File file : files) {
21344            if (!file.isDirectory()) continue;
21345
21346            final int userId;
21347            final UserInfo info;
21348            try {
21349                userId = Integer.parseInt(file.getName());
21350                info = sUserManager.getUserInfo(userId);
21351            } catch (NumberFormatException e) {
21352                Slog.w(TAG, "Invalid user directory " + file);
21353                continue;
21354            }
21355
21356            boolean destroyUser = false;
21357            if (info == null) {
21358                logCriticalInfo(Log.WARN, "Destroying user directory " + file
21359                        + " because no matching user was found");
21360                destroyUser = true;
21361            } else if (!mOnlyCore) {
21362                try {
21363                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
21364                } catch (IOException e) {
21365                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
21366                            + " because we failed to enforce serial number: " + e);
21367                    destroyUser = true;
21368                }
21369            }
21370
21371            if (destroyUser) {
21372                synchronized (mInstallLock) {
21373                    destroyUserDataLI(volumeUuid, userId,
21374                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21375                }
21376            }
21377        }
21378    }
21379
21380    private void assertPackageKnown(String volumeUuid, String packageName)
21381            throws PackageManagerException {
21382        synchronized (mPackages) {
21383            // Normalize package name to handle renamed packages
21384            packageName = normalizePackageNameLPr(packageName);
21385
21386            final PackageSetting ps = mSettings.mPackages.get(packageName);
21387            if (ps == null) {
21388                throw new PackageManagerException("Package " + packageName + " is unknown");
21389            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21390                throw new PackageManagerException(
21391                        "Package " + packageName + " found on unknown volume " + volumeUuid
21392                                + "; expected volume " + ps.volumeUuid);
21393            }
21394        }
21395    }
21396
21397    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21398            throws PackageManagerException {
21399        synchronized (mPackages) {
21400            // Normalize package name to handle renamed packages
21401            packageName = normalizePackageNameLPr(packageName);
21402
21403            final PackageSetting ps = mSettings.mPackages.get(packageName);
21404            if (ps == null) {
21405                throw new PackageManagerException("Package " + packageName + " is unknown");
21406            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21407                throw new PackageManagerException(
21408                        "Package " + packageName + " found on unknown volume " + volumeUuid
21409                                + "; expected volume " + ps.volumeUuid);
21410            } else if (!ps.getInstalled(userId)) {
21411                throw new PackageManagerException(
21412                        "Package " + packageName + " not installed for user " + userId);
21413            }
21414        }
21415    }
21416
21417    private List<String> collectAbsoluteCodePaths() {
21418        synchronized (mPackages) {
21419            List<String> codePaths = new ArrayList<>();
21420            final int packageCount = mSettings.mPackages.size();
21421            for (int i = 0; i < packageCount; i++) {
21422                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21423                codePaths.add(ps.codePath.getAbsolutePath());
21424            }
21425            return codePaths;
21426        }
21427    }
21428
21429    /**
21430     * Examine all apps present on given mounted volume, and destroy apps that
21431     * aren't expected, either due to uninstallation or reinstallation on
21432     * another volume.
21433     */
21434    private void reconcileApps(String volumeUuid) {
21435        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21436        List<File> filesToDelete = null;
21437
21438        final File[] files = FileUtils.listFilesOrEmpty(
21439                Environment.getDataAppDirectory(volumeUuid));
21440        for (File file : files) {
21441            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21442                    && !PackageInstallerService.isStageName(file.getName());
21443            if (!isPackage) {
21444                // Ignore entries which are not packages
21445                continue;
21446            }
21447
21448            String absolutePath = file.getAbsolutePath();
21449
21450            boolean pathValid = false;
21451            final int absoluteCodePathCount = absoluteCodePaths.size();
21452            for (int i = 0; i < absoluteCodePathCount; i++) {
21453                String absoluteCodePath = absoluteCodePaths.get(i);
21454                if (absolutePath.startsWith(absoluteCodePath)) {
21455                    pathValid = true;
21456                    break;
21457                }
21458            }
21459
21460            if (!pathValid) {
21461                if (filesToDelete == null) {
21462                    filesToDelete = new ArrayList<>();
21463                }
21464                filesToDelete.add(file);
21465            }
21466        }
21467
21468        if (filesToDelete != null) {
21469            final int fileToDeleteCount = filesToDelete.size();
21470            for (int i = 0; i < fileToDeleteCount; i++) {
21471                File fileToDelete = filesToDelete.get(i);
21472                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21473                synchronized (mInstallLock) {
21474                    removeCodePathLI(fileToDelete);
21475                }
21476            }
21477        }
21478    }
21479
21480    /**
21481     * Reconcile all app data for the given user.
21482     * <p>
21483     * Verifies that directories exist and that ownership and labeling is
21484     * correct for all installed apps on all mounted volumes.
21485     */
21486    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21487        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21488        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21489            final String volumeUuid = vol.getFsUuid();
21490            synchronized (mInstallLock) {
21491                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21492            }
21493        }
21494    }
21495
21496    /**
21497     * Reconcile all app data on given mounted volume.
21498     * <p>
21499     * Destroys app data that isn't expected, either due to uninstallation or
21500     * reinstallation on another volume.
21501     * <p>
21502     * Verifies that directories exist and that ownership and labeling is
21503     * correct for all installed apps.
21504     */
21505    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21506            boolean migrateAppData) {
21507        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21508                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21509
21510        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21511        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21512
21513        // First look for stale data that doesn't belong, and check if things
21514        // have changed since we did our last restorecon
21515        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21516            if (StorageManager.isFileEncryptedNativeOrEmulated()
21517                    && !StorageManager.isUserKeyUnlocked(userId)) {
21518                throw new RuntimeException(
21519                        "Yikes, someone asked us to reconcile CE storage while " + userId
21520                                + " was still locked; this would have caused massive data loss!");
21521            }
21522
21523            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21524            for (File file : files) {
21525                final String packageName = file.getName();
21526                try {
21527                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21528                } catch (PackageManagerException e) {
21529                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21530                    try {
21531                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21532                                StorageManager.FLAG_STORAGE_CE, 0);
21533                    } catch (InstallerException e2) {
21534                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21535                    }
21536                }
21537            }
21538        }
21539        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21540            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21541            for (File file : files) {
21542                final String packageName = file.getName();
21543                try {
21544                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21545                } catch (PackageManagerException e) {
21546                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21547                    try {
21548                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21549                                StorageManager.FLAG_STORAGE_DE, 0);
21550                    } catch (InstallerException e2) {
21551                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21552                    }
21553                }
21554            }
21555        }
21556
21557        // Ensure that data directories are ready to roll for all packages
21558        // installed for this volume and user
21559        final List<PackageSetting> packages;
21560        synchronized (mPackages) {
21561            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21562        }
21563        int preparedCount = 0;
21564        for (PackageSetting ps : packages) {
21565            final String packageName = ps.name;
21566            if (ps.pkg == null) {
21567                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21568                // TODO: might be due to legacy ASEC apps; we should circle back
21569                // and reconcile again once they're scanned
21570                continue;
21571            }
21572
21573            if (ps.getInstalled(userId)) {
21574                prepareAppDataLIF(ps.pkg, userId, flags);
21575
21576                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21577                    // We may have just shuffled around app data directories, so
21578                    // prepare them one more time
21579                    prepareAppDataLIF(ps.pkg, userId, flags);
21580                }
21581
21582                preparedCount++;
21583            }
21584        }
21585
21586        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21587    }
21588
21589    /**
21590     * Prepare app data for the given app just after it was installed or
21591     * upgraded. This method carefully only touches users that it's installed
21592     * for, and it forces a restorecon to handle any seinfo changes.
21593     * <p>
21594     * Verifies that directories exist and that ownership and labeling is
21595     * correct for all installed apps. If there is an ownership mismatch, it
21596     * will try recovering system apps by wiping data; third-party app data is
21597     * left intact.
21598     * <p>
21599     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21600     */
21601    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21602        final PackageSetting ps;
21603        synchronized (mPackages) {
21604            ps = mSettings.mPackages.get(pkg.packageName);
21605            mSettings.writeKernelMappingLPr(ps);
21606        }
21607
21608        final UserManager um = mContext.getSystemService(UserManager.class);
21609        UserManagerInternal umInternal = getUserManagerInternal();
21610        for (UserInfo user : um.getUsers()) {
21611            final int flags;
21612            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21613                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21614            } else if (umInternal.isUserRunning(user.id)) {
21615                flags = StorageManager.FLAG_STORAGE_DE;
21616            } else {
21617                continue;
21618            }
21619
21620            if (ps.getInstalled(user.id)) {
21621                // TODO: when user data is locked, mark that we're still dirty
21622                prepareAppDataLIF(pkg, user.id, flags);
21623            }
21624        }
21625    }
21626
21627    /**
21628     * Prepare app data for the given app.
21629     * <p>
21630     * Verifies that directories exist and that ownership and labeling is
21631     * correct for all installed apps. If there is an ownership mismatch, this
21632     * will try recovering system apps by wiping data; third-party app data is
21633     * left intact.
21634     */
21635    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21636        if (pkg == null) {
21637            Slog.wtf(TAG, "Package was null!", new Throwable());
21638            return;
21639        }
21640        prepareAppDataLeafLIF(pkg, userId, flags);
21641        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21642        for (int i = 0; i < childCount; i++) {
21643            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21644        }
21645    }
21646
21647    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21648        if (DEBUG_APP_DATA) {
21649            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21650                    + Integer.toHexString(flags));
21651        }
21652
21653        final String volumeUuid = pkg.volumeUuid;
21654        final String packageName = pkg.packageName;
21655        final ApplicationInfo app = pkg.applicationInfo;
21656        final int appId = UserHandle.getAppId(app.uid);
21657
21658        Preconditions.checkNotNull(app.seinfo);
21659
21660        long ceDataInode = -1;
21661        try {
21662            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21663                    appId, app.seinfo, app.targetSdkVersion);
21664        } catch (InstallerException e) {
21665            if (app.isSystemApp()) {
21666                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21667                        + ", but trying to recover: " + e);
21668                destroyAppDataLeafLIF(pkg, userId, flags);
21669                try {
21670                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21671                            appId, app.seinfo, app.targetSdkVersion);
21672                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21673                } catch (InstallerException e2) {
21674                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21675                }
21676            } else {
21677                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21678            }
21679        }
21680
21681        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21682            // TODO: mark this structure as dirty so we persist it!
21683            synchronized (mPackages) {
21684                final PackageSetting ps = mSettings.mPackages.get(packageName);
21685                if (ps != null) {
21686                    ps.setCeDataInode(ceDataInode, userId);
21687                }
21688            }
21689        }
21690
21691        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21692    }
21693
21694    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21695        if (pkg == null) {
21696            Slog.wtf(TAG, "Package was null!", new Throwable());
21697            return;
21698        }
21699        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21700        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21701        for (int i = 0; i < childCount; i++) {
21702            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21703        }
21704    }
21705
21706    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21707        final String volumeUuid = pkg.volumeUuid;
21708        final String packageName = pkg.packageName;
21709        final ApplicationInfo app = pkg.applicationInfo;
21710
21711        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21712            // Create a native library symlink only if we have native libraries
21713            // and if the native libraries are 32 bit libraries. We do not provide
21714            // this symlink for 64 bit libraries.
21715            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21716                final String nativeLibPath = app.nativeLibraryDir;
21717                try {
21718                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21719                            nativeLibPath, userId);
21720                } catch (InstallerException e) {
21721                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21722                }
21723            }
21724        }
21725    }
21726
21727    /**
21728     * For system apps on non-FBE devices, this method migrates any existing
21729     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21730     * requested by the app.
21731     */
21732    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21733        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21734                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21735            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21736                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21737            try {
21738                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21739                        storageTarget);
21740            } catch (InstallerException e) {
21741                logCriticalInfo(Log.WARN,
21742                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21743            }
21744            return true;
21745        } else {
21746            return false;
21747        }
21748    }
21749
21750    public PackageFreezer freezePackage(String packageName, String killReason) {
21751        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21752    }
21753
21754    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21755        return new PackageFreezer(packageName, userId, killReason);
21756    }
21757
21758    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21759            String killReason) {
21760        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21761    }
21762
21763    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21764            String killReason) {
21765        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21766            return new PackageFreezer();
21767        } else {
21768            return freezePackage(packageName, userId, killReason);
21769        }
21770    }
21771
21772    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21773            String killReason) {
21774        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21775    }
21776
21777    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21778            String killReason) {
21779        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21780            return new PackageFreezer();
21781        } else {
21782            return freezePackage(packageName, userId, killReason);
21783        }
21784    }
21785
21786    /**
21787     * Class that freezes and kills the given package upon creation, and
21788     * unfreezes it upon closing. This is typically used when doing surgery on
21789     * app code/data to prevent the app from running while you're working.
21790     */
21791    private class PackageFreezer implements AutoCloseable {
21792        private final String mPackageName;
21793        private final PackageFreezer[] mChildren;
21794
21795        private final boolean mWeFroze;
21796
21797        private final AtomicBoolean mClosed = new AtomicBoolean();
21798        private final CloseGuard mCloseGuard = CloseGuard.get();
21799
21800        /**
21801         * Create and return a stub freezer that doesn't actually do anything,
21802         * typically used when someone requested
21803         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21804         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21805         */
21806        public PackageFreezer() {
21807            mPackageName = null;
21808            mChildren = null;
21809            mWeFroze = false;
21810            mCloseGuard.open("close");
21811        }
21812
21813        public PackageFreezer(String packageName, int userId, String killReason) {
21814            synchronized (mPackages) {
21815                mPackageName = packageName;
21816                mWeFroze = mFrozenPackages.add(mPackageName);
21817
21818                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21819                if (ps != null) {
21820                    killApplication(ps.name, ps.appId, userId, killReason);
21821                }
21822
21823                final PackageParser.Package p = mPackages.get(packageName);
21824                if (p != null && p.childPackages != null) {
21825                    final int N = p.childPackages.size();
21826                    mChildren = new PackageFreezer[N];
21827                    for (int i = 0; i < N; i++) {
21828                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21829                                userId, killReason);
21830                    }
21831                } else {
21832                    mChildren = null;
21833                }
21834            }
21835            mCloseGuard.open("close");
21836        }
21837
21838        @Override
21839        protected void finalize() throws Throwable {
21840            try {
21841                mCloseGuard.warnIfOpen();
21842                close();
21843            } finally {
21844                super.finalize();
21845            }
21846        }
21847
21848        @Override
21849        public void close() {
21850            mCloseGuard.close();
21851            if (mClosed.compareAndSet(false, true)) {
21852                synchronized (mPackages) {
21853                    if (mWeFroze) {
21854                        mFrozenPackages.remove(mPackageName);
21855                    }
21856
21857                    if (mChildren != null) {
21858                        for (PackageFreezer freezer : mChildren) {
21859                            freezer.close();
21860                        }
21861                    }
21862                }
21863            }
21864        }
21865    }
21866
21867    /**
21868     * Verify that given package is currently frozen.
21869     */
21870    private void checkPackageFrozen(String packageName) {
21871        synchronized (mPackages) {
21872            if (!mFrozenPackages.contains(packageName)) {
21873                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21874            }
21875        }
21876    }
21877
21878    @Override
21879    public int movePackage(final String packageName, final String volumeUuid) {
21880        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21881
21882        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21883        final int moveId = mNextMoveId.getAndIncrement();
21884        mHandler.post(new Runnable() {
21885            @Override
21886            public void run() {
21887                try {
21888                    movePackageInternal(packageName, volumeUuid, moveId, user);
21889                } catch (PackageManagerException e) {
21890                    Slog.w(TAG, "Failed to move " + packageName, e);
21891                    mMoveCallbacks.notifyStatusChanged(moveId,
21892                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21893                }
21894            }
21895        });
21896        return moveId;
21897    }
21898
21899    private void movePackageInternal(final String packageName, final String volumeUuid,
21900            final int moveId, UserHandle user) throws PackageManagerException {
21901        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21902        final PackageManager pm = mContext.getPackageManager();
21903
21904        final boolean currentAsec;
21905        final String currentVolumeUuid;
21906        final File codeFile;
21907        final String installerPackageName;
21908        final String packageAbiOverride;
21909        final int appId;
21910        final String seinfo;
21911        final String label;
21912        final int targetSdkVersion;
21913        final PackageFreezer freezer;
21914        final int[] installedUserIds;
21915
21916        // reader
21917        synchronized (mPackages) {
21918            final PackageParser.Package pkg = mPackages.get(packageName);
21919            final PackageSetting ps = mSettings.mPackages.get(packageName);
21920            if (pkg == null || ps == null) {
21921                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21922            }
21923
21924            if (pkg.applicationInfo.isSystemApp()) {
21925                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21926                        "Cannot move system application");
21927            }
21928
21929            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21930            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21931                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21932            if (isInternalStorage && !allow3rdPartyOnInternal) {
21933                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21934                        "3rd party apps are not allowed on internal storage");
21935            }
21936
21937            if (pkg.applicationInfo.isExternalAsec()) {
21938                currentAsec = true;
21939                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21940            } else if (pkg.applicationInfo.isForwardLocked()) {
21941                currentAsec = true;
21942                currentVolumeUuid = "forward_locked";
21943            } else {
21944                currentAsec = false;
21945                currentVolumeUuid = ps.volumeUuid;
21946
21947                final File probe = new File(pkg.codePath);
21948                final File probeOat = new File(probe, "oat");
21949                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21950                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21951                            "Move only supported for modern cluster style installs");
21952                }
21953            }
21954
21955            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21956                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21957                        "Package already moved to " + volumeUuid);
21958            }
21959            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21960                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21961                        "Device admin cannot be moved");
21962            }
21963
21964            if (mFrozenPackages.contains(packageName)) {
21965                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21966                        "Failed to move already frozen package");
21967            }
21968
21969            codeFile = new File(pkg.codePath);
21970            installerPackageName = ps.installerPackageName;
21971            packageAbiOverride = ps.cpuAbiOverrideString;
21972            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21973            seinfo = pkg.applicationInfo.seinfo;
21974            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21975            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21976            freezer = freezePackage(packageName, "movePackageInternal");
21977            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21978        }
21979
21980        final Bundle extras = new Bundle();
21981        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21982        extras.putString(Intent.EXTRA_TITLE, label);
21983        mMoveCallbacks.notifyCreated(moveId, extras);
21984
21985        int installFlags;
21986        final boolean moveCompleteApp;
21987        final File measurePath;
21988
21989        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21990            installFlags = INSTALL_INTERNAL;
21991            moveCompleteApp = !currentAsec;
21992            measurePath = Environment.getDataAppDirectory(volumeUuid);
21993        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21994            installFlags = INSTALL_EXTERNAL;
21995            moveCompleteApp = false;
21996            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21997        } else {
21998            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21999            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22000                    || !volume.isMountedWritable()) {
22001                freezer.close();
22002                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22003                        "Move location not mounted private volume");
22004            }
22005
22006            Preconditions.checkState(!currentAsec);
22007
22008            installFlags = INSTALL_INTERNAL;
22009            moveCompleteApp = true;
22010            measurePath = Environment.getDataAppDirectory(volumeUuid);
22011        }
22012
22013        final PackageStats stats = new PackageStats(null, -1);
22014        synchronized (mInstaller) {
22015            for (int userId : installedUserIds) {
22016                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22017                    freezer.close();
22018                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22019                            "Failed to measure package size");
22020                }
22021            }
22022        }
22023
22024        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22025                + stats.dataSize);
22026
22027        final long startFreeBytes = measurePath.getFreeSpace();
22028        final long sizeBytes;
22029        if (moveCompleteApp) {
22030            sizeBytes = stats.codeSize + stats.dataSize;
22031        } else {
22032            sizeBytes = stats.codeSize;
22033        }
22034
22035        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22036            freezer.close();
22037            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22038                    "Not enough free space to move");
22039        }
22040
22041        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22042
22043        final CountDownLatch installedLatch = new CountDownLatch(1);
22044        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22045            @Override
22046            public void onUserActionRequired(Intent intent) throws RemoteException {
22047                throw new IllegalStateException();
22048            }
22049
22050            @Override
22051            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22052                    Bundle extras) throws RemoteException {
22053                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22054                        + PackageManager.installStatusToString(returnCode, msg));
22055
22056                installedLatch.countDown();
22057                freezer.close();
22058
22059                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22060                switch (status) {
22061                    case PackageInstaller.STATUS_SUCCESS:
22062                        mMoveCallbacks.notifyStatusChanged(moveId,
22063                                PackageManager.MOVE_SUCCEEDED);
22064                        break;
22065                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22066                        mMoveCallbacks.notifyStatusChanged(moveId,
22067                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22068                        break;
22069                    default:
22070                        mMoveCallbacks.notifyStatusChanged(moveId,
22071                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22072                        break;
22073                }
22074            }
22075        };
22076
22077        final MoveInfo move;
22078        if (moveCompleteApp) {
22079            // Kick off a thread to report progress estimates
22080            new Thread() {
22081                @Override
22082                public void run() {
22083                    while (true) {
22084                        try {
22085                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22086                                break;
22087                            }
22088                        } catch (InterruptedException ignored) {
22089                        }
22090
22091                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22092                        final int progress = 10 + (int) MathUtils.constrain(
22093                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22094                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22095                    }
22096                }
22097            }.start();
22098
22099            final String dataAppName = codeFile.getName();
22100            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22101                    dataAppName, appId, seinfo, targetSdkVersion);
22102        } else {
22103            move = null;
22104        }
22105
22106        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22107
22108        final Message msg = mHandler.obtainMessage(INIT_COPY);
22109        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22110        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22111                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22112                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22113                PackageManager.INSTALL_REASON_UNKNOWN);
22114        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22115        msg.obj = params;
22116
22117        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22118                System.identityHashCode(msg.obj));
22119        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22120                System.identityHashCode(msg.obj));
22121
22122        mHandler.sendMessage(msg);
22123    }
22124
22125    @Override
22126    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22127        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22128
22129        final int realMoveId = mNextMoveId.getAndIncrement();
22130        final Bundle extras = new Bundle();
22131        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22132        mMoveCallbacks.notifyCreated(realMoveId, extras);
22133
22134        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22135            @Override
22136            public void onCreated(int moveId, Bundle extras) {
22137                // Ignored
22138            }
22139
22140            @Override
22141            public void onStatusChanged(int moveId, int status, long estMillis) {
22142                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22143            }
22144        };
22145
22146        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22147        storage.setPrimaryStorageUuid(volumeUuid, callback);
22148        return realMoveId;
22149    }
22150
22151    @Override
22152    public int getMoveStatus(int moveId) {
22153        mContext.enforceCallingOrSelfPermission(
22154                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22155        return mMoveCallbacks.mLastStatus.get(moveId);
22156    }
22157
22158    @Override
22159    public void registerMoveCallback(IPackageMoveObserver callback) {
22160        mContext.enforceCallingOrSelfPermission(
22161                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22162        mMoveCallbacks.register(callback);
22163    }
22164
22165    @Override
22166    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22167        mContext.enforceCallingOrSelfPermission(
22168                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22169        mMoveCallbacks.unregister(callback);
22170    }
22171
22172    @Override
22173    public boolean setInstallLocation(int loc) {
22174        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22175                null);
22176        if (getInstallLocation() == loc) {
22177            return true;
22178        }
22179        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22180                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22181            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22182                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22183            return true;
22184        }
22185        return false;
22186   }
22187
22188    @Override
22189    public int getInstallLocation() {
22190        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22191                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22192                PackageHelper.APP_INSTALL_AUTO);
22193    }
22194
22195    /** Called by UserManagerService */
22196    void cleanUpUser(UserManagerService userManager, int userHandle) {
22197        synchronized (mPackages) {
22198            mDirtyUsers.remove(userHandle);
22199            mUserNeedsBadging.delete(userHandle);
22200            mSettings.removeUserLPw(userHandle);
22201            mPendingBroadcasts.remove(userHandle);
22202            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
22203            removeUnusedPackagesLPw(userManager, userHandle);
22204        }
22205    }
22206
22207    /**
22208     * We're removing userHandle and would like to remove any downloaded packages
22209     * that are no longer in use by any other user.
22210     * @param userHandle the user being removed
22211     */
22212    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22213        final boolean DEBUG_CLEAN_APKS = false;
22214        int [] users = userManager.getUserIds();
22215        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22216        while (psit.hasNext()) {
22217            PackageSetting ps = psit.next();
22218            if (ps.pkg == null) {
22219                continue;
22220            }
22221            final String packageName = ps.pkg.packageName;
22222            // Skip over if system app
22223            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22224                continue;
22225            }
22226            if (DEBUG_CLEAN_APKS) {
22227                Slog.i(TAG, "Checking package " + packageName);
22228            }
22229            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22230            if (keep) {
22231                if (DEBUG_CLEAN_APKS) {
22232                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22233                }
22234            } else {
22235                for (int i = 0; i < users.length; i++) {
22236                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22237                        keep = true;
22238                        if (DEBUG_CLEAN_APKS) {
22239                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22240                                    + users[i]);
22241                        }
22242                        break;
22243                    }
22244                }
22245            }
22246            if (!keep) {
22247                if (DEBUG_CLEAN_APKS) {
22248                    Slog.i(TAG, "  Removing package " + packageName);
22249                }
22250                mHandler.post(new Runnable() {
22251                    public void run() {
22252                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22253                                userHandle, 0);
22254                    } //end run
22255                });
22256            }
22257        }
22258    }
22259
22260    /** Called by UserManagerService */
22261    void createNewUser(int userId, String[] disallowedPackages) {
22262        synchronized (mInstallLock) {
22263            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22264        }
22265        synchronized (mPackages) {
22266            scheduleWritePackageRestrictionsLocked(userId);
22267            scheduleWritePackageListLocked(userId);
22268            applyFactoryDefaultBrowserLPw(userId);
22269            primeDomainVerificationsLPw(userId);
22270        }
22271    }
22272
22273    void onNewUserCreated(final int userId) {
22274        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22275        // If permission review for legacy apps is required, we represent
22276        // dagerous permissions for such apps as always granted runtime
22277        // permissions to keep per user flag state whether review is needed.
22278        // Hence, if a new user is added we have to propagate dangerous
22279        // permission grants for these legacy apps.
22280        if (mPermissionReviewRequired) {
22281            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22282                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22283        }
22284    }
22285
22286    @Override
22287    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22288        mContext.enforceCallingOrSelfPermission(
22289                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22290                "Only package verification agents can read the verifier device identity");
22291
22292        synchronized (mPackages) {
22293            return mSettings.getVerifierDeviceIdentityLPw();
22294        }
22295    }
22296
22297    @Override
22298    public void setPermissionEnforced(String permission, boolean enforced) {
22299        // TODO: Now that we no longer change GID for storage, this should to away.
22300        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22301                "setPermissionEnforced");
22302        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22303            synchronized (mPackages) {
22304                if (mSettings.mReadExternalStorageEnforced == null
22305                        || mSettings.mReadExternalStorageEnforced != enforced) {
22306                    mSettings.mReadExternalStorageEnforced = enforced;
22307                    mSettings.writeLPr();
22308                }
22309            }
22310            // kill any non-foreground processes so we restart them and
22311            // grant/revoke the GID.
22312            final IActivityManager am = ActivityManager.getService();
22313            if (am != null) {
22314                final long token = Binder.clearCallingIdentity();
22315                try {
22316                    am.killProcessesBelowForeground("setPermissionEnforcement");
22317                } catch (RemoteException e) {
22318                } finally {
22319                    Binder.restoreCallingIdentity(token);
22320                }
22321            }
22322        } else {
22323            throw new IllegalArgumentException("No selective enforcement for " + permission);
22324        }
22325    }
22326
22327    @Override
22328    @Deprecated
22329    public boolean isPermissionEnforced(String permission) {
22330        return true;
22331    }
22332
22333    @Override
22334    public boolean isStorageLow() {
22335        final long token = Binder.clearCallingIdentity();
22336        try {
22337            final DeviceStorageMonitorInternal
22338                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22339            if (dsm != null) {
22340                return dsm.isMemoryLow();
22341            } else {
22342                return false;
22343            }
22344        } finally {
22345            Binder.restoreCallingIdentity(token);
22346        }
22347    }
22348
22349    @Override
22350    public IPackageInstaller getPackageInstaller() {
22351        return mInstallerService;
22352    }
22353
22354    private boolean userNeedsBadging(int userId) {
22355        int index = mUserNeedsBadging.indexOfKey(userId);
22356        if (index < 0) {
22357            final UserInfo userInfo;
22358            final long token = Binder.clearCallingIdentity();
22359            try {
22360                userInfo = sUserManager.getUserInfo(userId);
22361            } finally {
22362                Binder.restoreCallingIdentity(token);
22363            }
22364            final boolean b;
22365            if (userInfo != null && userInfo.isManagedProfile()) {
22366                b = true;
22367            } else {
22368                b = false;
22369            }
22370            mUserNeedsBadging.put(userId, b);
22371            return b;
22372        }
22373        return mUserNeedsBadging.valueAt(index);
22374    }
22375
22376    @Override
22377    public KeySet getKeySetByAlias(String packageName, String alias) {
22378        if (packageName == null || alias == null) {
22379            return null;
22380        }
22381        synchronized(mPackages) {
22382            final PackageParser.Package pkg = mPackages.get(packageName);
22383            if (pkg == null) {
22384                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22385                throw new IllegalArgumentException("Unknown package: " + packageName);
22386            }
22387            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22388            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22389        }
22390    }
22391
22392    @Override
22393    public KeySet getSigningKeySet(String packageName) {
22394        if (packageName == null) {
22395            return null;
22396        }
22397        synchronized(mPackages) {
22398            final PackageParser.Package pkg = mPackages.get(packageName);
22399            if (pkg == null) {
22400                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22401                throw new IllegalArgumentException("Unknown package: " + packageName);
22402            }
22403            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22404                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22405                throw new SecurityException("May not access signing KeySet of other apps.");
22406            }
22407            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22408            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22409        }
22410    }
22411
22412    @Override
22413    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22414        if (packageName == null || ks == null) {
22415            return false;
22416        }
22417        synchronized(mPackages) {
22418            final PackageParser.Package pkg = mPackages.get(packageName);
22419            if (pkg == null) {
22420                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22421                throw new IllegalArgumentException("Unknown package: " + packageName);
22422            }
22423            IBinder ksh = ks.getToken();
22424            if (ksh instanceof KeySetHandle) {
22425                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22426                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22427            }
22428            return false;
22429        }
22430    }
22431
22432    @Override
22433    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22434        if (packageName == null || ks == null) {
22435            return false;
22436        }
22437        synchronized(mPackages) {
22438            final PackageParser.Package pkg = mPackages.get(packageName);
22439            if (pkg == null) {
22440                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22441                throw new IllegalArgumentException("Unknown package: " + packageName);
22442            }
22443            IBinder ksh = ks.getToken();
22444            if (ksh instanceof KeySetHandle) {
22445                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22446                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22447            }
22448            return false;
22449        }
22450    }
22451
22452    private void deletePackageIfUnusedLPr(final String packageName) {
22453        PackageSetting ps = mSettings.mPackages.get(packageName);
22454        if (ps == null) {
22455            return;
22456        }
22457        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22458            // TODO Implement atomic delete if package is unused
22459            // It is currently possible that the package will be deleted even if it is installed
22460            // after this method returns.
22461            mHandler.post(new Runnable() {
22462                public void run() {
22463                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22464                            0, PackageManager.DELETE_ALL_USERS);
22465                }
22466            });
22467        }
22468    }
22469
22470    /**
22471     * Check and throw if the given before/after packages would be considered a
22472     * downgrade.
22473     */
22474    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22475            throws PackageManagerException {
22476        if (after.versionCode < before.mVersionCode) {
22477            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22478                    "Update version code " + after.versionCode + " is older than current "
22479                    + before.mVersionCode);
22480        } else if (after.versionCode == before.mVersionCode) {
22481            if (after.baseRevisionCode < before.baseRevisionCode) {
22482                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22483                        "Update base revision code " + after.baseRevisionCode
22484                        + " is older than current " + before.baseRevisionCode);
22485            }
22486
22487            if (!ArrayUtils.isEmpty(after.splitNames)) {
22488                for (int i = 0; i < after.splitNames.length; i++) {
22489                    final String splitName = after.splitNames[i];
22490                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22491                    if (j != -1) {
22492                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22493                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22494                                    "Update split " + splitName + " revision code "
22495                                    + after.splitRevisionCodes[i] + " is older than current "
22496                                    + before.splitRevisionCodes[j]);
22497                        }
22498                    }
22499                }
22500            }
22501        }
22502    }
22503
22504    private static class MoveCallbacks extends Handler {
22505        private static final int MSG_CREATED = 1;
22506        private static final int MSG_STATUS_CHANGED = 2;
22507
22508        private final RemoteCallbackList<IPackageMoveObserver>
22509                mCallbacks = new RemoteCallbackList<>();
22510
22511        private final SparseIntArray mLastStatus = new SparseIntArray();
22512
22513        public MoveCallbacks(Looper looper) {
22514            super(looper);
22515        }
22516
22517        public void register(IPackageMoveObserver callback) {
22518            mCallbacks.register(callback);
22519        }
22520
22521        public void unregister(IPackageMoveObserver callback) {
22522            mCallbacks.unregister(callback);
22523        }
22524
22525        @Override
22526        public void handleMessage(Message msg) {
22527            final SomeArgs args = (SomeArgs) msg.obj;
22528            final int n = mCallbacks.beginBroadcast();
22529            for (int i = 0; i < n; i++) {
22530                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22531                try {
22532                    invokeCallback(callback, msg.what, args);
22533                } catch (RemoteException ignored) {
22534                }
22535            }
22536            mCallbacks.finishBroadcast();
22537            args.recycle();
22538        }
22539
22540        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22541                throws RemoteException {
22542            switch (what) {
22543                case MSG_CREATED: {
22544                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22545                    break;
22546                }
22547                case MSG_STATUS_CHANGED: {
22548                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22549                    break;
22550                }
22551            }
22552        }
22553
22554        private void notifyCreated(int moveId, Bundle extras) {
22555            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22556
22557            final SomeArgs args = SomeArgs.obtain();
22558            args.argi1 = moveId;
22559            args.arg2 = extras;
22560            obtainMessage(MSG_CREATED, args).sendToTarget();
22561        }
22562
22563        private void notifyStatusChanged(int moveId, int status) {
22564            notifyStatusChanged(moveId, status, -1);
22565        }
22566
22567        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22568            Slog.v(TAG, "Move " + moveId + " status " + status);
22569
22570            final SomeArgs args = SomeArgs.obtain();
22571            args.argi1 = moveId;
22572            args.argi2 = status;
22573            args.arg3 = estMillis;
22574            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22575
22576            synchronized (mLastStatus) {
22577                mLastStatus.put(moveId, status);
22578            }
22579        }
22580    }
22581
22582    private final static class OnPermissionChangeListeners extends Handler {
22583        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22584
22585        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22586                new RemoteCallbackList<>();
22587
22588        public OnPermissionChangeListeners(Looper looper) {
22589            super(looper);
22590        }
22591
22592        @Override
22593        public void handleMessage(Message msg) {
22594            switch (msg.what) {
22595                case MSG_ON_PERMISSIONS_CHANGED: {
22596                    final int uid = msg.arg1;
22597                    handleOnPermissionsChanged(uid);
22598                } break;
22599            }
22600        }
22601
22602        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22603            mPermissionListeners.register(listener);
22604
22605        }
22606
22607        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22608            mPermissionListeners.unregister(listener);
22609        }
22610
22611        public void onPermissionsChanged(int uid) {
22612            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22613                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22614            }
22615        }
22616
22617        private void handleOnPermissionsChanged(int uid) {
22618            final int count = mPermissionListeners.beginBroadcast();
22619            try {
22620                for (int i = 0; i < count; i++) {
22621                    IOnPermissionsChangeListener callback = mPermissionListeners
22622                            .getBroadcastItem(i);
22623                    try {
22624                        callback.onPermissionsChanged(uid);
22625                    } catch (RemoteException e) {
22626                        Log.e(TAG, "Permission listener is dead", e);
22627                    }
22628                }
22629            } finally {
22630                mPermissionListeners.finishBroadcast();
22631            }
22632        }
22633    }
22634
22635    private class PackageManagerInternalImpl extends PackageManagerInternal {
22636        @Override
22637        public void setLocationPackagesProvider(PackagesProvider provider) {
22638            synchronized (mPackages) {
22639                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22640            }
22641        }
22642
22643        @Override
22644        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22645            synchronized (mPackages) {
22646                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22647            }
22648        }
22649
22650        @Override
22651        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22652            synchronized (mPackages) {
22653                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22654            }
22655        }
22656
22657        @Override
22658        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22659            synchronized (mPackages) {
22660                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22661            }
22662        }
22663
22664        @Override
22665        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22666            synchronized (mPackages) {
22667                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22668            }
22669        }
22670
22671        @Override
22672        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22673            synchronized (mPackages) {
22674                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22675            }
22676        }
22677
22678        @Override
22679        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22680            synchronized (mPackages) {
22681                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22682                        packageName, userId);
22683            }
22684        }
22685
22686        @Override
22687        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22688            synchronized (mPackages) {
22689                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22690                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22691                        packageName, userId);
22692            }
22693        }
22694
22695        @Override
22696        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22697            synchronized (mPackages) {
22698                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22699                        packageName, userId);
22700            }
22701        }
22702
22703        @Override
22704        public void setKeepUninstalledPackages(final List<String> packageList) {
22705            Preconditions.checkNotNull(packageList);
22706            List<String> removedFromList = null;
22707            synchronized (mPackages) {
22708                if (mKeepUninstalledPackages != null) {
22709                    final int packagesCount = mKeepUninstalledPackages.size();
22710                    for (int i = 0; i < packagesCount; i++) {
22711                        String oldPackage = mKeepUninstalledPackages.get(i);
22712                        if (packageList != null && packageList.contains(oldPackage)) {
22713                            continue;
22714                        }
22715                        if (removedFromList == null) {
22716                            removedFromList = new ArrayList<>();
22717                        }
22718                        removedFromList.add(oldPackage);
22719                    }
22720                }
22721                mKeepUninstalledPackages = new ArrayList<>(packageList);
22722                if (removedFromList != null) {
22723                    final int removedCount = removedFromList.size();
22724                    for (int i = 0; i < removedCount; i++) {
22725                        deletePackageIfUnusedLPr(removedFromList.get(i));
22726                    }
22727                }
22728            }
22729        }
22730
22731        @Override
22732        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22733            synchronized (mPackages) {
22734                // If we do not support permission review, done.
22735                if (!mPermissionReviewRequired) {
22736                    return false;
22737                }
22738
22739                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22740                if (packageSetting == null) {
22741                    return false;
22742                }
22743
22744                // Permission review applies only to apps not supporting the new permission model.
22745                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22746                    return false;
22747                }
22748
22749                // Legacy apps have the permission and get user consent on launch.
22750                PermissionsState permissionsState = packageSetting.getPermissionsState();
22751                return permissionsState.isPermissionReviewRequired(userId);
22752            }
22753        }
22754
22755        @Override
22756        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22757            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22758        }
22759
22760        @Override
22761        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22762                int userId) {
22763            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22764        }
22765
22766        @Override
22767        public void setDeviceAndProfileOwnerPackages(
22768                int deviceOwnerUserId, String deviceOwnerPackage,
22769                SparseArray<String> profileOwnerPackages) {
22770            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22771                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22772        }
22773
22774        @Override
22775        public boolean isPackageDataProtected(int userId, String packageName) {
22776            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22777        }
22778
22779        @Override
22780        public boolean isPackageEphemeral(int userId, String packageName) {
22781            synchronized (mPackages) {
22782                PackageParser.Package p = mPackages.get(packageName);
22783                return p != null ? p.applicationInfo.isEphemeralApp() : false;
22784            }
22785        }
22786
22787        @Override
22788        public boolean wasPackageEverLaunched(String packageName, int userId) {
22789            synchronized (mPackages) {
22790                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22791            }
22792        }
22793
22794        @Override
22795        public void grantRuntimePermission(String packageName, String name, int userId,
22796                boolean overridePolicy) {
22797            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22798                    overridePolicy);
22799        }
22800
22801        @Override
22802        public void revokeRuntimePermission(String packageName, String name, int userId,
22803                boolean overridePolicy) {
22804            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22805                    overridePolicy);
22806        }
22807
22808        @Override
22809        public String getNameForUid(int uid) {
22810            return PackageManagerService.this.getNameForUid(uid);
22811        }
22812
22813        @Override
22814        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22815                Intent origIntent, String resolvedType, Intent launchIntent,
22816                String callingPackage, int userId) {
22817            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22818                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22819        }
22820
22821        @Override
22822        public void grantEphemeralAccess(int userId, Intent intent,
22823                int targetAppId, int ephemeralAppId) {
22824            synchronized (mPackages) {
22825                mEphemeralApplicationRegistry.grantEphemeralAccessLPw(userId, intent,
22826                        targetAppId, ephemeralAppId);
22827            }
22828        }
22829
22830        public String getSetupWizardPackageName() {
22831            return mSetupWizardPackage;
22832        }
22833    }
22834
22835    @Override
22836    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22837        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22838        synchronized (mPackages) {
22839            final long identity = Binder.clearCallingIdentity();
22840            try {
22841                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22842                        packageNames, userId);
22843            } finally {
22844                Binder.restoreCallingIdentity(identity);
22845            }
22846        }
22847    }
22848
22849    private static void enforceSystemOrPhoneCaller(String tag) {
22850        int callingUid = Binder.getCallingUid();
22851        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22852            throw new SecurityException(
22853                    "Cannot call " + tag + " from UID " + callingUid);
22854        }
22855    }
22856
22857    boolean isHistoricalPackageUsageAvailable() {
22858        return mPackageUsage.isHistoricalPackageUsageAvailable();
22859    }
22860
22861    /**
22862     * Return a <b>copy</b> of the collection of packages known to the package manager.
22863     * @return A copy of the values of mPackages.
22864     */
22865    Collection<PackageParser.Package> getPackages() {
22866        synchronized (mPackages) {
22867            return new ArrayList<>(mPackages.values());
22868        }
22869    }
22870
22871    /**
22872     * Logs process start information (including base APK hash) to the security log.
22873     * @hide
22874     */
22875    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22876            String apkFile, int pid) {
22877        if (!SecurityLog.isLoggingEnabled()) {
22878            return;
22879        }
22880        Bundle data = new Bundle();
22881        data.putLong("startTimestamp", System.currentTimeMillis());
22882        data.putString("processName", processName);
22883        data.putInt("uid", uid);
22884        data.putString("seinfo", seinfo);
22885        data.putString("apkFile", apkFile);
22886        data.putInt("pid", pid);
22887        Message msg = mProcessLoggingHandler.obtainMessage(
22888                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22889        msg.setData(data);
22890        mProcessLoggingHandler.sendMessage(msg);
22891    }
22892
22893    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22894        return mCompilerStats.getPackageStats(pkgName);
22895    }
22896
22897    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22898        return getOrCreateCompilerPackageStats(pkg.packageName);
22899    }
22900
22901    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22902        return mCompilerStats.getOrCreatePackageStats(pkgName);
22903    }
22904
22905    public void deleteCompilerPackageStats(String pkgName) {
22906        mCompilerStats.deletePackageStats(pkgName);
22907    }
22908
22909    @Override
22910    public int getInstallReason(String packageName, int userId) {
22911        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22912                true /* requireFullPermission */, false /* checkShell */,
22913                "get install reason");
22914        synchronized (mPackages) {
22915            final PackageSetting ps = mSettings.mPackages.get(packageName);
22916            if (ps != null) {
22917                return ps.getInstallReason(userId);
22918            }
22919        }
22920        return PackageManager.INSTALL_REASON_UNKNOWN;
22921    }
22922}
22923