PackageManagerService.java revision 540dcb222e14522e037fd0c6b69b21f14ac92b24
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                    || mSharedLibraries.containsKey(pkg.packageName)) {
9396                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9397                        "Application package " + pkg.packageName
9398                        + " already installed.  Skipping duplicate.");
9399            }
9400
9401            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9402                // Static libs have a synthetic package name containing the version
9403                // but we still want the base name to be unique.
9404                if (mPackages.containsKey(pkg.manifestPackageName)) {
9405                    throw new PackageManagerException(
9406                            "Duplicate static shared lib provider package");
9407                }
9408
9409                // Static shared libraries should have at least O target SDK
9410                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9411                    throw new PackageManagerException(
9412                            "Packages declaring static-shared libs must target O SDK or higher");
9413                }
9414
9415                // Package declaring static a shared lib cannot be ephemeral
9416                if (pkg.applicationInfo.isEphemeralApp()) {
9417                    throw new PackageManagerException(
9418                            "Packages declaring static-shared libs cannot be ephemeral");
9419                }
9420
9421                // Package declaring static a shared lib cannot be renamed since the package
9422                // name is synthetic and apps can't code around package manager internals.
9423                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9424                    throw new PackageManagerException(
9425                            "Packages declaring static-shared libs cannot be renamed");
9426                }
9427
9428                // Package declaring static a shared lib cannot declare child packages
9429                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9430                    throw new PackageManagerException(
9431                            "Packages declaring static-shared libs cannot have child packages");
9432                }
9433
9434                // Package declaring static a shared lib cannot declare dynamic libs
9435                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9436                    throw new PackageManagerException(
9437                            "Packages declaring static-shared libs cannot declare dynamic libs");
9438                }
9439
9440                // Package declaring static a shared lib cannot declare shared users
9441                if (pkg.mSharedUserId != null) {
9442                    throw new PackageManagerException(
9443                            "Packages declaring static-shared libs cannot declare shared users");
9444                }
9445
9446                // Static shared libs cannot declare activities
9447                if (!pkg.activities.isEmpty()) {
9448                    throw new PackageManagerException(
9449                            "Static shared libs cannot declare activities");
9450                }
9451
9452                // Static shared libs cannot declare services
9453                if (!pkg.services.isEmpty()) {
9454                    throw new PackageManagerException(
9455                            "Static shared libs cannot declare services");
9456                }
9457
9458                // Static shared libs cannot declare providers
9459                if (!pkg.providers.isEmpty()) {
9460                    throw new PackageManagerException(
9461                            "Static shared libs cannot declare content providers");
9462                }
9463
9464                // Static shared libs cannot declare receivers
9465                if (!pkg.receivers.isEmpty()) {
9466                    throw new PackageManagerException(
9467                            "Static shared libs cannot declare broadcast receivers");
9468                }
9469
9470                // Static shared libs cannot declare permission groups
9471                if (!pkg.permissionGroups.isEmpty()) {
9472                    throw new PackageManagerException(
9473                            "Static shared libs cannot declare permission groups");
9474                }
9475
9476                // Static shared libs cannot declare permissions
9477                if (!pkg.permissions.isEmpty()) {
9478                    throw new PackageManagerException(
9479                            "Static shared libs cannot declare permissions");
9480                }
9481
9482                // Static shared libs cannot declare protected broadcasts
9483                if (pkg.protectedBroadcasts != null) {
9484                    throw new PackageManagerException(
9485                            "Static shared libs cannot declare protected broadcasts");
9486                }
9487
9488                // Static shared libs cannot be overlay targets
9489                if (pkg.mOverlayTarget != null) {
9490                    throw new PackageManagerException(
9491                            "Static shared libs cannot be overlay targets");
9492                }
9493
9494                // The version codes must be ordered as lib versions
9495                int minVersionCode = Integer.MIN_VALUE;
9496                int maxVersionCode = Integer.MAX_VALUE;
9497
9498                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9499                        pkg.staticSharedLibName);
9500                if (versionedLib != null) {
9501                    final int versionCount = versionedLib.size();
9502                    for (int i = 0; i < versionCount; i++) {
9503                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9504                        // TODO: We will change version code to long, so in the new API it is long
9505                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9506                                .getVersionCode();
9507                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9508                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9509                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9510                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9511                        } else {
9512                            minVersionCode = maxVersionCode = libVersionCode;
9513                            break;
9514                        }
9515                    }
9516                }
9517                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9518                    throw new PackageManagerException("Static shared"
9519                            + " lib version codes must be ordered as lib versions");
9520                }
9521            }
9522
9523            // Only privileged apps and updated privileged apps can add child packages.
9524            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9525                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9526                    throw new PackageManagerException("Only privileged apps can add child "
9527                            + "packages. Ignoring package " + pkg.packageName);
9528                }
9529                final int childCount = pkg.childPackages.size();
9530                for (int i = 0; i < childCount; i++) {
9531                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9532                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9533                            childPkg.packageName)) {
9534                        throw new PackageManagerException("Can't override child of "
9535                                + "another disabled app. Ignoring package " + pkg.packageName);
9536                    }
9537                }
9538            }
9539
9540            // If we're only installing presumed-existing packages, require that the
9541            // scanned APK is both already known and at the path previously established
9542            // for it.  Previously unknown packages we pick up normally, but if we have an
9543            // a priori expectation about this package's install presence, enforce it.
9544            // With a singular exception for new system packages. When an OTA contains
9545            // a new system package, we allow the codepath to change from a system location
9546            // to the user-installed location. If we don't allow this change, any newer,
9547            // user-installed version of the application will be ignored.
9548            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9549                if (mExpectingBetter.containsKey(pkg.packageName)) {
9550                    logCriticalInfo(Log.WARN,
9551                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9552                } else {
9553                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9554                    if (known != null) {
9555                        if (DEBUG_PACKAGE_SCANNING) {
9556                            Log.d(TAG, "Examining " + pkg.codePath
9557                                    + " and requiring known paths " + known.codePathString
9558                                    + " & " + known.resourcePathString);
9559                        }
9560                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9561                                || !pkg.applicationInfo.getResourcePath().equals(
9562                                        known.resourcePathString)) {
9563                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9564                                    "Application package " + pkg.packageName
9565                                    + " found at " + pkg.applicationInfo.getCodePath()
9566                                    + " but expected at " + known.codePathString
9567                                    + "; ignoring.");
9568                        }
9569                    }
9570                }
9571            }
9572
9573            // Verify that this new package doesn't have any content providers
9574            // that conflict with existing packages.  Only do this if the
9575            // package isn't already installed, since we don't want to break
9576            // things that are installed.
9577            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9578                final int N = pkg.providers.size();
9579                int i;
9580                for (i=0; i<N; i++) {
9581                    PackageParser.Provider p = pkg.providers.get(i);
9582                    if (p.info.authority != null) {
9583                        String names[] = p.info.authority.split(";");
9584                        for (int j = 0; j < names.length; j++) {
9585                            if (mProvidersByAuthority.containsKey(names[j])) {
9586                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9587                                final String otherPackageName =
9588                                        ((other != null && other.getComponentName() != null) ?
9589                                                other.getComponentName().getPackageName() : "?");
9590                                throw new PackageManagerException(
9591                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9592                                        "Can't install because provider name " + names[j]
9593                                                + " (in package " + pkg.applicationInfo.packageName
9594                                                + ") is already used by " + otherPackageName);
9595                            }
9596                        }
9597                    }
9598                }
9599            }
9600        }
9601    }
9602
9603    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9604            int type, String declaringPackageName, int declaringVersionCode) {
9605        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9606        if (versionedLib == null) {
9607            versionedLib = new SparseArray<>();
9608            mSharedLibraries.put(name, versionedLib);
9609            if (type == SharedLibraryInfo.TYPE_STATIC) {
9610                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9611            }
9612        } else if (versionedLib.indexOfKey(version) >= 0) {
9613            return false;
9614        }
9615        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9616                version, type, declaringPackageName, declaringVersionCode);
9617        versionedLib.put(version, libEntry);
9618        return true;
9619    }
9620
9621    private boolean removeSharedLibraryLPw(String name, int version) {
9622        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9623        if (versionedLib == null) {
9624            return false;
9625        }
9626        final int libIdx = versionedLib.indexOfKey(version);
9627        if (libIdx < 0) {
9628            return false;
9629        }
9630        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9631        versionedLib.remove(version);
9632        if (versionedLib.size() <= 0) {
9633            mSharedLibraries.remove(name);
9634            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9635                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9636                        .getPackageName());
9637            }
9638        }
9639        return true;
9640    }
9641
9642    /**
9643     * Adds a scanned package to the system. When this method is finished, the package will
9644     * be available for query, resolution, etc...
9645     */
9646    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9647            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9648        final String pkgName = pkg.packageName;
9649        if (mCustomResolverComponentName != null &&
9650                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9651            setUpCustomResolverActivity(pkg);
9652        }
9653
9654        if (pkg.packageName.equals("android")) {
9655            synchronized (mPackages) {
9656                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9657                    // Set up information for our fall-back user intent resolution activity.
9658                    mPlatformPackage = pkg;
9659                    pkg.mVersionCode = mSdkVersion;
9660                    mAndroidApplication = pkg.applicationInfo;
9661
9662                    if (!mResolverReplaced) {
9663                        mResolveActivity.applicationInfo = mAndroidApplication;
9664                        mResolveActivity.name = ResolverActivity.class.getName();
9665                        mResolveActivity.packageName = mAndroidApplication.packageName;
9666                        mResolveActivity.processName = "system:ui";
9667                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9668                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9669                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9670                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9671                        mResolveActivity.exported = true;
9672                        mResolveActivity.enabled = true;
9673                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9674                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9675                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9676                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9677                                | ActivityInfo.CONFIG_ORIENTATION
9678                                | ActivityInfo.CONFIG_KEYBOARD
9679                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9680                        mResolveInfo.activityInfo = mResolveActivity;
9681                        mResolveInfo.priority = 0;
9682                        mResolveInfo.preferredOrder = 0;
9683                        mResolveInfo.match = 0;
9684                        mResolveComponentName = new ComponentName(
9685                                mAndroidApplication.packageName, mResolveActivity.name);
9686                    }
9687                }
9688            }
9689        }
9690
9691        ArrayList<PackageParser.Package> clientLibPkgs = null;
9692        // writer
9693        synchronized (mPackages) {
9694            boolean hasStaticSharedLibs = false;
9695
9696            // Any app can add new static shared libraries
9697            if (pkg.staticSharedLibName != null) {
9698                // Static shared libs don't allow renaming as they have synthetic package
9699                // names to allow install of multiple versions, so use name from manifest.
9700                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9701                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9702                        pkg.manifestPackageName, pkg.mVersionCode)) {
9703                    hasStaticSharedLibs = true;
9704                } else {
9705                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9706                                + pkg.staticSharedLibName + " already exists; skipping");
9707                }
9708                // Static shared libs cannot be updated once installed since they
9709                // use synthetic package name which includes the version code, so
9710                // not need to update other packages's shared lib dependencies.
9711            }
9712
9713            if (!hasStaticSharedLibs
9714                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9715                // Only system apps can add new dynamic shared libraries.
9716                if (pkg.libraryNames != null) {
9717                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9718                        String name = pkg.libraryNames.get(i);
9719                        boolean allowed = false;
9720                        if (pkg.isUpdatedSystemApp()) {
9721                            // New library entries can only be added through the
9722                            // system image.  This is important to get rid of a lot
9723                            // of nasty edge cases: for example if we allowed a non-
9724                            // system update of the app to add a library, then uninstalling
9725                            // the update would make the library go away, and assumptions
9726                            // we made such as through app install filtering would now
9727                            // have allowed apps on the device which aren't compatible
9728                            // with it.  Better to just have the restriction here, be
9729                            // conservative, and create many fewer cases that can negatively
9730                            // impact the user experience.
9731                            final PackageSetting sysPs = mSettings
9732                                    .getDisabledSystemPkgLPr(pkg.packageName);
9733                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9734                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9735                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9736                                        allowed = true;
9737                                        break;
9738                                    }
9739                                }
9740                            }
9741                        } else {
9742                            allowed = true;
9743                        }
9744                        if (allowed) {
9745                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9746                                    SharedLibraryInfo.VERSION_UNDEFINED,
9747                                    SharedLibraryInfo.TYPE_DYNAMIC,
9748                                    pkg.packageName, pkg.mVersionCode)) {
9749                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9750                                        + name + " already exists; skipping");
9751                            }
9752                        } else {
9753                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9754                                    + name + " that is not declared on system image; skipping");
9755                        }
9756                    }
9757
9758                    if ((scanFlags & SCAN_BOOTING) == 0) {
9759                        // If we are not booting, we need to update any applications
9760                        // that are clients of our shared library.  If we are booting,
9761                        // this will all be done once the scan is complete.
9762                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9763                    }
9764                }
9765            }
9766        }
9767
9768        if ((scanFlags & SCAN_BOOTING) != 0) {
9769            // No apps can run during boot scan, so they don't need to be frozen
9770        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9771            // Caller asked to not kill app, so it's probably not frozen
9772        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9773            // Caller asked us to ignore frozen check for some reason; they
9774            // probably didn't know the package name
9775        } else {
9776            // We're doing major surgery on this package, so it better be frozen
9777            // right now to keep it from launching
9778            checkPackageFrozen(pkgName);
9779        }
9780
9781        // Also need to kill any apps that are dependent on the library.
9782        if (clientLibPkgs != null) {
9783            for (int i=0; i<clientLibPkgs.size(); i++) {
9784                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9785                killApplication(clientPkg.applicationInfo.packageName,
9786                        clientPkg.applicationInfo.uid, "update lib");
9787            }
9788        }
9789
9790        // writer
9791        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9792
9793        boolean createIdmapFailed = false;
9794        synchronized (mPackages) {
9795            // We don't expect installation to fail beyond this point
9796
9797            if (pkgSetting.pkg != null) {
9798                // Note that |user| might be null during the initial boot scan. If a codePath
9799                // for an app has changed during a boot scan, it's due to an app update that's
9800                // part of the system partition and marker changes must be applied to all users.
9801                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9802                final int[] userIds = resolveUserIds(userId);
9803                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9804            }
9805
9806            // Add the new setting to mSettings
9807            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9808            // Add the new setting to mPackages
9809            mPackages.put(pkg.applicationInfo.packageName, pkg);
9810            // Make sure we don't accidentally delete its data.
9811            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9812            while (iter.hasNext()) {
9813                PackageCleanItem item = iter.next();
9814                if (pkgName.equals(item.packageName)) {
9815                    iter.remove();
9816                }
9817            }
9818
9819            // Add the package's KeySets to the global KeySetManagerService
9820            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9821            ksms.addScannedPackageLPw(pkg);
9822
9823            int N = pkg.providers.size();
9824            StringBuilder r = null;
9825            int i;
9826            for (i=0; i<N; i++) {
9827                PackageParser.Provider p = pkg.providers.get(i);
9828                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9829                        p.info.processName);
9830                mProviders.addProvider(p);
9831                p.syncable = p.info.isSyncable;
9832                if (p.info.authority != null) {
9833                    String names[] = p.info.authority.split(";");
9834                    p.info.authority = null;
9835                    for (int j = 0; j < names.length; j++) {
9836                        if (j == 1 && p.syncable) {
9837                            // We only want the first authority for a provider to possibly be
9838                            // syncable, so if we already added this provider using a different
9839                            // authority clear the syncable flag. We copy the provider before
9840                            // changing it because the mProviders object contains a reference
9841                            // to a provider that we don't want to change.
9842                            // Only do this for the second authority since the resulting provider
9843                            // object can be the same for all future authorities for this provider.
9844                            p = new PackageParser.Provider(p);
9845                            p.syncable = false;
9846                        }
9847                        if (!mProvidersByAuthority.containsKey(names[j])) {
9848                            mProvidersByAuthority.put(names[j], p);
9849                            if (p.info.authority == null) {
9850                                p.info.authority = names[j];
9851                            } else {
9852                                p.info.authority = p.info.authority + ";" + names[j];
9853                            }
9854                            if (DEBUG_PACKAGE_SCANNING) {
9855                                if (chatty)
9856                                    Log.d(TAG, "Registered content provider: " + names[j]
9857                                            + ", className = " + p.info.name + ", isSyncable = "
9858                                            + p.info.isSyncable);
9859                            }
9860                        } else {
9861                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9862                            Slog.w(TAG, "Skipping provider name " + names[j] +
9863                                    " (in package " + pkg.applicationInfo.packageName +
9864                                    "): name already used by "
9865                                    + ((other != null && other.getComponentName() != null)
9866                                            ? other.getComponentName().getPackageName() : "?"));
9867                        }
9868                    }
9869                }
9870                if (chatty) {
9871                    if (r == null) {
9872                        r = new StringBuilder(256);
9873                    } else {
9874                        r.append(' ');
9875                    }
9876                    r.append(p.info.name);
9877                }
9878            }
9879            if (r != null) {
9880                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9881            }
9882
9883            N = pkg.services.size();
9884            r = null;
9885            for (i=0; i<N; i++) {
9886                PackageParser.Service s = pkg.services.get(i);
9887                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9888                        s.info.processName);
9889                mServices.addService(s);
9890                if (chatty) {
9891                    if (r == null) {
9892                        r = new StringBuilder(256);
9893                    } else {
9894                        r.append(' ');
9895                    }
9896                    r.append(s.info.name);
9897                }
9898            }
9899            if (r != null) {
9900                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9901            }
9902
9903            N = pkg.receivers.size();
9904            r = null;
9905            for (i=0; i<N; i++) {
9906                PackageParser.Activity a = pkg.receivers.get(i);
9907                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9908                        a.info.processName);
9909                mReceivers.addActivity(a, "receiver");
9910                if (chatty) {
9911                    if (r == null) {
9912                        r = new StringBuilder(256);
9913                    } else {
9914                        r.append(' ');
9915                    }
9916                    r.append(a.info.name);
9917                }
9918            }
9919            if (r != null) {
9920                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9921            }
9922
9923            N = pkg.activities.size();
9924            r = null;
9925            for (i=0; i<N; i++) {
9926                PackageParser.Activity a = pkg.activities.get(i);
9927                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9928                        a.info.processName);
9929                mActivities.addActivity(a, "activity");
9930                if (chatty) {
9931                    if (r == null) {
9932                        r = new StringBuilder(256);
9933                    } else {
9934                        r.append(' ');
9935                    }
9936                    r.append(a.info.name);
9937                }
9938            }
9939            if (r != null) {
9940                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9941            }
9942
9943            N = pkg.permissionGroups.size();
9944            r = null;
9945            for (i=0; i<N; i++) {
9946                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9947                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9948                final String curPackageName = cur == null ? null : cur.info.packageName;
9949                // Dont allow ephemeral apps to define new permission groups.
9950                if (pkg.applicationInfo.isEphemeralApp()) {
9951                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9952                            + pg.info.packageName
9953                            + " ignored: ephemeral apps cannot define new permission groups.");
9954                    continue;
9955                }
9956                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9957                if (cur == null || isPackageUpdate) {
9958                    mPermissionGroups.put(pg.info.name, pg);
9959                    if (chatty) {
9960                        if (r == null) {
9961                            r = new StringBuilder(256);
9962                        } else {
9963                            r.append(' ');
9964                        }
9965                        if (isPackageUpdate) {
9966                            r.append("UPD:");
9967                        }
9968                        r.append(pg.info.name);
9969                    }
9970                } else {
9971                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9972                            + pg.info.packageName + " ignored: original from "
9973                            + cur.info.packageName);
9974                    if (chatty) {
9975                        if (r == null) {
9976                            r = new StringBuilder(256);
9977                        } else {
9978                            r.append(' ');
9979                        }
9980                        r.append("DUP:");
9981                        r.append(pg.info.name);
9982                    }
9983                }
9984            }
9985            if (r != null) {
9986                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9987            }
9988
9989            N = pkg.permissions.size();
9990            r = null;
9991            for (i=0; i<N; i++) {
9992                PackageParser.Permission p = pkg.permissions.get(i);
9993
9994                // Dont allow ephemeral apps to define new permissions.
9995                if (pkg.applicationInfo.isEphemeralApp()) {
9996                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9997                            + p.info.packageName
9998                            + " ignored: ephemeral apps cannot define new permissions.");
9999                    continue;
10000                }
10001
10002                // Assume by default that we did not install this permission into the system.
10003                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10004
10005                // Now that permission groups have a special meaning, we ignore permission
10006                // groups for legacy apps to prevent unexpected behavior. In particular,
10007                // permissions for one app being granted to someone just becase they happen
10008                // to be in a group defined by another app (before this had no implications).
10009                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10010                    p.group = mPermissionGroups.get(p.info.group);
10011                    // Warn for a permission in an unknown group.
10012                    if (p.info.group != null && p.group == null) {
10013                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10014                                + p.info.packageName + " in an unknown group " + p.info.group);
10015                    }
10016                }
10017
10018                ArrayMap<String, BasePermission> permissionMap =
10019                        p.tree ? mSettings.mPermissionTrees
10020                                : mSettings.mPermissions;
10021                BasePermission bp = permissionMap.get(p.info.name);
10022
10023                // Allow system apps to redefine non-system permissions
10024                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10025                    final boolean currentOwnerIsSystem = (bp.perm != null
10026                            && isSystemApp(bp.perm.owner));
10027                    if (isSystemApp(p.owner)) {
10028                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10029                            // It's a built-in permission and no owner, take ownership now
10030                            bp.packageSetting = pkgSetting;
10031                            bp.perm = p;
10032                            bp.uid = pkg.applicationInfo.uid;
10033                            bp.sourcePackage = p.info.packageName;
10034                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10035                        } else if (!currentOwnerIsSystem) {
10036                            String msg = "New decl " + p.owner + " of permission  "
10037                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10038                            reportSettingsProblem(Log.WARN, msg);
10039                            bp = null;
10040                        }
10041                    }
10042                }
10043
10044                if (bp == null) {
10045                    bp = new BasePermission(p.info.name, p.info.packageName,
10046                            BasePermission.TYPE_NORMAL);
10047                    permissionMap.put(p.info.name, bp);
10048                }
10049
10050                if (bp.perm == null) {
10051                    if (bp.sourcePackage == null
10052                            || bp.sourcePackage.equals(p.info.packageName)) {
10053                        BasePermission tree = findPermissionTreeLP(p.info.name);
10054                        if (tree == null
10055                                || tree.sourcePackage.equals(p.info.packageName)) {
10056                            bp.packageSetting = pkgSetting;
10057                            bp.perm = p;
10058                            bp.uid = pkg.applicationInfo.uid;
10059                            bp.sourcePackage = p.info.packageName;
10060                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10061                            if (chatty) {
10062                                if (r == null) {
10063                                    r = new StringBuilder(256);
10064                                } else {
10065                                    r.append(' ');
10066                                }
10067                                r.append(p.info.name);
10068                            }
10069                        } else {
10070                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10071                                    + p.info.packageName + " ignored: base tree "
10072                                    + tree.name + " is from package "
10073                                    + tree.sourcePackage);
10074                        }
10075                    } else {
10076                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10077                                + p.info.packageName + " ignored: original from "
10078                                + bp.sourcePackage);
10079                    }
10080                } else if (chatty) {
10081                    if (r == null) {
10082                        r = new StringBuilder(256);
10083                    } else {
10084                        r.append(' ');
10085                    }
10086                    r.append("DUP:");
10087                    r.append(p.info.name);
10088                }
10089                if (bp.perm == p) {
10090                    bp.protectionLevel = p.info.protectionLevel;
10091                }
10092            }
10093
10094            if (r != null) {
10095                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10096            }
10097
10098            N = pkg.instrumentation.size();
10099            r = null;
10100            for (i=0; i<N; i++) {
10101                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10102                a.info.packageName = pkg.applicationInfo.packageName;
10103                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10104                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10105                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10106                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10107                a.info.dataDir = pkg.applicationInfo.dataDir;
10108                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10109                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10110                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10111                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10112                mInstrumentation.put(a.getComponentName(), a);
10113                if (chatty) {
10114                    if (r == null) {
10115                        r = new StringBuilder(256);
10116                    } else {
10117                        r.append(' ');
10118                    }
10119                    r.append(a.info.name);
10120                }
10121            }
10122            if (r != null) {
10123                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10124            }
10125
10126            if (pkg.protectedBroadcasts != null) {
10127                N = pkg.protectedBroadcasts.size();
10128                for (i=0; i<N; i++) {
10129                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10130                }
10131            }
10132
10133            // Create idmap files for pairs of (packages, overlay packages).
10134            // Note: "android", ie framework-res.apk, is handled by native layers.
10135            if (pkg.mOverlayTarget != null) {
10136                // This is an overlay package.
10137                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10138                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10139                        mOverlays.put(pkg.mOverlayTarget,
10140                                new ArrayMap<String, PackageParser.Package>());
10141                    }
10142                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10143                    map.put(pkg.packageName, pkg);
10144                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10145                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10146                        createIdmapFailed = true;
10147                    }
10148                }
10149            } else if (mOverlays.containsKey(pkg.packageName) &&
10150                    !pkg.packageName.equals("android")) {
10151                // This is a regular package, with one or more known overlay packages.
10152                createIdmapsForPackageLI(pkg);
10153            }
10154        }
10155
10156        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10157
10158        if (createIdmapFailed) {
10159            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10160                    "scanPackageLI failed to createIdmap");
10161        }
10162    }
10163
10164    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10165            PackageParser.Package update, int[] userIds) {
10166        if (existing.applicationInfo == null || update.applicationInfo == null) {
10167            // This isn't due to an app installation.
10168            return;
10169        }
10170
10171        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10172        final File newCodePath = new File(update.applicationInfo.getCodePath());
10173
10174        // The codePath hasn't changed, so there's nothing for us to do.
10175        if (Objects.equals(oldCodePath, newCodePath)) {
10176            return;
10177        }
10178
10179        File canonicalNewCodePath;
10180        try {
10181            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10182        } catch (IOException e) {
10183            Slog.w(TAG, "Failed to get canonical path.", e);
10184            return;
10185        }
10186
10187        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10188        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10189        // that the last component of the path (i.e, the name) doesn't need canonicalization
10190        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10191        // but may change in the future. Hopefully this function won't exist at that point.
10192        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10193                oldCodePath.getName());
10194
10195        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10196        // with "@".
10197        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10198        if (!oldMarkerPrefix.endsWith("@")) {
10199            oldMarkerPrefix += "@";
10200        }
10201        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10202        if (!newMarkerPrefix.endsWith("@")) {
10203            newMarkerPrefix += "@";
10204        }
10205
10206        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10207        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10208        for (String updatedPath : updatedPaths) {
10209            String updatedPathName = new File(updatedPath).getName();
10210            markerSuffixes.add(updatedPathName.replace('/', '@'));
10211        }
10212
10213        for (int userId : userIds) {
10214            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10215
10216            for (String markerSuffix : markerSuffixes) {
10217                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10218                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10219                if (oldForeignUseMark.exists()) {
10220                    try {
10221                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10222                                newForeignUseMark.getAbsolutePath());
10223                    } catch (ErrnoException e) {
10224                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10225                        oldForeignUseMark.delete();
10226                    }
10227                }
10228            }
10229        }
10230    }
10231
10232    /**
10233     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10234     * is derived purely on the basis of the contents of {@code scanFile} and
10235     * {@code cpuAbiOverride}.
10236     *
10237     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10238     */
10239    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10240                                 String cpuAbiOverride, boolean extractLibs,
10241                                 File appLib32InstallDir)
10242            throws PackageManagerException {
10243        // Give ourselves some initial paths; we'll come back for another
10244        // pass once we've determined ABI below.
10245        setNativeLibraryPaths(pkg, appLib32InstallDir);
10246
10247        // We would never need to extract libs for forward-locked and external packages,
10248        // since the container service will do it for us. We shouldn't attempt to
10249        // extract libs from system app when it was not updated.
10250        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10251                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10252            extractLibs = false;
10253        }
10254
10255        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10256        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10257
10258        NativeLibraryHelper.Handle handle = null;
10259        try {
10260            handle = NativeLibraryHelper.Handle.create(pkg);
10261            // TODO(multiArch): This can be null for apps that didn't go through the
10262            // usual installation process. We can calculate it again, like we
10263            // do during install time.
10264            //
10265            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10266            // unnecessary.
10267            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10268
10269            // Null out the abis so that they can be recalculated.
10270            pkg.applicationInfo.primaryCpuAbi = null;
10271            pkg.applicationInfo.secondaryCpuAbi = null;
10272            if (isMultiArch(pkg.applicationInfo)) {
10273                // Warn if we've set an abiOverride for multi-lib packages..
10274                // By definition, we need to copy both 32 and 64 bit libraries for
10275                // such packages.
10276                if (pkg.cpuAbiOverride != null
10277                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10278                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10279                }
10280
10281                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10282                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10283                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10284                    if (extractLibs) {
10285                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10286                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10287                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10288                                useIsaSpecificSubdirs);
10289                    } else {
10290                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10291                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10292                    }
10293                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10294                }
10295
10296                maybeThrowExceptionForMultiArchCopy(
10297                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10298
10299                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10300                    if (extractLibs) {
10301                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10302                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10303                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10304                                useIsaSpecificSubdirs);
10305                    } else {
10306                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10307                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10308                    }
10309                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10310                }
10311
10312                maybeThrowExceptionForMultiArchCopy(
10313                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10314
10315                if (abi64 >= 0) {
10316                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10317                }
10318
10319                if (abi32 >= 0) {
10320                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10321                    if (abi64 >= 0) {
10322                        if (pkg.use32bitAbi) {
10323                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10324                            pkg.applicationInfo.primaryCpuAbi = abi;
10325                        } else {
10326                            pkg.applicationInfo.secondaryCpuAbi = abi;
10327                        }
10328                    } else {
10329                        pkg.applicationInfo.primaryCpuAbi = abi;
10330                    }
10331                }
10332
10333            } else {
10334                String[] abiList = (cpuAbiOverride != null) ?
10335                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10336
10337                // Enable gross and lame hacks for apps that are built with old
10338                // SDK tools. We must scan their APKs for renderscript bitcode and
10339                // not launch them if it's present. Don't bother checking on devices
10340                // that don't have 64 bit support.
10341                boolean needsRenderScriptOverride = false;
10342                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10343                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10344                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10345                    needsRenderScriptOverride = true;
10346                }
10347
10348                final int copyRet;
10349                if (extractLibs) {
10350                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10351                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10352                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10353                } else {
10354                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10355                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10356                }
10357                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10358
10359                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10360                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10361                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10362                }
10363
10364                if (copyRet >= 0) {
10365                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10366                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10367                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10368                } else if (needsRenderScriptOverride) {
10369                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10370                }
10371            }
10372        } catch (IOException ioe) {
10373            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10374        } finally {
10375            IoUtils.closeQuietly(handle);
10376        }
10377
10378        // Now that we've calculated the ABIs and determined if it's an internal app,
10379        // we will go ahead and populate the nativeLibraryPath.
10380        setNativeLibraryPaths(pkg, appLib32InstallDir);
10381    }
10382
10383    /**
10384     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10385     * i.e, so that all packages can be run inside a single process if required.
10386     *
10387     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10388     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10389     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10390     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10391     * updating a package that belongs to a shared user.
10392     *
10393     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10394     * adds unnecessary complexity.
10395     */
10396    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10397            PackageParser.Package scannedPackage) {
10398        String requiredInstructionSet = null;
10399        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10400            requiredInstructionSet = VMRuntime.getInstructionSet(
10401                     scannedPackage.applicationInfo.primaryCpuAbi);
10402        }
10403
10404        PackageSetting requirer = null;
10405        for (PackageSetting ps : packagesForUser) {
10406            // If packagesForUser contains scannedPackage, we skip it. This will happen
10407            // when scannedPackage is an update of an existing package. Without this check,
10408            // we will never be able to change the ABI of any package belonging to a shared
10409            // user, even if it's compatible with other packages.
10410            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10411                if (ps.primaryCpuAbiString == null) {
10412                    continue;
10413                }
10414
10415                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10416                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10417                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10418                    // this but there's not much we can do.
10419                    String errorMessage = "Instruction set mismatch, "
10420                            + ((requirer == null) ? "[caller]" : requirer)
10421                            + " requires " + requiredInstructionSet + " whereas " + ps
10422                            + " requires " + instructionSet;
10423                    Slog.w(TAG, errorMessage);
10424                }
10425
10426                if (requiredInstructionSet == null) {
10427                    requiredInstructionSet = instructionSet;
10428                    requirer = ps;
10429                }
10430            }
10431        }
10432
10433        if (requiredInstructionSet != null) {
10434            String adjustedAbi;
10435            if (requirer != null) {
10436                // requirer != null implies that either scannedPackage was null or that scannedPackage
10437                // did not require an ABI, in which case we have to adjust scannedPackage to match
10438                // the ABI of the set (which is the same as requirer's ABI)
10439                adjustedAbi = requirer.primaryCpuAbiString;
10440                if (scannedPackage != null) {
10441                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10442                }
10443            } else {
10444                // requirer == null implies that we're updating all ABIs in the set to
10445                // match scannedPackage.
10446                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10447            }
10448
10449            for (PackageSetting ps : packagesForUser) {
10450                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10451                    if (ps.primaryCpuAbiString != null) {
10452                        continue;
10453                    }
10454
10455                    ps.primaryCpuAbiString = adjustedAbi;
10456                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10457                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10458                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10459                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10460                                + " (requirer="
10461                                + (requirer == null ? "null" : requirer.pkg.packageName)
10462                                + ", scannedPackage="
10463                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10464                                + ")");
10465                        try {
10466                            mInstaller.rmdex(ps.codePathString,
10467                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10468                        } catch (InstallerException ignored) {
10469                        }
10470                    }
10471                }
10472            }
10473        }
10474    }
10475
10476    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10477        synchronized (mPackages) {
10478            mResolverReplaced = true;
10479            // Set up information for custom user intent resolution activity.
10480            mResolveActivity.applicationInfo = pkg.applicationInfo;
10481            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10482            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10483            mResolveActivity.processName = pkg.applicationInfo.packageName;
10484            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10485            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10486                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10487            mResolveActivity.theme = 0;
10488            mResolveActivity.exported = true;
10489            mResolveActivity.enabled = true;
10490            mResolveInfo.activityInfo = mResolveActivity;
10491            mResolveInfo.priority = 0;
10492            mResolveInfo.preferredOrder = 0;
10493            mResolveInfo.match = 0;
10494            mResolveComponentName = mCustomResolverComponentName;
10495            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10496                    mResolveComponentName);
10497        }
10498    }
10499
10500    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10501        if (installerComponent == null) {
10502            if (DEBUG_EPHEMERAL) {
10503                Slog.d(TAG, "Clear ephemeral installer activity");
10504            }
10505            mEphemeralInstallerActivity.applicationInfo = null;
10506            return;
10507        }
10508
10509        if (DEBUG_EPHEMERAL) {
10510            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10511        }
10512        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10513        // Set up information for ephemeral installer activity
10514        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10515        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10516        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10517        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10518        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10519        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10520                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10521        mEphemeralInstallerActivity.theme = 0;
10522        mEphemeralInstallerActivity.exported = true;
10523        mEphemeralInstallerActivity.enabled = true;
10524        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10525        mEphemeralInstallerInfo.priority = 0;
10526        mEphemeralInstallerInfo.preferredOrder = 1;
10527        mEphemeralInstallerInfo.isDefault = true;
10528        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10529                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10530    }
10531
10532    private static String calculateBundledApkRoot(final String codePathString) {
10533        final File codePath = new File(codePathString);
10534        final File codeRoot;
10535        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10536            codeRoot = Environment.getRootDirectory();
10537        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10538            codeRoot = Environment.getOemDirectory();
10539        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10540            codeRoot = Environment.getVendorDirectory();
10541        } else {
10542            // Unrecognized code path; take its top real segment as the apk root:
10543            // e.g. /something/app/blah.apk => /something
10544            try {
10545                File f = codePath.getCanonicalFile();
10546                File parent = f.getParentFile();    // non-null because codePath is a file
10547                File tmp;
10548                while ((tmp = parent.getParentFile()) != null) {
10549                    f = parent;
10550                    parent = tmp;
10551                }
10552                codeRoot = f;
10553                Slog.w(TAG, "Unrecognized code path "
10554                        + codePath + " - using " + codeRoot);
10555            } catch (IOException e) {
10556                // Can't canonicalize the code path -- shenanigans?
10557                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10558                return Environment.getRootDirectory().getPath();
10559            }
10560        }
10561        return codeRoot.getPath();
10562    }
10563
10564    /**
10565     * Derive and set the location of native libraries for the given package,
10566     * which varies depending on where and how the package was installed.
10567     */
10568    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10569        final ApplicationInfo info = pkg.applicationInfo;
10570        final String codePath = pkg.codePath;
10571        final File codeFile = new File(codePath);
10572        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10573        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10574
10575        info.nativeLibraryRootDir = null;
10576        info.nativeLibraryRootRequiresIsa = false;
10577        info.nativeLibraryDir = null;
10578        info.secondaryNativeLibraryDir = null;
10579
10580        if (isApkFile(codeFile)) {
10581            // Monolithic install
10582            if (bundledApp) {
10583                // If "/system/lib64/apkname" exists, assume that is the per-package
10584                // native library directory to use; otherwise use "/system/lib/apkname".
10585                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10586                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10587                        getPrimaryInstructionSet(info));
10588
10589                // This is a bundled system app so choose the path based on the ABI.
10590                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10591                // is just the default path.
10592                final String apkName = deriveCodePathName(codePath);
10593                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10594                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10595                        apkName).getAbsolutePath();
10596
10597                if (info.secondaryCpuAbi != null) {
10598                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10599                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10600                            secondaryLibDir, apkName).getAbsolutePath();
10601                }
10602            } else if (asecApp) {
10603                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10604                        .getAbsolutePath();
10605            } else {
10606                final String apkName = deriveCodePathName(codePath);
10607                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10608                        .getAbsolutePath();
10609            }
10610
10611            info.nativeLibraryRootRequiresIsa = false;
10612            info.nativeLibraryDir = info.nativeLibraryRootDir;
10613        } else {
10614            // Cluster install
10615            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10616            info.nativeLibraryRootRequiresIsa = true;
10617
10618            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10619                    getPrimaryInstructionSet(info)).getAbsolutePath();
10620
10621            if (info.secondaryCpuAbi != null) {
10622                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10623                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10624            }
10625        }
10626    }
10627
10628    /**
10629     * Calculate the abis and roots for a bundled app. These can uniquely
10630     * be determined from the contents of the system partition, i.e whether
10631     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10632     * of this information, and instead assume that the system was built
10633     * sensibly.
10634     */
10635    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10636                                           PackageSetting pkgSetting) {
10637        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10638
10639        // If "/system/lib64/apkname" exists, assume that is the per-package
10640        // native library directory to use; otherwise use "/system/lib/apkname".
10641        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10642        setBundledAppAbi(pkg, apkRoot, apkName);
10643        // pkgSetting might be null during rescan following uninstall of updates
10644        // to a bundled app, so accommodate that possibility.  The settings in
10645        // that case will be established later from the parsed package.
10646        //
10647        // If the settings aren't null, sync them up with what we've just derived.
10648        // note that apkRoot isn't stored in the package settings.
10649        if (pkgSetting != null) {
10650            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10651            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10652        }
10653    }
10654
10655    /**
10656     * Deduces the ABI of a bundled app and sets the relevant fields on the
10657     * parsed pkg object.
10658     *
10659     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10660     *        under which system libraries are installed.
10661     * @param apkName the name of the installed package.
10662     */
10663    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10664        final File codeFile = new File(pkg.codePath);
10665
10666        final boolean has64BitLibs;
10667        final boolean has32BitLibs;
10668        if (isApkFile(codeFile)) {
10669            // Monolithic install
10670            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10671            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10672        } else {
10673            // Cluster install
10674            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10675            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10676                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10677                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10678                has64BitLibs = (new File(rootDir, isa)).exists();
10679            } else {
10680                has64BitLibs = false;
10681            }
10682            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10683                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10684                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10685                has32BitLibs = (new File(rootDir, isa)).exists();
10686            } else {
10687                has32BitLibs = false;
10688            }
10689        }
10690
10691        if (has64BitLibs && !has32BitLibs) {
10692            // The package has 64 bit libs, but not 32 bit libs. Its primary
10693            // ABI should be 64 bit. We can safely assume here that the bundled
10694            // native libraries correspond to the most preferred ABI in the list.
10695
10696            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10697            pkg.applicationInfo.secondaryCpuAbi = null;
10698        } else if (has32BitLibs && !has64BitLibs) {
10699            // The package has 32 bit libs but not 64 bit libs. Its primary
10700            // ABI should be 32 bit.
10701
10702            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10703            pkg.applicationInfo.secondaryCpuAbi = null;
10704        } else if (has32BitLibs && has64BitLibs) {
10705            // The application has both 64 and 32 bit bundled libraries. We check
10706            // here that the app declares multiArch support, and warn if it doesn't.
10707            //
10708            // We will be lenient here and record both ABIs. The primary will be the
10709            // ABI that's higher on the list, i.e, a device that's configured to prefer
10710            // 64 bit apps will see a 64 bit primary ABI,
10711
10712            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10713                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10714            }
10715
10716            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10717                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10718                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10719            } else {
10720                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10721                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10722            }
10723        } else {
10724            pkg.applicationInfo.primaryCpuAbi = null;
10725            pkg.applicationInfo.secondaryCpuAbi = null;
10726        }
10727    }
10728
10729    private void killApplication(String pkgName, int appId, String reason) {
10730        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10731    }
10732
10733    private void killApplication(String pkgName, int appId, int userId, String reason) {
10734        // Request the ActivityManager to kill the process(only for existing packages)
10735        // so that we do not end up in a confused state while the user is still using the older
10736        // version of the application while the new one gets installed.
10737        final long token = Binder.clearCallingIdentity();
10738        try {
10739            IActivityManager am = ActivityManager.getService();
10740            if (am != null) {
10741                try {
10742                    am.killApplication(pkgName, appId, userId, reason);
10743                } catch (RemoteException e) {
10744                }
10745            }
10746        } finally {
10747            Binder.restoreCallingIdentity(token);
10748        }
10749    }
10750
10751    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10752        // Remove the parent package setting
10753        PackageSetting ps = (PackageSetting) pkg.mExtras;
10754        if (ps != null) {
10755            removePackageLI(ps, chatty);
10756        }
10757        // Remove the child package setting
10758        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10759        for (int i = 0; i < childCount; i++) {
10760            PackageParser.Package childPkg = pkg.childPackages.get(i);
10761            ps = (PackageSetting) childPkg.mExtras;
10762            if (ps != null) {
10763                removePackageLI(ps, chatty);
10764            }
10765        }
10766    }
10767
10768    void removePackageLI(PackageSetting ps, boolean chatty) {
10769        if (DEBUG_INSTALL) {
10770            if (chatty)
10771                Log.d(TAG, "Removing package " + ps.name);
10772        }
10773
10774        // writer
10775        synchronized (mPackages) {
10776            mPackages.remove(ps.name);
10777            final PackageParser.Package pkg = ps.pkg;
10778            if (pkg != null) {
10779                cleanPackageDataStructuresLILPw(pkg, chatty);
10780            }
10781        }
10782    }
10783
10784    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10785        if (DEBUG_INSTALL) {
10786            if (chatty)
10787                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10788        }
10789
10790        // writer
10791        synchronized (mPackages) {
10792            // Remove the parent package
10793            mPackages.remove(pkg.applicationInfo.packageName);
10794            cleanPackageDataStructuresLILPw(pkg, chatty);
10795
10796            // Remove the child packages
10797            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10798            for (int i = 0; i < childCount; i++) {
10799                PackageParser.Package childPkg = pkg.childPackages.get(i);
10800                mPackages.remove(childPkg.applicationInfo.packageName);
10801                cleanPackageDataStructuresLILPw(childPkg, chatty);
10802            }
10803        }
10804    }
10805
10806    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10807        int N = pkg.providers.size();
10808        StringBuilder r = null;
10809        int i;
10810        for (i=0; i<N; i++) {
10811            PackageParser.Provider p = pkg.providers.get(i);
10812            mProviders.removeProvider(p);
10813            if (p.info.authority == null) {
10814
10815                /* There was another ContentProvider with this authority when
10816                 * this app was installed so this authority is null,
10817                 * Ignore it as we don't have to unregister the provider.
10818                 */
10819                continue;
10820            }
10821            String names[] = p.info.authority.split(";");
10822            for (int j = 0; j < names.length; j++) {
10823                if (mProvidersByAuthority.get(names[j]) == p) {
10824                    mProvidersByAuthority.remove(names[j]);
10825                    if (DEBUG_REMOVE) {
10826                        if (chatty)
10827                            Log.d(TAG, "Unregistered content provider: " + names[j]
10828                                    + ", className = " + p.info.name + ", isSyncable = "
10829                                    + p.info.isSyncable);
10830                    }
10831                }
10832            }
10833            if (DEBUG_REMOVE && chatty) {
10834                if (r == null) {
10835                    r = new StringBuilder(256);
10836                } else {
10837                    r.append(' ');
10838                }
10839                r.append(p.info.name);
10840            }
10841        }
10842        if (r != null) {
10843            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10844        }
10845
10846        N = pkg.services.size();
10847        r = null;
10848        for (i=0; i<N; i++) {
10849            PackageParser.Service s = pkg.services.get(i);
10850            mServices.removeService(s);
10851            if (chatty) {
10852                if (r == null) {
10853                    r = new StringBuilder(256);
10854                } else {
10855                    r.append(' ');
10856                }
10857                r.append(s.info.name);
10858            }
10859        }
10860        if (r != null) {
10861            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10862        }
10863
10864        N = pkg.receivers.size();
10865        r = null;
10866        for (i=0; i<N; i++) {
10867            PackageParser.Activity a = pkg.receivers.get(i);
10868            mReceivers.removeActivity(a, "receiver");
10869            if (DEBUG_REMOVE && chatty) {
10870                if (r == null) {
10871                    r = new StringBuilder(256);
10872                } else {
10873                    r.append(' ');
10874                }
10875                r.append(a.info.name);
10876            }
10877        }
10878        if (r != null) {
10879            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10880        }
10881
10882        N = pkg.activities.size();
10883        r = null;
10884        for (i=0; i<N; i++) {
10885            PackageParser.Activity a = pkg.activities.get(i);
10886            mActivities.removeActivity(a, "activity");
10887            if (DEBUG_REMOVE && chatty) {
10888                if (r == null) {
10889                    r = new StringBuilder(256);
10890                } else {
10891                    r.append(' ');
10892                }
10893                r.append(a.info.name);
10894            }
10895        }
10896        if (r != null) {
10897            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10898        }
10899
10900        N = pkg.permissions.size();
10901        r = null;
10902        for (i=0; i<N; i++) {
10903            PackageParser.Permission p = pkg.permissions.get(i);
10904            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10905            if (bp == null) {
10906                bp = mSettings.mPermissionTrees.get(p.info.name);
10907            }
10908            if (bp != null && bp.perm == p) {
10909                bp.perm = null;
10910                if (DEBUG_REMOVE && chatty) {
10911                    if (r == null) {
10912                        r = new StringBuilder(256);
10913                    } else {
10914                        r.append(' ');
10915                    }
10916                    r.append(p.info.name);
10917                }
10918            }
10919            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10920                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10921                if (appOpPkgs != null) {
10922                    appOpPkgs.remove(pkg.packageName);
10923                }
10924            }
10925        }
10926        if (r != null) {
10927            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10928        }
10929
10930        N = pkg.requestedPermissions.size();
10931        r = null;
10932        for (i=0; i<N; i++) {
10933            String perm = pkg.requestedPermissions.get(i);
10934            BasePermission bp = mSettings.mPermissions.get(perm);
10935            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10936                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10937                if (appOpPkgs != null) {
10938                    appOpPkgs.remove(pkg.packageName);
10939                    if (appOpPkgs.isEmpty()) {
10940                        mAppOpPermissionPackages.remove(perm);
10941                    }
10942                }
10943            }
10944        }
10945        if (r != null) {
10946            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10947        }
10948
10949        N = pkg.instrumentation.size();
10950        r = null;
10951        for (i=0; i<N; i++) {
10952            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10953            mInstrumentation.remove(a.getComponentName());
10954            if (DEBUG_REMOVE && chatty) {
10955                if (r == null) {
10956                    r = new StringBuilder(256);
10957                } else {
10958                    r.append(' ');
10959                }
10960                r.append(a.info.name);
10961            }
10962        }
10963        if (r != null) {
10964            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10965        }
10966
10967        r = null;
10968        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10969            // Only system apps can hold shared libraries.
10970            if (pkg.libraryNames != null) {
10971                for (i = 0; i < pkg.libraryNames.size(); i++) {
10972                    String name = pkg.libraryNames.get(i);
10973                    if (removeSharedLibraryLPw(name, 0)) {
10974                        if (DEBUG_REMOVE && chatty) {
10975                            if (r == null) {
10976                                r = new StringBuilder(256);
10977                            } else {
10978                                r.append(' ');
10979                            }
10980                            r.append(name);
10981                        }
10982                    }
10983                }
10984            }
10985        }
10986
10987        r = null;
10988
10989        // Any package can hold static shared libraries.
10990        if (pkg.staticSharedLibName != null) {
10991            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
10992                if (DEBUG_REMOVE && chatty) {
10993                    if (r == null) {
10994                        r = new StringBuilder(256);
10995                    } else {
10996                        r.append(' ');
10997                    }
10998                    r.append(pkg.staticSharedLibName);
10999                }
11000            }
11001        }
11002
11003        if (r != null) {
11004            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11005        }
11006    }
11007
11008    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11009        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11010            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11011                return true;
11012            }
11013        }
11014        return false;
11015    }
11016
11017    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11018    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11019    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11020
11021    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11022        // Update the parent permissions
11023        updatePermissionsLPw(pkg.packageName, pkg, flags);
11024        // Update the child permissions
11025        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11026        for (int i = 0; i < childCount; i++) {
11027            PackageParser.Package childPkg = pkg.childPackages.get(i);
11028            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11029        }
11030    }
11031
11032    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11033            int flags) {
11034        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11035        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11036    }
11037
11038    private void updatePermissionsLPw(String changingPkg,
11039            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11040        // Make sure there are no dangling permission trees.
11041        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11042        while (it.hasNext()) {
11043            final BasePermission bp = it.next();
11044            if (bp.packageSetting == null) {
11045                // We may not yet have parsed the package, so just see if
11046                // we still know about its settings.
11047                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11048            }
11049            if (bp.packageSetting == null) {
11050                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11051                        + " from package " + bp.sourcePackage);
11052                it.remove();
11053            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11054                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11055                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11056                            + " from package " + bp.sourcePackage);
11057                    flags |= UPDATE_PERMISSIONS_ALL;
11058                    it.remove();
11059                }
11060            }
11061        }
11062
11063        // Make sure all dynamic permissions have been assigned to a package,
11064        // and make sure there are no dangling permissions.
11065        it = mSettings.mPermissions.values().iterator();
11066        while (it.hasNext()) {
11067            final BasePermission bp = it.next();
11068            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11069                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11070                        + bp.name + " pkg=" + bp.sourcePackage
11071                        + " info=" + bp.pendingInfo);
11072                if (bp.packageSetting == null && bp.pendingInfo != null) {
11073                    final BasePermission tree = findPermissionTreeLP(bp.name);
11074                    if (tree != null && tree.perm != null) {
11075                        bp.packageSetting = tree.packageSetting;
11076                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11077                                new PermissionInfo(bp.pendingInfo));
11078                        bp.perm.info.packageName = tree.perm.info.packageName;
11079                        bp.perm.info.name = bp.name;
11080                        bp.uid = tree.uid;
11081                    }
11082                }
11083            }
11084            if (bp.packageSetting == null) {
11085                // We may not yet have parsed the package, so just see if
11086                // we still know about its settings.
11087                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11088            }
11089            if (bp.packageSetting == null) {
11090                Slog.w(TAG, "Removing dangling permission: " + bp.name
11091                        + " from package " + bp.sourcePackage);
11092                it.remove();
11093            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11094                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11095                    Slog.i(TAG, "Removing old permission: " + bp.name
11096                            + " from package " + bp.sourcePackage);
11097                    flags |= UPDATE_PERMISSIONS_ALL;
11098                    it.remove();
11099                }
11100            }
11101        }
11102
11103        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11104        // Now update the permissions for all packages, in particular
11105        // replace the granted permissions of the system packages.
11106        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11107            for (PackageParser.Package pkg : mPackages.values()) {
11108                if (pkg != pkgInfo) {
11109                    // Only replace for packages on requested volume
11110                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11111                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11112                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11113                    grantPermissionsLPw(pkg, replace, changingPkg);
11114                }
11115            }
11116        }
11117
11118        if (pkgInfo != null) {
11119            // Only replace for packages on requested volume
11120            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11121            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11122                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11123            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11124        }
11125        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11126    }
11127
11128    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11129            String packageOfInterest) {
11130        // IMPORTANT: There are two types of permissions: install and runtime.
11131        // Install time permissions are granted when the app is installed to
11132        // all device users and users added in the future. Runtime permissions
11133        // are granted at runtime explicitly to specific users. Normal and signature
11134        // protected permissions are install time permissions. Dangerous permissions
11135        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11136        // otherwise they are runtime permissions. This function does not manage
11137        // runtime permissions except for the case an app targeting Lollipop MR1
11138        // being upgraded to target a newer SDK, in which case dangerous permissions
11139        // are transformed from install time to runtime ones.
11140
11141        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11142        if (ps == null) {
11143            return;
11144        }
11145
11146        PermissionsState permissionsState = ps.getPermissionsState();
11147        PermissionsState origPermissions = permissionsState;
11148
11149        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11150
11151        boolean runtimePermissionsRevoked = false;
11152        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11153
11154        boolean changedInstallPermission = false;
11155
11156        if (replace) {
11157            ps.installPermissionsFixed = false;
11158            if (!ps.isSharedUser()) {
11159                origPermissions = new PermissionsState(permissionsState);
11160                permissionsState.reset();
11161            } else {
11162                // We need to know only about runtime permission changes since the
11163                // calling code always writes the install permissions state but
11164                // the runtime ones are written only if changed. The only cases of
11165                // changed runtime permissions here are promotion of an install to
11166                // runtime and revocation of a runtime from a shared user.
11167                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11168                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11169                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11170                    runtimePermissionsRevoked = true;
11171                }
11172            }
11173        }
11174
11175        permissionsState.setGlobalGids(mGlobalGids);
11176
11177        final int N = pkg.requestedPermissions.size();
11178        for (int i=0; i<N; i++) {
11179            final String name = pkg.requestedPermissions.get(i);
11180            final BasePermission bp = mSettings.mPermissions.get(name);
11181
11182            if (DEBUG_INSTALL) {
11183                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11184            }
11185
11186            if (bp == null || bp.packageSetting == null) {
11187                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11188                    Slog.w(TAG, "Unknown permission " + name
11189                            + " in package " + pkg.packageName);
11190                }
11191                continue;
11192            }
11193
11194
11195            // Limit ephemeral apps to ephemeral allowed permissions.
11196            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
11197                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11198                        + pkg.packageName);
11199                continue;
11200            }
11201
11202            final String perm = bp.name;
11203            boolean allowedSig = false;
11204            int grant = GRANT_DENIED;
11205
11206            // Keep track of app op permissions.
11207            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11208                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11209                if (pkgs == null) {
11210                    pkgs = new ArraySet<>();
11211                    mAppOpPermissionPackages.put(bp.name, pkgs);
11212                }
11213                pkgs.add(pkg.packageName);
11214            }
11215
11216            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11217            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11218                    >= Build.VERSION_CODES.M;
11219            switch (level) {
11220                case PermissionInfo.PROTECTION_NORMAL: {
11221                    // For all apps normal permissions are install time ones.
11222                    grant = GRANT_INSTALL;
11223                } break;
11224
11225                case PermissionInfo.PROTECTION_DANGEROUS: {
11226                    // If a permission review is required for legacy apps we represent
11227                    // their permissions as always granted runtime ones since we need
11228                    // to keep the review required permission flag per user while an
11229                    // install permission's state is shared across all users.
11230                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11231                        // For legacy apps dangerous permissions are install time ones.
11232                        grant = GRANT_INSTALL;
11233                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11234                        // For legacy apps that became modern, install becomes runtime.
11235                        grant = GRANT_UPGRADE;
11236                    } else if (mPromoteSystemApps
11237                            && isSystemApp(ps)
11238                            && mExistingSystemPackages.contains(ps.name)) {
11239                        // For legacy system apps, install becomes runtime.
11240                        // We cannot check hasInstallPermission() for system apps since those
11241                        // permissions were granted implicitly and not persisted pre-M.
11242                        grant = GRANT_UPGRADE;
11243                    } else {
11244                        // For modern apps keep runtime permissions unchanged.
11245                        grant = GRANT_RUNTIME;
11246                    }
11247                } break;
11248
11249                case PermissionInfo.PROTECTION_SIGNATURE: {
11250                    // For all apps signature permissions are install time ones.
11251                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11252                    if (allowedSig) {
11253                        grant = GRANT_INSTALL;
11254                    }
11255                } break;
11256            }
11257
11258            if (DEBUG_INSTALL) {
11259                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11260            }
11261
11262            if (grant != GRANT_DENIED) {
11263                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11264                    // If this is an existing, non-system package, then
11265                    // we can't add any new permissions to it.
11266                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11267                        // Except...  if this is a permission that was added
11268                        // to the platform (note: need to only do this when
11269                        // updating the platform).
11270                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11271                            grant = GRANT_DENIED;
11272                        }
11273                    }
11274                }
11275
11276                switch (grant) {
11277                    case GRANT_INSTALL: {
11278                        // Revoke this as runtime permission to handle the case of
11279                        // a runtime permission being downgraded to an install one.
11280                        // Also in permission review mode we keep dangerous permissions
11281                        // for legacy apps
11282                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11283                            if (origPermissions.getRuntimePermissionState(
11284                                    bp.name, userId) != null) {
11285                                // Revoke the runtime permission and clear the flags.
11286                                origPermissions.revokeRuntimePermission(bp, userId);
11287                                origPermissions.updatePermissionFlags(bp, userId,
11288                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11289                                // If we revoked a permission permission, we have to write.
11290                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11291                                        changedRuntimePermissionUserIds, userId);
11292                            }
11293                        }
11294                        // Grant an install permission.
11295                        if (permissionsState.grantInstallPermission(bp) !=
11296                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11297                            changedInstallPermission = true;
11298                        }
11299                    } break;
11300
11301                    case GRANT_RUNTIME: {
11302                        // Grant previously granted runtime permissions.
11303                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11304                            PermissionState permissionState = origPermissions
11305                                    .getRuntimePermissionState(bp.name, userId);
11306                            int flags = permissionState != null
11307                                    ? permissionState.getFlags() : 0;
11308                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11309                                // Don't propagate the permission in a permission review mode if
11310                                // the former was revoked, i.e. marked to not propagate on upgrade.
11311                                // Note that in a permission review mode install permissions are
11312                                // represented as constantly granted runtime ones since we need to
11313                                // keep a per user state associated with the permission. Also the
11314                                // revoke on upgrade flag is no longer applicable and is reset.
11315                                final boolean revokeOnUpgrade = (flags & PackageManager
11316                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11317                                if (revokeOnUpgrade) {
11318                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11319                                    // Since we changed the flags, we have to write.
11320                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11321                                            changedRuntimePermissionUserIds, userId);
11322                                }
11323                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11324                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11325                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11326                                        // If we cannot put the permission as it was,
11327                                        // we have to write.
11328                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11329                                                changedRuntimePermissionUserIds, userId);
11330                                    }
11331                                }
11332
11333                                // If the app supports runtime permissions no need for a review.
11334                                if (mPermissionReviewRequired
11335                                        && appSupportsRuntimePermissions
11336                                        && (flags & PackageManager
11337                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11338                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11339                                    // Since we changed the flags, we have to write.
11340                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11341                                            changedRuntimePermissionUserIds, userId);
11342                                }
11343                            } else if (mPermissionReviewRequired
11344                                    && !appSupportsRuntimePermissions) {
11345                                // For legacy apps that need a permission review, every new
11346                                // runtime permission is granted but it is pending a review.
11347                                // We also need to review only platform defined runtime
11348                                // permissions as these are the only ones the platform knows
11349                                // how to disable the API to simulate revocation as legacy
11350                                // apps don't expect to run with revoked permissions.
11351                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11352                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11353                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11354                                        // We changed the flags, hence have to write.
11355                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11356                                                changedRuntimePermissionUserIds, userId);
11357                                    }
11358                                }
11359                                if (permissionsState.grantRuntimePermission(bp, userId)
11360                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11361                                    // We changed the permission, hence have to write.
11362                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11363                                            changedRuntimePermissionUserIds, userId);
11364                                }
11365                            }
11366                            // Propagate the permission flags.
11367                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11368                        }
11369                    } break;
11370
11371                    case GRANT_UPGRADE: {
11372                        // Grant runtime permissions for a previously held install permission.
11373                        PermissionState permissionState = origPermissions
11374                                .getInstallPermissionState(bp.name);
11375                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11376
11377                        if (origPermissions.revokeInstallPermission(bp)
11378                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11379                            // We will be transferring the permission flags, so clear them.
11380                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11381                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11382                            changedInstallPermission = true;
11383                        }
11384
11385                        // If the permission is not to be promoted to runtime we ignore it and
11386                        // also its other flags as they are not applicable to install permissions.
11387                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11388                            for (int userId : currentUserIds) {
11389                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11390                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11391                                    // Transfer the permission flags.
11392                                    permissionsState.updatePermissionFlags(bp, userId,
11393                                            flags, flags);
11394                                    // If we granted the permission, we have to write.
11395                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11396                                            changedRuntimePermissionUserIds, userId);
11397                                }
11398                            }
11399                        }
11400                    } break;
11401
11402                    default: {
11403                        if (packageOfInterest == null
11404                                || packageOfInterest.equals(pkg.packageName)) {
11405                            Slog.w(TAG, "Not granting permission " + perm
11406                                    + " to package " + pkg.packageName
11407                                    + " because it was previously installed without");
11408                        }
11409                    } break;
11410                }
11411            } else {
11412                if (permissionsState.revokeInstallPermission(bp) !=
11413                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11414                    // Also drop the permission flags.
11415                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11416                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11417                    changedInstallPermission = true;
11418                    Slog.i(TAG, "Un-granting permission " + perm
11419                            + " from package " + pkg.packageName
11420                            + " (protectionLevel=" + bp.protectionLevel
11421                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11422                            + ")");
11423                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11424                    // Don't print warning for app op permissions, since it is fine for them
11425                    // not to be granted, there is a UI for the user to decide.
11426                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11427                        Slog.w(TAG, "Not granting permission " + perm
11428                                + " to package " + pkg.packageName
11429                                + " (protectionLevel=" + bp.protectionLevel
11430                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11431                                + ")");
11432                    }
11433                }
11434            }
11435        }
11436
11437        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11438                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11439            // This is the first that we have heard about this package, so the
11440            // permissions we have now selected are fixed until explicitly
11441            // changed.
11442            ps.installPermissionsFixed = true;
11443        }
11444
11445        // Persist the runtime permissions state for users with changes. If permissions
11446        // were revoked because no app in the shared user declares them we have to
11447        // write synchronously to avoid losing runtime permissions state.
11448        for (int userId : changedRuntimePermissionUserIds) {
11449            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11450        }
11451    }
11452
11453    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11454        boolean allowed = false;
11455        final int NP = PackageParser.NEW_PERMISSIONS.length;
11456        for (int ip=0; ip<NP; ip++) {
11457            final PackageParser.NewPermissionInfo npi
11458                    = PackageParser.NEW_PERMISSIONS[ip];
11459            if (npi.name.equals(perm)
11460                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11461                allowed = true;
11462                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11463                        + pkg.packageName);
11464                break;
11465            }
11466        }
11467        return allowed;
11468    }
11469
11470    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11471            BasePermission bp, PermissionsState origPermissions) {
11472        boolean privilegedPermission = (bp.protectionLevel
11473                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11474        boolean privappPermissionsDisable =
11475                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11476        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11477        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11478        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11479                && !platformPackage && platformPermission) {
11480            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11481                    .getPrivAppPermissions(pkg.packageName);
11482            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11483            if (!whitelisted) {
11484                Slog.w(TAG, "Privileged permission " + perm + " for package "
11485                        + pkg.packageName + " - not in privapp-permissions whitelist");
11486                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11487                    return false;
11488                }
11489            }
11490        }
11491        boolean allowed = (compareSignatures(
11492                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11493                        == PackageManager.SIGNATURE_MATCH)
11494                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11495                        == PackageManager.SIGNATURE_MATCH);
11496        if (!allowed && privilegedPermission) {
11497            if (isSystemApp(pkg)) {
11498                // For updated system applications, a system permission
11499                // is granted only if it had been defined by the original application.
11500                if (pkg.isUpdatedSystemApp()) {
11501                    final PackageSetting sysPs = mSettings
11502                            .getDisabledSystemPkgLPr(pkg.packageName);
11503                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11504                        // If the original was granted this permission, we take
11505                        // that grant decision as read and propagate it to the
11506                        // update.
11507                        if (sysPs.isPrivileged()) {
11508                            allowed = true;
11509                        }
11510                    } else {
11511                        // The system apk may have been updated with an older
11512                        // version of the one on the data partition, but which
11513                        // granted a new system permission that it didn't have
11514                        // before.  In this case we do want to allow the app to
11515                        // now get the new permission if the ancestral apk is
11516                        // privileged to get it.
11517                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11518                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11519                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11520                                    allowed = true;
11521                                    break;
11522                                }
11523                            }
11524                        }
11525                        // Also if a privileged parent package on the system image or any of
11526                        // its children requested a privileged permission, the updated child
11527                        // packages can also get the permission.
11528                        if (pkg.parentPackage != null) {
11529                            final PackageSetting disabledSysParentPs = mSettings
11530                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11531                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11532                                    && disabledSysParentPs.isPrivileged()) {
11533                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11534                                    allowed = true;
11535                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11536                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11537                                    for (int i = 0; i < count; i++) {
11538                                        PackageParser.Package disabledSysChildPkg =
11539                                                disabledSysParentPs.pkg.childPackages.get(i);
11540                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11541                                                perm)) {
11542                                            allowed = true;
11543                                            break;
11544                                        }
11545                                    }
11546                                }
11547                            }
11548                        }
11549                    }
11550                } else {
11551                    allowed = isPrivilegedApp(pkg);
11552                }
11553            }
11554        }
11555        if (!allowed) {
11556            if (!allowed && (bp.protectionLevel
11557                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11558                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11559                // If this was a previously normal/dangerous permission that got moved
11560                // to a system permission as part of the runtime permission redesign, then
11561                // we still want to blindly grant it to old apps.
11562                allowed = true;
11563            }
11564            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11565                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11566                // If this permission is to be granted to the system installer and
11567                // this app is an installer, then it gets the permission.
11568                allowed = true;
11569            }
11570            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11571                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11572                // If this permission is to be granted to the system verifier and
11573                // this app is a verifier, then it gets the permission.
11574                allowed = true;
11575            }
11576            if (!allowed && (bp.protectionLevel
11577                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11578                    && isSystemApp(pkg)) {
11579                // Any pre-installed system app is allowed to get this permission.
11580                allowed = true;
11581            }
11582            if (!allowed && (bp.protectionLevel
11583                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11584                // For development permissions, a development permission
11585                // is granted only if it was already granted.
11586                allowed = origPermissions.hasInstallPermission(perm);
11587            }
11588            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11589                    && pkg.packageName.equals(mSetupWizardPackage)) {
11590                // If this permission is to be granted to the system setup wizard and
11591                // this app is a setup wizard, then it gets the permission.
11592                allowed = true;
11593            }
11594        }
11595        return allowed;
11596    }
11597
11598    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11599        final int permCount = pkg.requestedPermissions.size();
11600        for (int j = 0; j < permCount; j++) {
11601            String requestedPermission = pkg.requestedPermissions.get(j);
11602            if (permission.equals(requestedPermission)) {
11603                return true;
11604            }
11605        }
11606        return false;
11607    }
11608
11609    final class ActivityIntentResolver
11610            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11611        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11612                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11613            if (!sUserManager.exists(userId)) return null;
11614            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11615                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11616                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11617            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11618                    isEphemeral, userId);
11619        }
11620
11621        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11622                int userId) {
11623            if (!sUserManager.exists(userId)) return null;
11624            mFlags = flags;
11625            return super.queryIntent(intent, resolvedType,
11626                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11627                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11628                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11629        }
11630
11631        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11632                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11633            if (!sUserManager.exists(userId)) return null;
11634            if (packageActivities == null) {
11635                return null;
11636            }
11637            mFlags = flags;
11638            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11639            final boolean vislbleToEphemeral =
11640                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11641            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11642            final int N = packageActivities.size();
11643            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11644                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11645
11646            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11647            for (int i = 0; i < N; ++i) {
11648                intentFilters = packageActivities.get(i).intents;
11649                if (intentFilters != null && intentFilters.size() > 0) {
11650                    PackageParser.ActivityIntentInfo[] array =
11651                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11652                    intentFilters.toArray(array);
11653                    listCut.add(array);
11654                }
11655            }
11656            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11657                    vislbleToEphemeral, isEphemeral, listCut, userId);
11658        }
11659
11660        /**
11661         * Finds a privileged activity that matches the specified activity names.
11662         */
11663        private PackageParser.Activity findMatchingActivity(
11664                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11665            for (PackageParser.Activity sysActivity : activityList) {
11666                if (sysActivity.info.name.equals(activityInfo.name)) {
11667                    return sysActivity;
11668                }
11669                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11670                    return sysActivity;
11671                }
11672                if (sysActivity.info.targetActivity != null) {
11673                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11674                        return sysActivity;
11675                    }
11676                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11677                        return sysActivity;
11678                    }
11679                }
11680            }
11681            return null;
11682        }
11683
11684        public class IterGenerator<E> {
11685            public Iterator<E> generate(ActivityIntentInfo info) {
11686                return null;
11687            }
11688        }
11689
11690        public class ActionIterGenerator extends IterGenerator<String> {
11691            @Override
11692            public Iterator<String> generate(ActivityIntentInfo info) {
11693                return info.actionsIterator();
11694            }
11695        }
11696
11697        public class CategoriesIterGenerator extends IterGenerator<String> {
11698            @Override
11699            public Iterator<String> generate(ActivityIntentInfo info) {
11700                return info.categoriesIterator();
11701            }
11702        }
11703
11704        public class SchemesIterGenerator extends IterGenerator<String> {
11705            @Override
11706            public Iterator<String> generate(ActivityIntentInfo info) {
11707                return info.schemesIterator();
11708            }
11709        }
11710
11711        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11712            @Override
11713            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11714                return info.authoritiesIterator();
11715            }
11716        }
11717
11718        /**
11719         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11720         * MODIFIED. Do not pass in a list that should not be changed.
11721         */
11722        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11723                IterGenerator<T> generator, Iterator<T> searchIterator) {
11724            // loop through the set of actions; every one must be found in the intent filter
11725            while (searchIterator.hasNext()) {
11726                // we must have at least one filter in the list to consider a match
11727                if (intentList.size() == 0) {
11728                    break;
11729                }
11730
11731                final T searchAction = searchIterator.next();
11732
11733                // loop through the set of intent filters
11734                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11735                while (intentIter.hasNext()) {
11736                    final ActivityIntentInfo intentInfo = intentIter.next();
11737                    boolean selectionFound = false;
11738
11739                    // loop through the intent filter's selection criteria; at least one
11740                    // of them must match the searched criteria
11741                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11742                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11743                        final T intentSelection = intentSelectionIter.next();
11744                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11745                            selectionFound = true;
11746                            break;
11747                        }
11748                    }
11749
11750                    // the selection criteria wasn't found in this filter's set; this filter
11751                    // is not a potential match
11752                    if (!selectionFound) {
11753                        intentIter.remove();
11754                    }
11755                }
11756            }
11757        }
11758
11759        private boolean isProtectedAction(ActivityIntentInfo filter) {
11760            final Iterator<String> actionsIter = filter.actionsIterator();
11761            while (actionsIter != null && actionsIter.hasNext()) {
11762                final String filterAction = actionsIter.next();
11763                if (PROTECTED_ACTIONS.contains(filterAction)) {
11764                    return true;
11765                }
11766            }
11767            return false;
11768        }
11769
11770        /**
11771         * Adjusts the priority of the given intent filter according to policy.
11772         * <p>
11773         * <ul>
11774         * <li>The priority for non privileged applications is capped to '0'</li>
11775         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11776         * <li>The priority for unbundled updates to privileged applications is capped to the
11777         *      priority defined on the system partition</li>
11778         * </ul>
11779         * <p>
11780         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11781         * allowed to obtain any priority on any action.
11782         */
11783        private void adjustPriority(
11784                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11785            // nothing to do; priority is fine as-is
11786            if (intent.getPriority() <= 0) {
11787                return;
11788            }
11789
11790            final ActivityInfo activityInfo = intent.activity.info;
11791            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11792
11793            final boolean privilegedApp =
11794                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11795            if (!privilegedApp) {
11796                // non-privileged applications can never define a priority >0
11797                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11798                        + " package: " + applicationInfo.packageName
11799                        + " activity: " + intent.activity.className
11800                        + " origPrio: " + intent.getPriority());
11801                intent.setPriority(0);
11802                return;
11803            }
11804
11805            if (systemActivities == null) {
11806                // the system package is not disabled; we're parsing the system partition
11807                if (isProtectedAction(intent)) {
11808                    if (mDeferProtectedFilters) {
11809                        // We can't deal with these just yet. No component should ever obtain a
11810                        // >0 priority for a protected actions, with ONE exception -- the setup
11811                        // wizard. The setup wizard, however, cannot be known until we're able to
11812                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11813                        // until all intent filters have been processed. Chicken, meet egg.
11814                        // Let the filter temporarily have a high priority and rectify the
11815                        // priorities after all system packages have been scanned.
11816                        mProtectedFilters.add(intent);
11817                        if (DEBUG_FILTERS) {
11818                            Slog.i(TAG, "Protected action; save for later;"
11819                                    + " package: " + applicationInfo.packageName
11820                                    + " activity: " + intent.activity.className
11821                                    + " origPrio: " + intent.getPriority());
11822                        }
11823                        return;
11824                    } else {
11825                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11826                            Slog.i(TAG, "No setup wizard;"
11827                                + " All protected intents capped to priority 0");
11828                        }
11829                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11830                            if (DEBUG_FILTERS) {
11831                                Slog.i(TAG, "Found setup wizard;"
11832                                    + " allow priority " + intent.getPriority() + ";"
11833                                    + " package: " + intent.activity.info.packageName
11834                                    + " activity: " + intent.activity.className
11835                                    + " priority: " + intent.getPriority());
11836                            }
11837                            // setup wizard gets whatever it wants
11838                            return;
11839                        }
11840                        Slog.w(TAG, "Protected action; cap priority to 0;"
11841                                + " package: " + intent.activity.info.packageName
11842                                + " activity: " + intent.activity.className
11843                                + " origPrio: " + intent.getPriority());
11844                        intent.setPriority(0);
11845                        return;
11846                    }
11847                }
11848                // privileged apps on the system image get whatever priority they request
11849                return;
11850            }
11851
11852            // privileged app unbundled update ... try to find the same activity
11853            final PackageParser.Activity foundActivity =
11854                    findMatchingActivity(systemActivities, activityInfo);
11855            if (foundActivity == null) {
11856                // this is a new activity; it cannot obtain >0 priority
11857                if (DEBUG_FILTERS) {
11858                    Slog.i(TAG, "New activity; cap priority to 0;"
11859                            + " package: " + applicationInfo.packageName
11860                            + " activity: " + intent.activity.className
11861                            + " origPrio: " + intent.getPriority());
11862                }
11863                intent.setPriority(0);
11864                return;
11865            }
11866
11867            // found activity, now check for filter equivalence
11868
11869            // a shallow copy is enough; we modify the list, not its contents
11870            final List<ActivityIntentInfo> intentListCopy =
11871                    new ArrayList<>(foundActivity.intents);
11872            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11873
11874            // find matching action subsets
11875            final Iterator<String> actionsIterator = intent.actionsIterator();
11876            if (actionsIterator != null) {
11877                getIntentListSubset(
11878                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11879                if (intentListCopy.size() == 0) {
11880                    // no more intents to match; we're not equivalent
11881                    if (DEBUG_FILTERS) {
11882                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11883                                + " package: " + applicationInfo.packageName
11884                                + " activity: " + intent.activity.className
11885                                + " origPrio: " + intent.getPriority());
11886                    }
11887                    intent.setPriority(0);
11888                    return;
11889                }
11890            }
11891
11892            // find matching category subsets
11893            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11894            if (categoriesIterator != null) {
11895                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11896                        categoriesIterator);
11897                if (intentListCopy.size() == 0) {
11898                    // no more intents to match; we're not equivalent
11899                    if (DEBUG_FILTERS) {
11900                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11901                                + " package: " + applicationInfo.packageName
11902                                + " activity: " + intent.activity.className
11903                                + " origPrio: " + intent.getPriority());
11904                    }
11905                    intent.setPriority(0);
11906                    return;
11907                }
11908            }
11909
11910            // find matching schemes subsets
11911            final Iterator<String> schemesIterator = intent.schemesIterator();
11912            if (schemesIterator != null) {
11913                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11914                        schemesIterator);
11915                if (intentListCopy.size() == 0) {
11916                    // no more intents to match; we're not equivalent
11917                    if (DEBUG_FILTERS) {
11918                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11919                                + " package: " + applicationInfo.packageName
11920                                + " activity: " + intent.activity.className
11921                                + " origPrio: " + intent.getPriority());
11922                    }
11923                    intent.setPriority(0);
11924                    return;
11925                }
11926            }
11927
11928            // find matching authorities subsets
11929            final Iterator<IntentFilter.AuthorityEntry>
11930                    authoritiesIterator = intent.authoritiesIterator();
11931            if (authoritiesIterator != null) {
11932                getIntentListSubset(intentListCopy,
11933                        new AuthoritiesIterGenerator(),
11934                        authoritiesIterator);
11935                if (intentListCopy.size() == 0) {
11936                    // no more intents to match; we're not equivalent
11937                    if (DEBUG_FILTERS) {
11938                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11939                                + " package: " + applicationInfo.packageName
11940                                + " activity: " + intent.activity.className
11941                                + " origPrio: " + intent.getPriority());
11942                    }
11943                    intent.setPriority(0);
11944                    return;
11945                }
11946            }
11947
11948            // we found matching filter(s); app gets the max priority of all intents
11949            int cappedPriority = 0;
11950            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11951                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11952            }
11953            if (intent.getPriority() > cappedPriority) {
11954                if (DEBUG_FILTERS) {
11955                    Slog.i(TAG, "Found matching filter(s);"
11956                            + " cap priority to " + cappedPriority + ";"
11957                            + " package: " + applicationInfo.packageName
11958                            + " activity: " + intent.activity.className
11959                            + " origPrio: " + intent.getPriority());
11960                }
11961                intent.setPriority(cappedPriority);
11962                return;
11963            }
11964            // all this for nothing; the requested priority was <= what was on the system
11965        }
11966
11967        public final void addActivity(PackageParser.Activity a, String type) {
11968            mActivities.put(a.getComponentName(), a);
11969            if (DEBUG_SHOW_INFO)
11970                Log.v(
11971                TAG, "  " + type + " " +
11972                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11973            if (DEBUG_SHOW_INFO)
11974                Log.v(TAG, "    Class=" + a.info.name);
11975            final int NI = a.intents.size();
11976            for (int j=0; j<NI; j++) {
11977                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11978                if ("activity".equals(type)) {
11979                    final PackageSetting ps =
11980                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11981                    final List<PackageParser.Activity> systemActivities =
11982                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11983                    adjustPriority(systemActivities, intent);
11984                }
11985                if (DEBUG_SHOW_INFO) {
11986                    Log.v(TAG, "    IntentFilter:");
11987                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11988                }
11989                if (!intent.debugCheck()) {
11990                    Log.w(TAG, "==> For Activity " + a.info.name);
11991                }
11992                addFilter(intent);
11993            }
11994        }
11995
11996        public final void removeActivity(PackageParser.Activity a, String type) {
11997            mActivities.remove(a.getComponentName());
11998            if (DEBUG_SHOW_INFO) {
11999                Log.v(TAG, "  " + type + " "
12000                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12001                                : a.info.name) + ":");
12002                Log.v(TAG, "    Class=" + a.info.name);
12003            }
12004            final int NI = a.intents.size();
12005            for (int j=0; j<NI; j++) {
12006                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12007                if (DEBUG_SHOW_INFO) {
12008                    Log.v(TAG, "    IntentFilter:");
12009                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12010                }
12011                removeFilter(intent);
12012            }
12013        }
12014
12015        @Override
12016        protected boolean allowFilterResult(
12017                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12018            ActivityInfo filterAi = filter.activity.info;
12019            for (int i=dest.size()-1; i>=0; i--) {
12020                ActivityInfo destAi = dest.get(i).activityInfo;
12021                if (destAi.name == filterAi.name
12022                        && destAi.packageName == filterAi.packageName) {
12023                    return false;
12024                }
12025            }
12026            return true;
12027        }
12028
12029        @Override
12030        protected ActivityIntentInfo[] newArray(int size) {
12031            return new ActivityIntentInfo[size];
12032        }
12033
12034        @Override
12035        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12036            if (!sUserManager.exists(userId)) return true;
12037            PackageParser.Package p = filter.activity.owner;
12038            if (p != null) {
12039                PackageSetting ps = (PackageSetting)p.mExtras;
12040                if (ps != null) {
12041                    // System apps are never considered stopped for purposes of
12042                    // filtering, because there may be no way for the user to
12043                    // actually re-launch them.
12044                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12045                            && ps.getStopped(userId);
12046                }
12047            }
12048            return false;
12049        }
12050
12051        @Override
12052        protected boolean isPackageForFilter(String packageName,
12053                PackageParser.ActivityIntentInfo info) {
12054            return packageName.equals(info.activity.owner.packageName);
12055        }
12056
12057        @Override
12058        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12059                int match, int userId) {
12060            if (!sUserManager.exists(userId)) return null;
12061            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12062                return null;
12063            }
12064            final PackageParser.Activity activity = info.activity;
12065            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12066            if (ps == null) {
12067                return null;
12068            }
12069            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12070                    ps.readUserState(userId), userId);
12071            if (ai == null) {
12072                return null;
12073            }
12074            final ResolveInfo res = new ResolveInfo();
12075            res.activityInfo = ai;
12076            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12077                res.filter = info;
12078            }
12079            if (info != null) {
12080                res.handleAllWebDataURI = info.handleAllWebDataURI();
12081            }
12082            res.priority = info.getPriority();
12083            res.preferredOrder = activity.owner.mPreferredOrder;
12084            //System.out.println("Result: " + res.activityInfo.className +
12085            //                   " = " + res.priority);
12086            res.match = match;
12087            res.isDefault = info.hasDefault;
12088            res.labelRes = info.labelRes;
12089            res.nonLocalizedLabel = info.nonLocalizedLabel;
12090            if (userNeedsBadging(userId)) {
12091                res.noResourceId = true;
12092            } else {
12093                res.icon = info.icon;
12094            }
12095            res.iconResourceId = info.icon;
12096            res.system = res.activityInfo.applicationInfo.isSystemApp();
12097            return res;
12098        }
12099
12100        @Override
12101        protected void sortResults(List<ResolveInfo> results) {
12102            Collections.sort(results, mResolvePrioritySorter);
12103        }
12104
12105        @Override
12106        protected void dumpFilter(PrintWriter out, String prefix,
12107                PackageParser.ActivityIntentInfo filter) {
12108            out.print(prefix); out.print(
12109                    Integer.toHexString(System.identityHashCode(filter.activity)));
12110                    out.print(' ');
12111                    filter.activity.printComponentShortName(out);
12112                    out.print(" filter ");
12113                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12114        }
12115
12116        @Override
12117        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12118            return filter.activity;
12119        }
12120
12121        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12122            PackageParser.Activity activity = (PackageParser.Activity)label;
12123            out.print(prefix); out.print(
12124                    Integer.toHexString(System.identityHashCode(activity)));
12125                    out.print(' ');
12126                    activity.printComponentShortName(out);
12127            if (count > 1) {
12128                out.print(" ("); out.print(count); out.print(" filters)");
12129            }
12130            out.println();
12131        }
12132
12133        // Keys are String (activity class name), values are Activity.
12134        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12135                = new ArrayMap<ComponentName, PackageParser.Activity>();
12136        private int mFlags;
12137    }
12138
12139    private final class ServiceIntentResolver
12140            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12141        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12142                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12143            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12144            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12145                    isEphemeral, userId);
12146        }
12147
12148        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12149                int userId) {
12150            if (!sUserManager.exists(userId)) return null;
12151            mFlags = flags;
12152            return super.queryIntent(intent, resolvedType,
12153                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12154                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12155                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12156        }
12157
12158        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12159                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12160            if (!sUserManager.exists(userId)) return null;
12161            if (packageServices == null) {
12162                return null;
12163            }
12164            mFlags = flags;
12165            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12166            final boolean vislbleToEphemeral =
12167                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12168            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12169            final int N = packageServices.size();
12170            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12171                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12172
12173            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12174            for (int i = 0; i < N; ++i) {
12175                intentFilters = packageServices.get(i).intents;
12176                if (intentFilters != null && intentFilters.size() > 0) {
12177                    PackageParser.ServiceIntentInfo[] array =
12178                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12179                    intentFilters.toArray(array);
12180                    listCut.add(array);
12181                }
12182            }
12183            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12184                    vislbleToEphemeral, isEphemeral, listCut, userId);
12185        }
12186
12187        public final void addService(PackageParser.Service s) {
12188            mServices.put(s.getComponentName(), s);
12189            if (DEBUG_SHOW_INFO) {
12190                Log.v(TAG, "  "
12191                        + (s.info.nonLocalizedLabel != null
12192                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12193                Log.v(TAG, "    Class=" + s.info.name);
12194            }
12195            final int NI = s.intents.size();
12196            int j;
12197            for (j=0; j<NI; j++) {
12198                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12199                if (DEBUG_SHOW_INFO) {
12200                    Log.v(TAG, "    IntentFilter:");
12201                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12202                }
12203                if (!intent.debugCheck()) {
12204                    Log.w(TAG, "==> For Service " + s.info.name);
12205                }
12206                addFilter(intent);
12207            }
12208        }
12209
12210        public final void removeService(PackageParser.Service s) {
12211            mServices.remove(s.getComponentName());
12212            if (DEBUG_SHOW_INFO) {
12213                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12214                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12215                Log.v(TAG, "    Class=" + s.info.name);
12216            }
12217            final int NI = s.intents.size();
12218            int j;
12219            for (j=0; j<NI; j++) {
12220                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12221                if (DEBUG_SHOW_INFO) {
12222                    Log.v(TAG, "    IntentFilter:");
12223                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12224                }
12225                removeFilter(intent);
12226            }
12227        }
12228
12229        @Override
12230        protected boolean allowFilterResult(
12231                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12232            ServiceInfo filterSi = filter.service.info;
12233            for (int i=dest.size()-1; i>=0; i--) {
12234                ServiceInfo destAi = dest.get(i).serviceInfo;
12235                if (destAi.name == filterSi.name
12236                        && destAi.packageName == filterSi.packageName) {
12237                    return false;
12238                }
12239            }
12240            return true;
12241        }
12242
12243        @Override
12244        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12245            return new PackageParser.ServiceIntentInfo[size];
12246        }
12247
12248        @Override
12249        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12250            if (!sUserManager.exists(userId)) return true;
12251            PackageParser.Package p = filter.service.owner;
12252            if (p != null) {
12253                PackageSetting ps = (PackageSetting)p.mExtras;
12254                if (ps != null) {
12255                    // System apps are never considered stopped for purposes of
12256                    // filtering, because there may be no way for the user to
12257                    // actually re-launch them.
12258                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12259                            && ps.getStopped(userId);
12260                }
12261            }
12262            return false;
12263        }
12264
12265        @Override
12266        protected boolean isPackageForFilter(String packageName,
12267                PackageParser.ServiceIntentInfo info) {
12268            return packageName.equals(info.service.owner.packageName);
12269        }
12270
12271        @Override
12272        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12273                int match, int userId) {
12274            if (!sUserManager.exists(userId)) return null;
12275            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12276            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12277                return null;
12278            }
12279            final PackageParser.Service service = info.service;
12280            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12281            if (ps == null) {
12282                return null;
12283            }
12284            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12285                    ps.readUserState(userId), userId);
12286            if (si == null) {
12287                return null;
12288            }
12289            final ResolveInfo res = new ResolveInfo();
12290            res.serviceInfo = si;
12291            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12292                res.filter = filter;
12293            }
12294            res.priority = info.getPriority();
12295            res.preferredOrder = service.owner.mPreferredOrder;
12296            res.match = match;
12297            res.isDefault = info.hasDefault;
12298            res.labelRes = info.labelRes;
12299            res.nonLocalizedLabel = info.nonLocalizedLabel;
12300            res.icon = info.icon;
12301            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12302            return res;
12303        }
12304
12305        @Override
12306        protected void sortResults(List<ResolveInfo> results) {
12307            Collections.sort(results, mResolvePrioritySorter);
12308        }
12309
12310        @Override
12311        protected void dumpFilter(PrintWriter out, String prefix,
12312                PackageParser.ServiceIntentInfo filter) {
12313            out.print(prefix); out.print(
12314                    Integer.toHexString(System.identityHashCode(filter.service)));
12315                    out.print(' ');
12316                    filter.service.printComponentShortName(out);
12317                    out.print(" filter ");
12318                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12319        }
12320
12321        @Override
12322        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12323            return filter.service;
12324        }
12325
12326        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12327            PackageParser.Service service = (PackageParser.Service)label;
12328            out.print(prefix); out.print(
12329                    Integer.toHexString(System.identityHashCode(service)));
12330                    out.print(' ');
12331                    service.printComponentShortName(out);
12332            if (count > 1) {
12333                out.print(" ("); out.print(count); out.print(" filters)");
12334            }
12335            out.println();
12336        }
12337
12338//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12339//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12340//            final List<ResolveInfo> retList = Lists.newArrayList();
12341//            while (i.hasNext()) {
12342//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12343//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12344//                    retList.add(resolveInfo);
12345//                }
12346//            }
12347//            return retList;
12348//        }
12349
12350        // Keys are String (activity class name), values are Activity.
12351        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12352                = new ArrayMap<ComponentName, PackageParser.Service>();
12353        private int mFlags;
12354    }
12355
12356    private final class ProviderIntentResolver
12357            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12358        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12359                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12360            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12361            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12362                    isEphemeral, userId);
12363        }
12364
12365        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12366                int userId) {
12367            if (!sUserManager.exists(userId))
12368                return null;
12369            mFlags = flags;
12370            return super.queryIntent(intent, resolvedType,
12371                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12372                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12373                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12374        }
12375
12376        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12377                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12378            if (!sUserManager.exists(userId))
12379                return null;
12380            if (packageProviders == null) {
12381                return null;
12382            }
12383            mFlags = flags;
12384            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12385            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12386            final boolean vislbleToEphemeral =
12387                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12388            final int N = packageProviders.size();
12389            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12390                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12391
12392            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12393            for (int i = 0; i < N; ++i) {
12394                intentFilters = packageProviders.get(i).intents;
12395                if (intentFilters != null && intentFilters.size() > 0) {
12396                    PackageParser.ProviderIntentInfo[] array =
12397                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12398                    intentFilters.toArray(array);
12399                    listCut.add(array);
12400                }
12401            }
12402            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12403                    vislbleToEphemeral, isEphemeral, listCut, userId);
12404        }
12405
12406        public final void addProvider(PackageParser.Provider p) {
12407            if (mProviders.containsKey(p.getComponentName())) {
12408                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12409                return;
12410            }
12411
12412            mProviders.put(p.getComponentName(), p);
12413            if (DEBUG_SHOW_INFO) {
12414                Log.v(TAG, "  "
12415                        + (p.info.nonLocalizedLabel != null
12416                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12417                Log.v(TAG, "    Class=" + p.info.name);
12418            }
12419            final int NI = p.intents.size();
12420            int j;
12421            for (j = 0; j < NI; j++) {
12422                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12423                if (DEBUG_SHOW_INFO) {
12424                    Log.v(TAG, "    IntentFilter:");
12425                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12426                }
12427                if (!intent.debugCheck()) {
12428                    Log.w(TAG, "==> For Provider " + p.info.name);
12429                }
12430                addFilter(intent);
12431            }
12432        }
12433
12434        public final void removeProvider(PackageParser.Provider p) {
12435            mProviders.remove(p.getComponentName());
12436            if (DEBUG_SHOW_INFO) {
12437                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12438                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12439                Log.v(TAG, "    Class=" + p.info.name);
12440            }
12441            final int NI = p.intents.size();
12442            int j;
12443            for (j = 0; j < NI; j++) {
12444                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12445                if (DEBUG_SHOW_INFO) {
12446                    Log.v(TAG, "    IntentFilter:");
12447                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12448                }
12449                removeFilter(intent);
12450            }
12451        }
12452
12453        @Override
12454        protected boolean allowFilterResult(
12455                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12456            ProviderInfo filterPi = filter.provider.info;
12457            for (int i = dest.size() - 1; i >= 0; i--) {
12458                ProviderInfo destPi = dest.get(i).providerInfo;
12459                if (destPi.name == filterPi.name
12460                        && destPi.packageName == filterPi.packageName) {
12461                    return false;
12462                }
12463            }
12464            return true;
12465        }
12466
12467        @Override
12468        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12469            return new PackageParser.ProviderIntentInfo[size];
12470        }
12471
12472        @Override
12473        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12474            if (!sUserManager.exists(userId))
12475                return true;
12476            PackageParser.Package p = filter.provider.owner;
12477            if (p != null) {
12478                PackageSetting ps = (PackageSetting) p.mExtras;
12479                if (ps != null) {
12480                    // System apps are never considered stopped for purposes of
12481                    // filtering, because there may be no way for the user to
12482                    // actually re-launch them.
12483                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12484                            && ps.getStopped(userId);
12485                }
12486            }
12487            return false;
12488        }
12489
12490        @Override
12491        protected boolean isPackageForFilter(String packageName,
12492                PackageParser.ProviderIntentInfo info) {
12493            return packageName.equals(info.provider.owner.packageName);
12494        }
12495
12496        @Override
12497        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12498                int match, int userId) {
12499            if (!sUserManager.exists(userId))
12500                return null;
12501            final PackageParser.ProviderIntentInfo info = filter;
12502            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12503                return null;
12504            }
12505            final PackageParser.Provider provider = info.provider;
12506            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12507            if (ps == null) {
12508                return null;
12509            }
12510            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12511                    ps.readUserState(userId), userId);
12512            if (pi == null) {
12513                return null;
12514            }
12515            final ResolveInfo res = new ResolveInfo();
12516            res.providerInfo = pi;
12517            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12518                res.filter = filter;
12519            }
12520            res.priority = info.getPriority();
12521            res.preferredOrder = provider.owner.mPreferredOrder;
12522            res.match = match;
12523            res.isDefault = info.hasDefault;
12524            res.labelRes = info.labelRes;
12525            res.nonLocalizedLabel = info.nonLocalizedLabel;
12526            res.icon = info.icon;
12527            res.system = res.providerInfo.applicationInfo.isSystemApp();
12528            return res;
12529        }
12530
12531        @Override
12532        protected void sortResults(List<ResolveInfo> results) {
12533            Collections.sort(results, mResolvePrioritySorter);
12534        }
12535
12536        @Override
12537        protected void dumpFilter(PrintWriter out, String prefix,
12538                PackageParser.ProviderIntentInfo filter) {
12539            out.print(prefix);
12540            out.print(
12541                    Integer.toHexString(System.identityHashCode(filter.provider)));
12542            out.print(' ');
12543            filter.provider.printComponentShortName(out);
12544            out.print(" filter ");
12545            out.println(Integer.toHexString(System.identityHashCode(filter)));
12546        }
12547
12548        @Override
12549        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12550            return filter.provider;
12551        }
12552
12553        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12554            PackageParser.Provider provider = (PackageParser.Provider)label;
12555            out.print(prefix); out.print(
12556                    Integer.toHexString(System.identityHashCode(provider)));
12557                    out.print(' ');
12558                    provider.printComponentShortName(out);
12559            if (count > 1) {
12560                out.print(" ("); out.print(count); out.print(" filters)");
12561            }
12562            out.println();
12563        }
12564
12565        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12566                = new ArrayMap<ComponentName, PackageParser.Provider>();
12567        private int mFlags;
12568    }
12569
12570    static final class EphemeralIntentResolver
12571            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12572        /**
12573         * The result that has the highest defined order. Ordering applies on a
12574         * per-package basis. Mapping is from package name to Pair of order and
12575         * EphemeralResolveInfo.
12576         * <p>
12577         * NOTE: This is implemented as a field variable for convenience and efficiency.
12578         * By having a field variable, we're able to track filter ordering as soon as
12579         * a non-zero order is defined. Otherwise, multiple loops across the result set
12580         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12581         * this needs to be contained entirely within {@link #filterResults()}.
12582         */
12583        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12584
12585        @Override
12586        protected EphemeralResponse[] newArray(int size) {
12587            return new EphemeralResponse[size];
12588        }
12589
12590        @Override
12591        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12592            return true;
12593        }
12594
12595        @Override
12596        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12597                int userId) {
12598            if (!sUserManager.exists(userId)) {
12599                return null;
12600            }
12601            final String packageName = responseObj.resolveInfo.getPackageName();
12602            final Integer order = responseObj.getOrder();
12603            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12604                    mOrderResult.get(packageName);
12605            // ordering is enabled and this item's order isn't high enough
12606            if (lastOrderResult != null && lastOrderResult.first >= order) {
12607                return null;
12608            }
12609            final EphemeralResolveInfo res = responseObj.resolveInfo;
12610            if (order > 0) {
12611                // non-zero order, enable ordering
12612                mOrderResult.put(packageName, new Pair<>(order, res));
12613            }
12614            return responseObj;
12615        }
12616
12617        @Override
12618        protected void filterResults(List<EphemeralResponse> results) {
12619            // only do work if ordering is enabled [most of the time it won't be]
12620            if (mOrderResult.size() == 0) {
12621                return;
12622            }
12623            int resultSize = results.size();
12624            for (int i = 0; i < resultSize; i++) {
12625                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12626                final String packageName = info.getPackageName();
12627                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12628                if (savedInfo == null) {
12629                    // package doesn't having ordering
12630                    continue;
12631                }
12632                if (savedInfo.second == info) {
12633                    // circled back to the highest ordered item; remove from order list
12634                    mOrderResult.remove(savedInfo);
12635                    if (mOrderResult.size() == 0) {
12636                        // no more ordered items
12637                        break;
12638                    }
12639                    continue;
12640                }
12641                // item has a worse order, remove it from the result list
12642                results.remove(i);
12643                resultSize--;
12644                i--;
12645            }
12646        }
12647    }
12648
12649    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12650            new Comparator<ResolveInfo>() {
12651        public int compare(ResolveInfo r1, ResolveInfo r2) {
12652            int v1 = r1.priority;
12653            int v2 = r2.priority;
12654            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12655            if (v1 != v2) {
12656                return (v1 > v2) ? -1 : 1;
12657            }
12658            v1 = r1.preferredOrder;
12659            v2 = r2.preferredOrder;
12660            if (v1 != v2) {
12661                return (v1 > v2) ? -1 : 1;
12662            }
12663            if (r1.isDefault != r2.isDefault) {
12664                return r1.isDefault ? -1 : 1;
12665            }
12666            v1 = r1.match;
12667            v2 = r2.match;
12668            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12669            if (v1 != v2) {
12670                return (v1 > v2) ? -1 : 1;
12671            }
12672            if (r1.system != r2.system) {
12673                return r1.system ? -1 : 1;
12674            }
12675            if (r1.activityInfo != null) {
12676                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12677            }
12678            if (r1.serviceInfo != null) {
12679                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12680            }
12681            if (r1.providerInfo != null) {
12682                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12683            }
12684            return 0;
12685        }
12686    };
12687
12688    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12689            new Comparator<ProviderInfo>() {
12690        public int compare(ProviderInfo p1, ProviderInfo p2) {
12691            final int v1 = p1.initOrder;
12692            final int v2 = p2.initOrder;
12693            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12694        }
12695    };
12696
12697    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12698            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12699            final int[] userIds) {
12700        mHandler.post(new Runnable() {
12701            @Override
12702            public void run() {
12703                try {
12704                    final IActivityManager am = ActivityManager.getService();
12705                    if (am == null) return;
12706                    final int[] resolvedUserIds;
12707                    if (userIds == null) {
12708                        resolvedUserIds = am.getRunningUserIds();
12709                    } else {
12710                        resolvedUserIds = userIds;
12711                    }
12712                    for (int id : resolvedUserIds) {
12713                        final Intent intent = new Intent(action,
12714                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12715                        if (extras != null) {
12716                            intent.putExtras(extras);
12717                        }
12718                        if (targetPkg != null) {
12719                            intent.setPackage(targetPkg);
12720                        }
12721                        // Modify the UID when posting to other users
12722                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12723                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12724                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12725                            intent.putExtra(Intent.EXTRA_UID, uid);
12726                        }
12727                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12728                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12729                        if (DEBUG_BROADCASTS) {
12730                            RuntimeException here = new RuntimeException("here");
12731                            here.fillInStackTrace();
12732                            Slog.d(TAG, "Sending to user " + id + ": "
12733                                    + intent.toShortString(false, true, false, false)
12734                                    + " " + intent.getExtras(), here);
12735                        }
12736                        am.broadcastIntent(null, intent, null, finishedReceiver,
12737                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12738                                null, finishedReceiver != null, false, id);
12739                    }
12740                } catch (RemoteException ex) {
12741                }
12742            }
12743        });
12744    }
12745
12746    /**
12747     * Check if the external storage media is available. This is true if there
12748     * is a mounted external storage medium or if the external storage is
12749     * emulated.
12750     */
12751    private boolean isExternalMediaAvailable() {
12752        return mMediaMounted || Environment.isExternalStorageEmulated();
12753    }
12754
12755    @Override
12756    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12757        // writer
12758        synchronized (mPackages) {
12759            if (!isExternalMediaAvailable()) {
12760                // If the external storage is no longer mounted at this point,
12761                // the caller may not have been able to delete all of this
12762                // packages files and can not delete any more.  Bail.
12763                return null;
12764            }
12765            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12766            if (lastPackage != null) {
12767                pkgs.remove(lastPackage);
12768            }
12769            if (pkgs.size() > 0) {
12770                return pkgs.get(0);
12771            }
12772        }
12773        return null;
12774    }
12775
12776    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12777        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12778                userId, andCode ? 1 : 0, packageName);
12779        if (mSystemReady) {
12780            msg.sendToTarget();
12781        } else {
12782            if (mPostSystemReadyMessages == null) {
12783                mPostSystemReadyMessages = new ArrayList<>();
12784            }
12785            mPostSystemReadyMessages.add(msg);
12786        }
12787    }
12788
12789    void startCleaningPackages() {
12790        // reader
12791        if (!isExternalMediaAvailable()) {
12792            return;
12793        }
12794        synchronized (mPackages) {
12795            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12796                return;
12797            }
12798        }
12799        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12800        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12801        IActivityManager am = ActivityManager.getService();
12802        if (am != null) {
12803            try {
12804                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12805                        UserHandle.USER_SYSTEM);
12806            } catch (RemoteException e) {
12807            }
12808        }
12809    }
12810
12811    @Override
12812    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12813            int installFlags, String installerPackageName, int userId) {
12814        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12815
12816        final int callingUid = Binder.getCallingUid();
12817        enforceCrossUserPermission(callingUid, userId,
12818                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12819
12820        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12821            try {
12822                if (observer != null) {
12823                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12824                }
12825            } catch (RemoteException re) {
12826            }
12827            return;
12828        }
12829
12830        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12831            installFlags |= PackageManager.INSTALL_FROM_ADB;
12832
12833        } else {
12834            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12835            // about installerPackageName.
12836
12837            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12838            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12839        }
12840
12841        UserHandle user;
12842        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12843            user = UserHandle.ALL;
12844        } else {
12845            user = new UserHandle(userId);
12846        }
12847
12848        // Only system components can circumvent runtime permissions when installing.
12849        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12850                && mContext.checkCallingOrSelfPermission(Manifest.permission
12851                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12852            throw new SecurityException("You need the "
12853                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12854                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12855        }
12856
12857        final File originFile = new File(originPath);
12858        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12859
12860        final Message msg = mHandler.obtainMessage(INIT_COPY);
12861        final VerificationInfo verificationInfo = new VerificationInfo(
12862                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12863        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12864                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12865                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12866                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12867        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12868        msg.obj = params;
12869
12870        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12871                System.identityHashCode(msg.obj));
12872        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12873                System.identityHashCode(msg.obj));
12874
12875        mHandler.sendMessage(msg);
12876    }
12877
12878
12879    /**
12880     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12881     * it is acting on behalf on an enterprise or the user).
12882     *
12883     * Note that the ordering of the conditionals in this method is important. The checks we perform
12884     * are as follows, in this order:
12885     *
12886     * 1) If the install is being performed by a system app, we can trust the app to have set the
12887     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12888     *    what it is.
12889     * 2) If the install is being performed by a device or profile owner app, the install reason
12890     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12891     *    set the install reason correctly. If the app targets an older SDK version where install
12892     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12893     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12894     * 3) In all other cases, the install is being performed by a regular app that is neither part
12895     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12896     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12897     *    set to enterprise policy and if so, change it to unknown instead.
12898     */
12899    private int fixUpInstallReason(String installerPackageName, int installerUid,
12900            int installReason) {
12901        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12902                == PERMISSION_GRANTED) {
12903            // If the install is being performed by a system app, we trust that app to have set the
12904            // install reason correctly.
12905            return installReason;
12906        }
12907
12908        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12909            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12910        if (dpm != null) {
12911            ComponentName owner = null;
12912            try {
12913                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12914                if (owner == null) {
12915                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12916                }
12917            } catch (RemoteException e) {
12918            }
12919            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12920                // If the install is being performed by a device or profile owner, the install
12921                // reason should be enterprise policy.
12922                return PackageManager.INSTALL_REASON_POLICY;
12923            }
12924        }
12925
12926        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12927            // If the install is being performed by a regular app (i.e. neither system app nor
12928            // device or profile owner), we have no reason to believe that the app is acting on
12929            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12930            // change it to unknown instead.
12931            return PackageManager.INSTALL_REASON_UNKNOWN;
12932        }
12933
12934        // If the install is being performed by a regular app and the install reason was set to any
12935        // value but enterprise policy, leave the install reason unchanged.
12936        return installReason;
12937    }
12938
12939    void installStage(String packageName, File stagedDir, String stagedCid,
12940            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12941            String installerPackageName, int installerUid, UserHandle user,
12942            Certificate[][] certificates) {
12943        if (DEBUG_EPHEMERAL) {
12944            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12945                Slog.d(TAG, "Ephemeral install of " + packageName);
12946            }
12947        }
12948        final VerificationInfo verificationInfo = new VerificationInfo(
12949                sessionParams.originatingUri, sessionParams.referrerUri,
12950                sessionParams.originatingUid, installerUid);
12951
12952        final OriginInfo origin;
12953        if (stagedDir != null) {
12954            origin = OriginInfo.fromStagedFile(stagedDir);
12955        } else {
12956            origin = OriginInfo.fromStagedContainer(stagedCid);
12957        }
12958
12959        final Message msg = mHandler.obtainMessage(INIT_COPY);
12960        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
12961                sessionParams.installReason);
12962        final InstallParams params = new InstallParams(origin, null, observer,
12963                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12964                verificationInfo, user, sessionParams.abiOverride,
12965                sessionParams.grantedRuntimePermissions, certificates, installReason);
12966        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12967        msg.obj = params;
12968
12969        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12970                System.identityHashCode(msg.obj));
12971        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12972                System.identityHashCode(msg.obj));
12973
12974        mHandler.sendMessage(msg);
12975    }
12976
12977    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12978            int userId) {
12979        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12980        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12981    }
12982
12983    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12984            int appId, int... userIds) {
12985        if (ArrayUtils.isEmpty(userIds)) {
12986            return;
12987        }
12988        Bundle extras = new Bundle(1);
12989        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12990        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12991
12992        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12993                packageName, extras, 0, null, null, userIds);
12994        if (isSystem) {
12995            mHandler.post(() -> {
12996                        for (int userId : userIds) {
12997                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12998                        }
12999                    }
13000            );
13001        }
13002    }
13003
13004    /**
13005     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13006     * automatically without needing an explicit launch.
13007     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13008     */
13009    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13010        // If user is not running, the app didn't miss any broadcast
13011        if (!mUserManagerInternal.isUserRunning(userId)) {
13012            return;
13013        }
13014        final IActivityManager am = ActivityManager.getService();
13015        try {
13016            // Deliver LOCKED_BOOT_COMPLETED first
13017            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13018                    .setPackage(packageName);
13019            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13020            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13021                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13022
13023            // Deliver BOOT_COMPLETED only if user is unlocked
13024            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13025                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13026                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13027                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13028            }
13029        } catch (RemoteException e) {
13030            throw e.rethrowFromSystemServer();
13031        }
13032    }
13033
13034    @Override
13035    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13036            int userId) {
13037        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13038        PackageSetting pkgSetting;
13039        final int uid = Binder.getCallingUid();
13040        enforceCrossUserPermission(uid, userId,
13041                true /* requireFullPermission */, true /* checkShell */,
13042                "setApplicationHiddenSetting for user " + userId);
13043
13044        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13045            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13046            return false;
13047        }
13048
13049        long callingId = Binder.clearCallingIdentity();
13050        try {
13051            boolean sendAdded = false;
13052            boolean sendRemoved = false;
13053            // writer
13054            synchronized (mPackages) {
13055                pkgSetting = mSettings.mPackages.get(packageName);
13056                if (pkgSetting == null) {
13057                    return false;
13058                }
13059                // Do not allow "android" is being disabled
13060                if ("android".equals(packageName)) {
13061                    Slog.w(TAG, "Cannot hide package: android");
13062                    return false;
13063                }
13064                // Cannot hide static shared libs as they are considered
13065                // a part of the using app (emulating static linking). Also
13066                // static libs are installed always on internal storage.
13067                PackageParser.Package pkg = mPackages.get(packageName);
13068                if (pkg != null && pkg.staticSharedLibName != null) {
13069                    Slog.w(TAG, "Cannot hide package: " + packageName
13070                            + " providing static shared library: "
13071                            + pkg.staticSharedLibName);
13072                    return false;
13073                }
13074                // Only allow protected packages to hide themselves.
13075                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13076                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13077                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13078                    return false;
13079                }
13080
13081                if (pkgSetting.getHidden(userId) != hidden) {
13082                    pkgSetting.setHidden(hidden, userId);
13083                    mSettings.writePackageRestrictionsLPr(userId);
13084                    if (hidden) {
13085                        sendRemoved = true;
13086                    } else {
13087                        sendAdded = true;
13088                    }
13089                }
13090            }
13091            if (sendAdded) {
13092                sendPackageAddedForUser(packageName, pkgSetting, userId);
13093                return true;
13094            }
13095            if (sendRemoved) {
13096                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13097                        "hiding pkg");
13098                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13099                return true;
13100            }
13101        } finally {
13102            Binder.restoreCallingIdentity(callingId);
13103        }
13104        return false;
13105    }
13106
13107    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13108            int userId) {
13109        final PackageRemovedInfo info = new PackageRemovedInfo();
13110        info.removedPackage = packageName;
13111        info.removedUsers = new int[] {userId};
13112        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13113        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13114    }
13115
13116    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13117        if (pkgList.length > 0) {
13118            Bundle extras = new Bundle(1);
13119            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13120
13121            sendPackageBroadcast(
13122                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13123                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13124                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13125                    new int[] {userId});
13126        }
13127    }
13128
13129    /**
13130     * Returns true if application is not found or there was an error. Otherwise it returns
13131     * the hidden state of the package for the given user.
13132     */
13133    @Override
13134    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13135        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13136        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13137                true /* requireFullPermission */, false /* checkShell */,
13138                "getApplicationHidden for user " + userId);
13139        PackageSetting pkgSetting;
13140        long callingId = Binder.clearCallingIdentity();
13141        try {
13142            // writer
13143            synchronized (mPackages) {
13144                pkgSetting = mSettings.mPackages.get(packageName);
13145                if (pkgSetting == null) {
13146                    return true;
13147                }
13148                return pkgSetting.getHidden(userId);
13149            }
13150        } finally {
13151            Binder.restoreCallingIdentity(callingId);
13152        }
13153    }
13154
13155    /**
13156     * @hide
13157     */
13158    @Override
13159    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13160        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13161                null);
13162        PackageSetting pkgSetting;
13163        final int uid = Binder.getCallingUid();
13164        enforceCrossUserPermission(uid, userId,
13165                true /* requireFullPermission */, true /* checkShell */,
13166                "installExistingPackage for user " + userId);
13167        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13168            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13169        }
13170
13171        long callingId = Binder.clearCallingIdentity();
13172        try {
13173            boolean installed = false;
13174
13175            // writer
13176            synchronized (mPackages) {
13177                pkgSetting = mSettings.mPackages.get(packageName);
13178                if (pkgSetting == null) {
13179                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13180                }
13181                if (!pkgSetting.getInstalled(userId)) {
13182                    pkgSetting.setInstalled(true, userId);
13183                    pkgSetting.setHidden(false, userId);
13184                    pkgSetting.setInstallReason(installReason, userId);
13185                    mSettings.writePackageRestrictionsLPr(userId);
13186                    installed = true;
13187                }
13188            }
13189
13190            if (installed) {
13191                if (pkgSetting.pkg != null) {
13192                    synchronized (mInstallLock) {
13193                        // We don't need to freeze for a brand new install
13194                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13195                    }
13196                }
13197                sendPackageAddedForUser(packageName, pkgSetting, userId);
13198            }
13199        } finally {
13200            Binder.restoreCallingIdentity(callingId);
13201        }
13202
13203        return PackageManager.INSTALL_SUCCEEDED;
13204    }
13205
13206    boolean isUserRestricted(int userId, String restrictionKey) {
13207        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13208        if (restrictions.getBoolean(restrictionKey, false)) {
13209            Log.w(TAG, "User is restricted: " + restrictionKey);
13210            return true;
13211        }
13212        return false;
13213    }
13214
13215    @Override
13216    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13217            int userId) {
13218        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13220                true /* requireFullPermission */, true /* checkShell */,
13221                "setPackagesSuspended for user " + userId);
13222
13223        if (ArrayUtils.isEmpty(packageNames)) {
13224            return packageNames;
13225        }
13226
13227        // List of package names for whom the suspended state has changed.
13228        List<String> changedPackages = new ArrayList<>(packageNames.length);
13229        // List of package names for whom the suspended state is not set as requested in this
13230        // method.
13231        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13232        long callingId = Binder.clearCallingIdentity();
13233        try {
13234            for (int i = 0; i < packageNames.length; i++) {
13235                String packageName = packageNames[i];
13236                boolean changed = false;
13237                final int appId;
13238                synchronized (mPackages) {
13239                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13240                    if (pkgSetting == null) {
13241                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13242                                + "\". Skipping suspending/un-suspending.");
13243                        unactionedPackages.add(packageName);
13244                        continue;
13245                    }
13246                    appId = pkgSetting.appId;
13247                    if (pkgSetting.getSuspended(userId) != suspended) {
13248                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13249                            unactionedPackages.add(packageName);
13250                            continue;
13251                        }
13252                        pkgSetting.setSuspended(suspended, userId);
13253                        mSettings.writePackageRestrictionsLPr(userId);
13254                        changed = true;
13255                        changedPackages.add(packageName);
13256                    }
13257                }
13258
13259                if (changed && suspended) {
13260                    killApplication(packageName, UserHandle.getUid(userId, appId),
13261                            "suspending package");
13262                }
13263            }
13264        } finally {
13265            Binder.restoreCallingIdentity(callingId);
13266        }
13267
13268        if (!changedPackages.isEmpty()) {
13269            sendPackagesSuspendedForUser(changedPackages.toArray(
13270                    new String[changedPackages.size()]), userId, suspended);
13271        }
13272
13273        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13274    }
13275
13276    @Override
13277    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13279                true /* requireFullPermission */, false /* checkShell */,
13280                "isPackageSuspendedForUser for user " + userId);
13281        synchronized (mPackages) {
13282            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13283            if (pkgSetting == null) {
13284                throw new IllegalArgumentException("Unknown target package: " + packageName);
13285            }
13286            return pkgSetting.getSuspended(userId);
13287        }
13288    }
13289
13290    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13291        if (isPackageDeviceAdmin(packageName, userId)) {
13292            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13293                    + "\": has an active device admin");
13294            return false;
13295        }
13296
13297        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13298        if (packageName.equals(activeLauncherPackageName)) {
13299            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13300                    + "\": contains the active launcher");
13301            return false;
13302        }
13303
13304        if (packageName.equals(mRequiredInstallerPackage)) {
13305            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13306                    + "\": required for package installation");
13307            return false;
13308        }
13309
13310        if (packageName.equals(mRequiredUninstallerPackage)) {
13311            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13312                    + "\": required for package uninstallation");
13313            return false;
13314        }
13315
13316        if (packageName.equals(mRequiredVerifierPackage)) {
13317            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13318                    + "\": required for package verification");
13319            return false;
13320        }
13321
13322        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13323            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13324                    + "\": is the default dialer");
13325            return false;
13326        }
13327
13328        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13329            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13330                    + "\": protected package");
13331            return false;
13332        }
13333
13334        // Cannot suspend static shared libs as they are considered
13335        // a part of the using app (emulating static linking). Also
13336        // static libs are installed always on internal storage.
13337        PackageParser.Package pkg = mPackages.get(packageName);
13338        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13339            Slog.w(TAG, "Cannot suspend package: " + packageName
13340                    + " providing static shared library: "
13341                    + pkg.staticSharedLibName);
13342            return false;
13343        }
13344
13345        return true;
13346    }
13347
13348    private String getActiveLauncherPackageName(int userId) {
13349        Intent intent = new Intent(Intent.ACTION_MAIN);
13350        intent.addCategory(Intent.CATEGORY_HOME);
13351        ResolveInfo resolveInfo = resolveIntent(
13352                intent,
13353                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13354                PackageManager.MATCH_DEFAULT_ONLY,
13355                userId);
13356
13357        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13358    }
13359
13360    private String getDefaultDialerPackageName(int userId) {
13361        synchronized (mPackages) {
13362            return mSettings.getDefaultDialerPackageNameLPw(userId);
13363        }
13364    }
13365
13366    @Override
13367    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13368        mContext.enforceCallingOrSelfPermission(
13369                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13370                "Only package verification agents can verify applications");
13371
13372        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13373        final PackageVerificationResponse response = new PackageVerificationResponse(
13374                verificationCode, Binder.getCallingUid());
13375        msg.arg1 = id;
13376        msg.obj = response;
13377        mHandler.sendMessage(msg);
13378    }
13379
13380    @Override
13381    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13382            long millisecondsToDelay) {
13383        mContext.enforceCallingOrSelfPermission(
13384                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13385                "Only package verification agents can extend verification timeouts");
13386
13387        final PackageVerificationState state = mPendingVerification.get(id);
13388        final PackageVerificationResponse response = new PackageVerificationResponse(
13389                verificationCodeAtTimeout, Binder.getCallingUid());
13390
13391        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13392            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13393        }
13394        if (millisecondsToDelay < 0) {
13395            millisecondsToDelay = 0;
13396        }
13397        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13398                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13399            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13400        }
13401
13402        if ((state != null) && !state.timeoutExtended()) {
13403            state.extendTimeout();
13404
13405            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13406            msg.arg1 = id;
13407            msg.obj = response;
13408            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13409        }
13410    }
13411
13412    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13413            int verificationCode, UserHandle user) {
13414        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13415        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13416        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13417        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13418        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13419
13420        mContext.sendBroadcastAsUser(intent, user,
13421                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13422    }
13423
13424    private ComponentName matchComponentForVerifier(String packageName,
13425            List<ResolveInfo> receivers) {
13426        ActivityInfo targetReceiver = null;
13427
13428        final int NR = receivers.size();
13429        for (int i = 0; i < NR; i++) {
13430            final ResolveInfo info = receivers.get(i);
13431            if (info.activityInfo == null) {
13432                continue;
13433            }
13434
13435            if (packageName.equals(info.activityInfo.packageName)) {
13436                targetReceiver = info.activityInfo;
13437                break;
13438            }
13439        }
13440
13441        if (targetReceiver == null) {
13442            return null;
13443        }
13444
13445        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13446    }
13447
13448    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13449            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13450        if (pkgInfo.verifiers.length == 0) {
13451            return null;
13452        }
13453
13454        final int N = pkgInfo.verifiers.length;
13455        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13456        for (int i = 0; i < N; i++) {
13457            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13458
13459            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13460                    receivers);
13461            if (comp == null) {
13462                continue;
13463            }
13464
13465            final int verifierUid = getUidForVerifier(verifierInfo);
13466            if (verifierUid == -1) {
13467                continue;
13468            }
13469
13470            if (DEBUG_VERIFY) {
13471                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13472                        + " with the correct signature");
13473            }
13474            sufficientVerifiers.add(comp);
13475            verificationState.addSufficientVerifier(verifierUid);
13476        }
13477
13478        return sufficientVerifiers;
13479    }
13480
13481    private int getUidForVerifier(VerifierInfo verifierInfo) {
13482        synchronized (mPackages) {
13483            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13484            if (pkg == null) {
13485                return -1;
13486            } else if (pkg.mSignatures.length != 1) {
13487                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13488                        + " has more than one signature; ignoring");
13489                return -1;
13490            }
13491
13492            /*
13493             * If the public key of the package's signature does not match
13494             * our expected public key, then this is a different package and
13495             * we should skip.
13496             */
13497
13498            final byte[] expectedPublicKey;
13499            try {
13500                final Signature verifierSig = pkg.mSignatures[0];
13501                final PublicKey publicKey = verifierSig.getPublicKey();
13502                expectedPublicKey = publicKey.getEncoded();
13503            } catch (CertificateException e) {
13504                return -1;
13505            }
13506
13507            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13508
13509            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13510                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13511                        + " does not have the expected public key; ignoring");
13512                return -1;
13513            }
13514
13515            return pkg.applicationInfo.uid;
13516        }
13517    }
13518
13519    @Override
13520    public void finishPackageInstall(int token, boolean didLaunch) {
13521        enforceSystemOrRoot("Only the system is allowed to finish installs");
13522
13523        if (DEBUG_INSTALL) {
13524            Slog.v(TAG, "BM finishing package install for " + token);
13525        }
13526        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13527
13528        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13529        mHandler.sendMessage(msg);
13530    }
13531
13532    /**
13533     * Get the verification agent timeout.
13534     *
13535     * @return verification timeout in milliseconds
13536     */
13537    private long getVerificationTimeout() {
13538        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13539                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13540                DEFAULT_VERIFICATION_TIMEOUT);
13541    }
13542
13543    /**
13544     * Get the default verification agent response code.
13545     *
13546     * @return default verification response code
13547     */
13548    private int getDefaultVerificationResponse() {
13549        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13550                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13551                DEFAULT_VERIFICATION_RESPONSE);
13552    }
13553
13554    /**
13555     * Check whether or not package verification has been enabled.
13556     *
13557     * @return true if verification should be performed
13558     */
13559    private boolean isVerificationEnabled(int userId, int installFlags) {
13560        if (!DEFAULT_VERIFY_ENABLE) {
13561            return false;
13562        }
13563        // Ephemeral apps don't get the full verification treatment
13564        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13565            if (DEBUG_EPHEMERAL) {
13566                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13567            }
13568            return false;
13569        }
13570
13571        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13572
13573        // Check if installing from ADB
13574        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13575            // Do not run verification in a test harness environment
13576            if (ActivityManager.isRunningInTestHarness()) {
13577                return false;
13578            }
13579            if (ensureVerifyAppsEnabled) {
13580                return true;
13581            }
13582            // Check if the developer does not want package verification for ADB installs
13583            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13584                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13585                return false;
13586            }
13587        }
13588
13589        if (ensureVerifyAppsEnabled) {
13590            return true;
13591        }
13592
13593        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13594                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13595    }
13596
13597    @Override
13598    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13599            throws RemoteException {
13600        mContext.enforceCallingOrSelfPermission(
13601                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13602                "Only intentfilter verification agents can verify applications");
13603
13604        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13605        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13606                Binder.getCallingUid(), verificationCode, failedDomains);
13607        msg.arg1 = id;
13608        msg.obj = response;
13609        mHandler.sendMessage(msg);
13610    }
13611
13612    @Override
13613    public int getIntentVerificationStatus(String packageName, int userId) {
13614        synchronized (mPackages) {
13615            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13616        }
13617    }
13618
13619    @Override
13620    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13621        mContext.enforceCallingOrSelfPermission(
13622                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13623
13624        boolean result = false;
13625        synchronized (mPackages) {
13626            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13627        }
13628        if (result) {
13629            scheduleWritePackageRestrictionsLocked(userId);
13630        }
13631        return result;
13632    }
13633
13634    @Override
13635    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13636            String packageName) {
13637        synchronized (mPackages) {
13638            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13639        }
13640    }
13641
13642    @Override
13643    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13644        if (TextUtils.isEmpty(packageName)) {
13645            return ParceledListSlice.emptyList();
13646        }
13647        synchronized (mPackages) {
13648            PackageParser.Package pkg = mPackages.get(packageName);
13649            if (pkg == null || pkg.activities == null) {
13650                return ParceledListSlice.emptyList();
13651            }
13652            final int count = pkg.activities.size();
13653            ArrayList<IntentFilter> result = new ArrayList<>();
13654            for (int n=0; n<count; n++) {
13655                PackageParser.Activity activity = pkg.activities.get(n);
13656                if (activity.intents != null && activity.intents.size() > 0) {
13657                    result.addAll(activity.intents);
13658                }
13659            }
13660            return new ParceledListSlice<>(result);
13661        }
13662    }
13663
13664    @Override
13665    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13666        mContext.enforceCallingOrSelfPermission(
13667                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13668
13669        synchronized (mPackages) {
13670            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13671            if (packageName != null) {
13672                result |= updateIntentVerificationStatus(packageName,
13673                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13674                        userId);
13675                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13676                        packageName, userId);
13677            }
13678            return result;
13679        }
13680    }
13681
13682    @Override
13683    public String getDefaultBrowserPackageName(int userId) {
13684        synchronized (mPackages) {
13685            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13686        }
13687    }
13688
13689    /**
13690     * Get the "allow unknown sources" setting.
13691     *
13692     * @return the current "allow unknown sources" setting
13693     */
13694    private int getUnknownSourcesSettings() {
13695        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13696                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13697                -1);
13698    }
13699
13700    @Override
13701    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13702        final int uid = Binder.getCallingUid();
13703        // writer
13704        synchronized (mPackages) {
13705            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13706            if (targetPackageSetting == null) {
13707                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13708            }
13709
13710            PackageSetting installerPackageSetting;
13711            if (installerPackageName != null) {
13712                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13713                if (installerPackageSetting == null) {
13714                    throw new IllegalArgumentException("Unknown installer package: "
13715                            + installerPackageName);
13716                }
13717            } else {
13718                installerPackageSetting = null;
13719            }
13720
13721            Signature[] callerSignature;
13722            Object obj = mSettings.getUserIdLPr(uid);
13723            if (obj != null) {
13724                if (obj instanceof SharedUserSetting) {
13725                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13726                } else if (obj instanceof PackageSetting) {
13727                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13728                } else {
13729                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13730                }
13731            } else {
13732                throw new SecurityException("Unknown calling UID: " + uid);
13733            }
13734
13735            // Verify: can't set installerPackageName to a package that is
13736            // not signed with the same cert as the caller.
13737            if (installerPackageSetting != null) {
13738                if (compareSignatures(callerSignature,
13739                        installerPackageSetting.signatures.mSignatures)
13740                        != PackageManager.SIGNATURE_MATCH) {
13741                    throw new SecurityException(
13742                            "Caller does not have same cert as new installer package "
13743                            + installerPackageName);
13744                }
13745            }
13746
13747            // Verify: if target already has an installer package, it must
13748            // be signed with the same cert as the caller.
13749            if (targetPackageSetting.installerPackageName != null) {
13750                PackageSetting setting = mSettings.mPackages.get(
13751                        targetPackageSetting.installerPackageName);
13752                // If the currently set package isn't valid, then it's always
13753                // okay to change it.
13754                if (setting != null) {
13755                    if (compareSignatures(callerSignature,
13756                            setting.signatures.mSignatures)
13757                            != PackageManager.SIGNATURE_MATCH) {
13758                        throw new SecurityException(
13759                                "Caller does not have same cert as old installer package "
13760                                + targetPackageSetting.installerPackageName);
13761                    }
13762                }
13763            }
13764
13765            // Okay!
13766            targetPackageSetting.installerPackageName = installerPackageName;
13767            if (installerPackageName != null) {
13768                mSettings.mInstallerPackages.add(installerPackageName);
13769            }
13770            scheduleWriteSettingsLocked();
13771        }
13772    }
13773
13774    @Override
13775    public void setApplicationCategoryHint(String packageName, int categoryHint,
13776            String callerPackageName) {
13777        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13778                callerPackageName);
13779        synchronized (mPackages) {
13780            PackageSetting ps = mSettings.mPackages.get(packageName);
13781            if (ps == null) {
13782                throw new IllegalArgumentException("Unknown target package " + packageName);
13783            }
13784
13785            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13786                throw new IllegalArgumentException("Calling package " + callerPackageName
13787                        + " is not installer for " + packageName);
13788            }
13789
13790            if (ps.categoryHint != categoryHint) {
13791                ps.categoryHint = categoryHint;
13792                scheduleWriteSettingsLocked();
13793            }
13794        }
13795    }
13796
13797    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13798        // Queue up an async operation since the package installation may take a little while.
13799        mHandler.post(new Runnable() {
13800            public void run() {
13801                mHandler.removeCallbacks(this);
13802                 // Result object to be returned
13803                PackageInstalledInfo res = new PackageInstalledInfo();
13804                res.setReturnCode(currentStatus);
13805                res.uid = -1;
13806                res.pkg = null;
13807                res.removedInfo = null;
13808                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13809                    args.doPreInstall(res.returnCode);
13810                    synchronized (mInstallLock) {
13811                        installPackageTracedLI(args, res);
13812                    }
13813                    args.doPostInstall(res.returnCode, res.uid);
13814                }
13815
13816                // A restore should be performed at this point if (a) the install
13817                // succeeded, (b) the operation is not an update, and (c) the new
13818                // package has not opted out of backup participation.
13819                final boolean update = res.removedInfo != null
13820                        && res.removedInfo.removedPackage != null;
13821                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13822                boolean doRestore = !update
13823                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13824
13825                // Set up the post-install work request bookkeeping.  This will be used
13826                // and cleaned up by the post-install event handling regardless of whether
13827                // there's a restore pass performed.  Token values are >= 1.
13828                int token;
13829                if (mNextInstallToken < 0) mNextInstallToken = 1;
13830                token = mNextInstallToken++;
13831
13832                PostInstallData data = new PostInstallData(args, res);
13833                mRunningInstalls.put(token, data);
13834                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13835
13836                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13837                    // Pass responsibility to the Backup Manager.  It will perform a
13838                    // restore if appropriate, then pass responsibility back to the
13839                    // Package Manager to run the post-install observer callbacks
13840                    // and broadcasts.
13841                    IBackupManager bm = IBackupManager.Stub.asInterface(
13842                            ServiceManager.getService(Context.BACKUP_SERVICE));
13843                    if (bm != null) {
13844                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13845                                + " to BM for possible restore");
13846                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13847                        try {
13848                            // TODO: http://b/22388012
13849                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13850                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13851                            } else {
13852                                doRestore = false;
13853                            }
13854                        } catch (RemoteException e) {
13855                            // can't happen; the backup manager is local
13856                        } catch (Exception e) {
13857                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13858                            doRestore = false;
13859                        }
13860                    } else {
13861                        Slog.e(TAG, "Backup Manager not found!");
13862                        doRestore = false;
13863                    }
13864                }
13865
13866                if (!doRestore) {
13867                    // No restore possible, or the Backup Manager was mysteriously not
13868                    // available -- just fire the post-install work request directly.
13869                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13870
13871                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13872
13873                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13874                    mHandler.sendMessage(msg);
13875                }
13876            }
13877        });
13878    }
13879
13880    /**
13881     * Callback from PackageSettings whenever an app is first transitioned out of the
13882     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13883     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13884     * here whether the app is the target of an ongoing install, and only send the
13885     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13886     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13887     * handling.
13888     */
13889    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13890        // Serialize this with the rest of the install-process message chain.  In the
13891        // restore-at-install case, this Runnable will necessarily run before the
13892        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13893        // are coherent.  In the non-restore case, the app has already completed install
13894        // and been launched through some other means, so it is not in a problematic
13895        // state for observers to see the FIRST_LAUNCH signal.
13896        mHandler.post(new Runnable() {
13897            @Override
13898            public void run() {
13899                for (int i = 0; i < mRunningInstalls.size(); i++) {
13900                    final PostInstallData data = mRunningInstalls.valueAt(i);
13901                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13902                        continue;
13903                    }
13904                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13905                        // right package; but is it for the right user?
13906                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13907                            if (userId == data.res.newUsers[uIndex]) {
13908                                if (DEBUG_BACKUP) {
13909                                    Slog.i(TAG, "Package " + pkgName
13910                                            + " being restored so deferring FIRST_LAUNCH");
13911                                }
13912                                return;
13913                            }
13914                        }
13915                    }
13916                }
13917                // didn't find it, so not being restored
13918                if (DEBUG_BACKUP) {
13919                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13920                }
13921                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13922            }
13923        });
13924    }
13925
13926    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13927        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13928                installerPkg, null, userIds);
13929    }
13930
13931    private abstract class HandlerParams {
13932        private static final int MAX_RETRIES = 4;
13933
13934        /**
13935         * Number of times startCopy() has been attempted and had a non-fatal
13936         * error.
13937         */
13938        private int mRetries = 0;
13939
13940        /** User handle for the user requesting the information or installation. */
13941        private final UserHandle mUser;
13942        String traceMethod;
13943        int traceCookie;
13944
13945        HandlerParams(UserHandle user) {
13946            mUser = user;
13947        }
13948
13949        UserHandle getUser() {
13950            return mUser;
13951        }
13952
13953        HandlerParams setTraceMethod(String traceMethod) {
13954            this.traceMethod = traceMethod;
13955            return this;
13956        }
13957
13958        HandlerParams setTraceCookie(int traceCookie) {
13959            this.traceCookie = traceCookie;
13960            return this;
13961        }
13962
13963        final boolean startCopy() {
13964            boolean res;
13965            try {
13966                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13967
13968                if (++mRetries > MAX_RETRIES) {
13969                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13970                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13971                    handleServiceError();
13972                    return false;
13973                } else {
13974                    handleStartCopy();
13975                    res = true;
13976                }
13977            } catch (RemoteException e) {
13978                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13979                mHandler.sendEmptyMessage(MCS_RECONNECT);
13980                res = false;
13981            }
13982            handleReturnCode();
13983            return res;
13984        }
13985
13986        final void serviceError() {
13987            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13988            handleServiceError();
13989            handleReturnCode();
13990        }
13991
13992        abstract void handleStartCopy() throws RemoteException;
13993        abstract void handleServiceError();
13994        abstract void handleReturnCode();
13995    }
13996
13997    class MeasureParams extends HandlerParams {
13998        private final PackageStats mStats;
13999        private boolean mSuccess;
14000
14001        private final IPackageStatsObserver mObserver;
14002
14003        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14004            super(new UserHandle(stats.userHandle));
14005            mObserver = observer;
14006            mStats = stats;
14007        }
14008
14009        @Override
14010        public String toString() {
14011            return "MeasureParams{"
14012                + Integer.toHexString(System.identityHashCode(this))
14013                + " " + mStats.packageName + "}";
14014        }
14015
14016        @Override
14017        void handleStartCopy() throws RemoteException {
14018            synchronized (mInstallLock) {
14019                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14020            }
14021
14022            if (mSuccess) {
14023                boolean mounted = false;
14024                try {
14025                    final String status = Environment.getExternalStorageState();
14026                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14027                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14028                } catch (Exception e) {
14029                }
14030
14031                if (mounted) {
14032                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14033
14034                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14035                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14036
14037                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14038                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14039
14040                    // Always subtract cache size, since it's a subdirectory
14041                    mStats.externalDataSize -= mStats.externalCacheSize;
14042
14043                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14044                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14045
14046                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14047                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14048                }
14049            }
14050        }
14051
14052        @Override
14053        void handleReturnCode() {
14054            if (mObserver != null) {
14055                try {
14056                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14057                } catch (RemoteException e) {
14058                    Slog.i(TAG, "Observer no longer exists.");
14059                }
14060            }
14061        }
14062
14063        @Override
14064        void handleServiceError() {
14065            Slog.e(TAG, "Could not measure application " + mStats.packageName
14066                            + " external storage");
14067        }
14068    }
14069
14070    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14071            throws RemoteException {
14072        long result = 0;
14073        for (File path : paths) {
14074            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14075        }
14076        return result;
14077    }
14078
14079    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14080        for (File path : paths) {
14081            try {
14082                mcs.clearDirectory(path.getAbsolutePath());
14083            } catch (RemoteException e) {
14084            }
14085        }
14086    }
14087
14088    static class OriginInfo {
14089        /**
14090         * Location where install is coming from, before it has been
14091         * copied/renamed into place. This could be a single monolithic APK
14092         * file, or a cluster directory. This location may be untrusted.
14093         */
14094        final File file;
14095        final String cid;
14096
14097        /**
14098         * Flag indicating that {@link #file} or {@link #cid} has already been
14099         * staged, meaning downstream users don't need to defensively copy the
14100         * contents.
14101         */
14102        final boolean staged;
14103
14104        /**
14105         * Flag indicating that {@link #file} or {@link #cid} is an already
14106         * installed app that is being moved.
14107         */
14108        final boolean existing;
14109
14110        final String resolvedPath;
14111        final File resolvedFile;
14112
14113        static OriginInfo fromNothing() {
14114            return new OriginInfo(null, null, false, false);
14115        }
14116
14117        static OriginInfo fromUntrustedFile(File file) {
14118            return new OriginInfo(file, null, false, false);
14119        }
14120
14121        static OriginInfo fromExistingFile(File file) {
14122            return new OriginInfo(file, null, false, true);
14123        }
14124
14125        static OriginInfo fromStagedFile(File file) {
14126            return new OriginInfo(file, null, true, false);
14127        }
14128
14129        static OriginInfo fromStagedContainer(String cid) {
14130            return new OriginInfo(null, cid, true, false);
14131        }
14132
14133        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14134            this.file = file;
14135            this.cid = cid;
14136            this.staged = staged;
14137            this.existing = existing;
14138
14139            if (cid != null) {
14140                resolvedPath = PackageHelper.getSdDir(cid);
14141                resolvedFile = new File(resolvedPath);
14142            } else if (file != null) {
14143                resolvedPath = file.getAbsolutePath();
14144                resolvedFile = file;
14145            } else {
14146                resolvedPath = null;
14147                resolvedFile = null;
14148            }
14149        }
14150    }
14151
14152    static class MoveInfo {
14153        final int moveId;
14154        final String fromUuid;
14155        final String toUuid;
14156        final String packageName;
14157        final String dataAppName;
14158        final int appId;
14159        final String seinfo;
14160        final int targetSdkVersion;
14161
14162        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14163                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14164            this.moveId = moveId;
14165            this.fromUuid = fromUuid;
14166            this.toUuid = toUuid;
14167            this.packageName = packageName;
14168            this.dataAppName = dataAppName;
14169            this.appId = appId;
14170            this.seinfo = seinfo;
14171            this.targetSdkVersion = targetSdkVersion;
14172        }
14173    }
14174
14175    static class VerificationInfo {
14176        /** A constant used to indicate that a uid value is not present. */
14177        public static final int NO_UID = -1;
14178
14179        /** URI referencing where the package was downloaded from. */
14180        final Uri originatingUri;
14181
14182        /** HTTP referrer URI associated with the originatingURI. */
14183        final Uri referrer;
14184
14185        /** UID of the application that the install request originated from. */
14186        final int originatingUid;
14187
14188        /** UID of application requesting the install */
14189        final int installerUid;
14190
14191        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14192            this.originatingUri = originatingUri;
14193            this.referrer = referrer;
14194            this.originatingUid = originatingUid;
14195            this.installerUid = installerUid;
14196        }
14197    }
14198
14199    class InstallParams extends HandlerParams {
14200        final OriginInfo origin;
14201        final MoveInfo move;
14202        final IPackageInstallObserver2 observer;
14203        int installFlags;
14204        final String installerPackageName;
14205        final String volumeUuid;
14206        private InstallArgs mArgs;
14207        private int mRet;
14208        final String packageAbiOverride;
14209        final String[] grantedRuntimePermissions;
14210        final VerificationInfo verificationInfo;
14211        final Certificate[][] certificates;
14212        final int installReason;
14213
14214        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14215                int installFlags, String installerPackageName, String volumeUuid,
14216                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14217                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14218            super(user);
14219            this.origin = origin;
14220            this.move = move;
14221            this.observer = observer;
14222            this.installFlags = installFlags;
14223            this.installerPackageName = installerPackageName;
14224            this.volumeUuid = volumeUuid;
14225            this.verificationInfo = verificationInfo;
14226            this.packageAbiOverride = packageAbiOverride;
14227            this.grantedRuntimePermissions = grantedPermissions;
14228            this.certificates = certificates;
14229            this.installReason = installReason;
14230        }
14231
14232        @Override
14233        public String toString() {
14234            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14235                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14236        }
14237
14238        private int installLocationPolicy(PackageInfoLite pkgLite) {
14239            String packageName = pkgLite.packageName;
14240            int installLocation = pkgLite.installLocation;
14241            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14242            // reader
14243            synchronized (mPackages) {
14244                // Currently installed package which the new package is attempting to replace or
14245                // null if no such package is installed.
14246                PackageParser.Package installedPkg = mPackages.get(packageName);
14247                // Package which currently owns the data which the new package will own if installed.
14248                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14249                // will be null whereas dataOwnerPkg will contain information about the package
14250                // which was uninstalled while keeping its data.
14251                PackageParser.Package dataOwnerPkg = installedPkg;
14252                if (dataOwnerPkg  == null) {
14253                    PackageSetting ps = mSettings.mPackages.get(packageName);
14254                    if (ps != null) {
14255                        dataOwnerPkg = ps.pkg;
14256                    }
14257                }
14258
14259                if (dataOwnerPkg != null) {
14260                    // If installed, the package will get access to data left on the device by its
14261                    // predecessor. As a security measure, this is permited only if this is not a
14262                    // version downgrade or if the predecessor package is marked as debuggable and
14263                    // a downgrade is explicitly requested.
14264                    //
14265                    // On debuggable platform builds, downgrades are permitted even for
14266                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14267                    // not offer security guarantees and thus it's OK to disable some security
14268                    // mechanisms to make debugging/testing easier on those builds. However, even on
14269                    // debuggable builds downgrades of packages are permitted only if requested via
14270                    // installFlags. This is because we aim to keep the behavior of debuggable
14271                    // platform builds as close as possible to the behavior of non-debuggable
14272                    // platform builds.
14273                    final boolean downgradeRequested =
14274                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14275                    final boolean packageDebuggable =
14276                                (dataOwnerPkg.applicationInfo.flags
14277                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14278                    final boolean downgradePermitted =
14279                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14280                    if (!downgradePermitted) {
14281                        try {
14282                            checkDowngrade(dataOwnerPkg, pkgLite);
14283                        } catch (PackageManagerException e) {
14284                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14285                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14286                        }
14287                    }
14288                }
14289
14290                if (installedPkg != null) {
14291                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14292                        // Check for updated system application.
14293                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14294                            if (onSd) {
14295                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14296                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14297                            }
14298                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14299                        } else {
14300                            if (onSd) {
14301                                // Install flag overrides everything.
14302                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14303                            }
14304                            // If current upgrade specifies particular preference
14305                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14306                                // Application explicitly specified internal.
14307                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14308                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14309                                // App explictly prefers external. Let policy decide
14310                            } else {
14311                                // Prefer previous location
14312                                if (isExternal(installedPkg)) {
14313                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14314                                }
14315                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14316                            }
14317                        }
14318                    } else {
14319                        // Invalid install. Return error code
14320                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14321                    }
14322                }
14323            }
14324            // All the special cases have been taken care of.
14325            // Return result based on recommended install location.
14326            if (onSd) {
14327                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14328            }
14329            return pkgLite.recommendedInstallLocation;
14330        }
14331
14332        /*
14333         * Invoke remote method to get package information and install
14334         * location values. Override install location based on default
14335         * policy if needed and then create install arguments based
14336         * on the install location.
14337         */
14338        public void handleStartCopy() throws RemoteException {
14339            int ret = PackageManager.INSTALL_SUCCEEDED;
14340
14341            // If we're already staged, we've firmly committed to an install location
14342            if (origin.staged) {
14343                if (origin.file != null) {
14344                    installFlags |= PackageManager.INSTALL_INTERNAL;
14345                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14346                } else if (origin.cid != null) {
14347                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14348                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14349                } else {
14350                    throw new IllegalStateException("Invalid stage location");
14351                }
14352            }
14353
14354            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14355            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14356            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14357            PackageInfoLite pkgLite = null;
14358
14359            if (onInt && onSd) {
14360                // Check if both bits are set.
14361                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14362                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14363            } else if (onSd && ephemeral) {
14364                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14365                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14366            } else {
14367                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14368                        packageAbiOverride);
14369
14370                if (DEBUG_EPHEMERAL && ephemeral) {
14371                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14372                }
14373
14374                /*
14375                 * If we have too little free space, try to free cache
14376                 * before giving up.
14377                 */
14378                if (!origin.staged && pkgLite.recommendedInstallLocation
14379                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14380                    // TODO: focus freeing disk space on the target device
14381                    final StorageManager storage = StorageManager.from(mContext);
14382                    final long lowThreshold = storage.getStorageLowBytes(
14383                            Environment.getDataDirectory());
14384
14385                    final long sizeBytes = mContainerService.calculateInstalledSize(
14386                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14387
14388                    try {
14389                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14390                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14391                                installFlags, packageAbiOverride);
14392                    } catch (InstallerException e) {
14393                        Slog.w(TAG, "Failed to free cache", e);
14394                    }
14395
14396                    /*
14397                     * The cache free must have deleted the file we
14398                     * downloaded to install.
14399                     *
14400                     * TODO: fix the "freeCache" call to not delete
14401                     *       the file we care about.
14402                     */
14403                    if (pkgLite.recommendedInstallLocation
14404                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14405                        pkgLite.recommendedInstallLocation
14406                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14407                    }
14408                }
14409            }
14410
14411            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14412                int loc = pkgLite.recommendedInstallLocation;
14413                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14414                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14415                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14416                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14417                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14418                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14419                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14420                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14421                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14422                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14423                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14424                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14425                } else {
14426                    // Override with defaults if needed.
14427                    loc = installLocationPolicy(pkgLite);
14428                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14429                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14430                    } else if (!onSd && !onInt) {
14431                        // Override install location with flags
14432                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14433                            // Set the flag to install on external media.
14434                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14435                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14436                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14437                            if (DEBUG_EPHEMERAL) {
14438                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14439                            }
14440                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14441                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14442                                    |PackageManager.INSTALL_INTERNAL);
14443                        } else {
14444                            // Make sure the flag for installing on external
14445                            // media is unset
14446                            installFlags |= PackageManager.INSTALL_INTERNAL;
14447                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14448                        }
14449                    }
14450                }
14451            }
14452
14453            final InstallArgs args = createInstallArgs(this);
14454            mArgs = args;
14455
14456            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14457                // TODO: http://b/22976637
14458                // Apps installed for "all" users use the device owner to verify the app
14459                UserHandle verifierUser = getUser();
14460                if (verifierUser == UserHandle.ALL) {
14461                    verifierUser = UserHandle.SYSTEM;
14462                }
14463
14464                /*
14465                 * Determine if we have any installed package verifiers. If we
14466                 * do, then we'll defer to them to verify the packages.
14467                 */
14468                final int requiredUid = mRequiredVerifierPackage == null ? -1
14469                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14470                                verifierUser.getIdentifier());
14471                if (!origin.existing && requiredUid != -1
14472                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14473                    final Intent verification = new Intent(
14474                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14475                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14476                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14477                            PACKAGE_MIME_TYPE);
14478                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14479
14480                    // Query all live verifiers based on current user state
14481                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14482                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14483
14484                    if (DEBUG_VERIFY) {
14485                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14486                                + verification.toString() + " with " + pkgLite.verifiers.length
14487                                + " optional verifiers");
14488                    }
14489
14490                    final int verificationId = mPendingVerificationToken++;
14491
14492                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14493
14494                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14495                            installerPackageName);
14496
14497                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14498                            installFlags);
14499
14500                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14501                            pkgLite.packageName);
14502
14503                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14504                            pkgLite.versionCode);
14505
14506                    if (verificationInfo != null) {
14507                        if (verificationInfo.originatingUri != null) {
14508                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14509                                    verificationInfo.originatingUri);
14510                        }
14511                        if (verificationInfo.referrer != null) {
14512                            verification.putExtra(Intent.EXTRA_REFERRER,
14513                                    verificationInfo.referrer);
14514                        }
14515                        if (verificationInfo.originatingUid >= 0) {
14516                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14517                                    verificationInfo.originatingUid);
14518                        }
14519                        if (verificationInfo.installerUid >= 0) {
14520                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14521                                    verificationInfo.installerUid);
14522                        }
14523                    }
14524
14525                    final PackageVerificationState verificationState = new PackageVerificationState(
14526                            requiredUid, args);
14527
14528                    mPendingVerification.append(verificationId, verificationState);
14529
14530                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14531                            receivers, verificationState);
14532
14533                    /*
14534                     * If any sufficient verifiers were listed in the package
14535                     * manifest, attempt to ask them.
14536                     */
14537                    if (sufficientVerifiers != null) {
14538                        final int N = sufficientVerifiers.size();
14539                        if (N == 0) {
14540                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14541                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14542                        } else {
14543                            for (int i = 0; i < N; i++) {
14544                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14545
14546                                final Intent sufficientIntent = new Intent(verification);
14547                                sufficientIntent.setComponent(verifierComponent);
14548                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14549                            }
14550                        }
14551                    }
14552
14553                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14554                            mRequiredVerifierPackage, receivers);
14555                    if (ret == PackageManager.INSTALL_SUCCEEDED
14556                            && mRequiredVerifierPackage != null) {
14557                        Trace.asyncTraceBegin(
14558                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14559                        /*
14560                         * Send the intent to the required verification agent,
14561                         * but only start the verification timeout after the
14562                         * target BroadcastReceivers have run.
14563                         */
14564                        verification.setComponent(requiredVerifierComponent);
14565                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14566                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14567                                new BroadcastReceiver() {
14568                                    @Override
14569                                    public void onReceive(Context context, Intent intent) {
14570                                        final Message msg = mHandler
14571                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14572                                        msg.arg1 = verificationId;
14573                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14574                                    }
14575                                }, null, 0, null, null);
14576
14577                        /*
14578                         * We don't want the copy to proceed until verification
14579                         * succeeds, so null out this field.
14580                         */
14581                        mArgs = null;
14582                    }
14583                } else {
14584                    /*
14585                     * No package verification is enabled, so immediately start
14586                     * the remote call to initiate copy using temporary file.
14587                     */
14588                    ret = args.copyApk(mContainerService, true);
14589                }
14590            }
14591
14592            mRet = ret;
14593        }
14594
14595        @Override
14596        void handleReturnCode() {
14597            // If mArgs is null, then MCS couldn't be reached. When it
14598            // reconnects, it will try again to install. At that point, this
14599            // will succeed.
14600            if (mArgs != null) {
14601                processPendingInstall(mArgs, mRet);
14602            }
14603        }
14604
14605        @Override
14606        void handleServiceError() {
14607            mArgs = createInstallArgs(this);
14608            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14609        }
14610
14611        public boolean isForwardLocked() {
14612            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14613        }
14614    }
14615
14616    /**
14617     * Used during creation of InstallArgs
14618     *
14619     * @param installFlags package installation flags
14620     * @return true if should be installed on external storage
14621     */
14622    private static boolean installOnExternalAsec(int installFlags) {
14623        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14624            return false;
14625        }
14626        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14627            return true;
14628        }
14629        return false;
14630    }
14631
14632    /**
14633     * Used during creation of InstallArgs
14634     *
14635     * @param installFlags package installation flags
14636     * @return true if should be installed as forward locked
14637     */
14638    private static boolean installForwardLocked(int installFlags) {
14639        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14640    }
14641
14642    private InstallArgs createInstallArgs(InstallParams params) {
14643        if (params.move != null) {
14644            return new MoveInstallArgs(params);
14645        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14646            return new AsecInstallArgs(params);
14647        } else {
14648            return new FileInstallArgs(params);
14649        }
14650    }
14651
14652    /**
14653     * Create args that describe an existing installed package. Typically used
14654     * when cleaning up old installs, or used as a move source.
14655     */
14656    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14657            String resourcePath, String[] instructionSets) {
14658        final boolean isInAsec;
14659        if (installOnExternalAsec(installFlags)) {
14660            /* Apps on SD card are always in ASEC containers. */
14661            isInAsec = true;
14662        } else if (installForwardLocked(installFlags)
14663                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14664            /*
14665             * Forward-locked apps are only in ASEC containers if they're the
14666             * new style
14667             */
14668            isInAsec = true;
14669        } else {
14670            isInAsec = false;
14671        }
14672
14673        if (isInAsec) {
14674            return new AsecInstallArgs(codePath, instructionSets,
14675                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14676        } else {
14677            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14678        }
14679    }
14680
14681    static abstract class InstallArgs {
14682        /** @see InstallParams#origin */
14683        final OriginInfo origin;
14684        /** @see InstallParams#move */
14685        final MoveInfo move;
14686
14687        final IPackageInstallObserver2 observer;
14688        // Always refers to PackageManager flags only
14689        final int installFlags;
14690        final String installerPackageName;
14691        final String volumeUuid;
14692        final UserHandle user;
14693        final String abiOverride;
14694        final String[] installGrantPermissions;
14695        /** If non-null, drop an async trace when the install completes */
14696        final String traceMethod;
14697        final int traceCookie;
14698        final Certificate[][] certificates;
14699        final int installReason;
14700
14701        // The list of instruction sets supported by this app. This is currently
14702        // only used during the rmdex() phase to clean up resources. We can get rid of this
14703        // if we move dex files under the common app path.
14704        /* nullable */ String[] instructionSets;
14705
14706        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14707                int installFlags, String installerPackageName, String volumeUuid,
14708                UserHandle user, String[] instructionSets,
14709                String abiOverride, String[] installGrantPermissions,
14710                String traceMethod, int traceCookie, Certificate[][] certificates,
14711                int installReason) {
14712            this.origin = origin;
14713            this.move = move;
14714            this.installFlags = installFlags;
14715            this.observer = observer;
14716            this.installerPackageName = installerPackageName;
14717            this.volumeUuid = volumeUuid;
14718            this.user = user;
14719            this.instructionSets = instructionSets;
14720            this.abiOverride = abiOverride;
14721            this.installGrantPermissions = installGrantPermissions;
14722            this.traceMethod = traceMethod;
14723            this.traceCookie = traceCookie;
14724            this.certificates = certificates;
14725            this.installReason = installReason;
14726        }
14727
14728        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14729        abstract int doPreInstall(int status);
14730
14731        /**
14732         * Rename package into final resting place. All paths on the given
14733         * scanned package should be updated to reflect the rename.
14734         */
14735        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14736        abstract int doPostInstall(int status, int uid);
14737
14738        /** @see PackageSettingBase#codePathString */
14739        abstract String getCodePath();
14740        /** @see PackageSettingBase#resourcePathString */
14741        abstract String getResourcePath();
14742
14743        // Need installer lock especially for dex file removal.
14744        abstract void cleanUpResourcesLI();
14745        abstract boolean doPostDeleteLI(boolean delete);
14746
14747        /**
14748         * Called before the source arguments are copied. This is used mostly
14749         * for MoveParams when it needs to read the source file to put it in the
14750         * destination.
14751         */
14752        int doPreCopy() {
14753            return PackageManager.INSTALL_SUCCEEDED;
14754        }
14755
14756        /**
14757         * Called after the source arguments are copied. This is used mostly for
14758         * MoveParams when it needs to read the source file to put it in the
14759         * destination.
14760         */
14761        int doPostCopy(int uid) {
14762            return PackageManager.INSTALL_SUCCEEDED;
14763        }
14764
14765        protected boolean isFwdLocked() {
14766            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14767        }
14768
14769        protected boolean isExternalAsec() {
14770            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14771        }
14772
14773        protected boolean isEphemeral() {
14774            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14775        }
14776
14777        UserHandle getUser() {
14778            return user;
14779        }
14780    }
14781
14782    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14783        if (!allCodePaths.isEmpty()) {
14784            if (instructionSets == null) {
14785                throw new IllegalStateException("instructionSet == null");
14786            }
14787            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14788            for (String codePath : allCodePaths) {
14789                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14790                    try {
14791                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14792                    } catch (InstallerException ignored) {
14793                    }
14794                }
14795            }
14796        }
14797    }
14798
14799    /**
14800     * Logic to handle installation of non-ASEC applications, including copying
14801     * and renaming logic.
14802     */
14803    class FileInstallArgs extends InstallArgs {
14804        private File codeFile;
14805        private File resourceFile;
14806
14807        // Example topology:
14808        // /data/app/com.example/base.apk
14809        // /data/app/com.example/split_foo.apk
14810        // /data/app/com.example/lib/arm/libfoo.so
14811        // /data/app/com.example/lib/arm64/libfoo.so
14812        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14813
14814        /** New install */
14815        FileInstallArgs(InstallParams params) {
14816            super(params.origin, params.move, params.observer, params.installFlags,
14817                    params.installerPackageName, params.volumeUuid,
14818                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14819                    params.grantedRuntimePermissions,
14820                    params.traceMethod, params.traceCookie, params.certificates,
14821                    params.installReason);
14822            if (isFwdLocked()) {
14823                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14824            }
14825        }
14826
14827        /** Existing install */
14828        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14829            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14830                    null, null, null, 0, null /*certificates*/,
14831                    PackageManager.INSTALL_REASON_UNKNOWN);
14832            this.codeFile = (codePath != null) ? new File(codePath) : null;
14833            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14834        }
14835
14836        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14838            try {
14839                return doCopyApk(imcs, temp);
14840            } finally {
14841                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14842            }
14843        }
14844
14845        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14846            if (origin.staged) {
14847                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14848                codeFile = origin.file;
14849                resourceFile = origin.file;
14850                return PackageManager.INSTALL_SUCCEEDED;
14851            }
14852
14853            try {
14854                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14855                final File tempDir =
14856                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14857                codeFile = tempDir;
14858                resourceFile = tempDir;
14859            } catch (IOException e) {
14860                Slog.w(TAG, "Failed to create copy file: " + e);
14861                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14862            }
14863
14864            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14865                @Override
14866                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14867                    if (!FileUtils.isValidExtFilename(name)) {
14868                        throw new IllegalArgumentException("Invalid filename: " + name);
14869                    }
14870                    try {
14871                        final File file = new File(codeFile, name);
14872                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14873                                O_RDWR | O_CREAT, 0644);
14874                        Os.chmod(file.getAbsolutePath(), 0644);
14875                        return new ParcelFileDescriptor(fd);
14876                    } catch (ErrnoException e) {
14877                        throw new RemoteException("Failed to open: " + e.getMessage());
14878                    }
14879                }
14880            };
14881
14882            int ret = PackageManager.INSTALL_SUCCEEDED;
14883            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14884            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14885                Slog.e(TAG, "Failed to copy package");
14886                return ret;
14887            }
14888
14889            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14890            NativeLibraryHelper.Handle handle = null;
14891            try {
14892                handle = NativeLibraryHelper.Handle.create(codeFile);
14893                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14894                        abiOverride);
14895            } catch (IOException e) {
14896                Slog.e(TAG, "Copying native libraries failed", e);
14897                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14898            } finally {
14899                IoUtils.closeQuietly(handle);
14900            }
14901
14902            return ret;
14903        }
14904
14905        int doPreInstall(int status) {
14906            if (status != PackageManager.INSTALL_SUCCEEDED) {
14907                cleanUp();
14908            }
14909            return status;
14910        }
14911
14912        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14913            if (status != PackageManager.INSTALL_SUCCEEDED) {
14914                cleanUp();
14915                return false;
14916            }
14917
14918            final File targetDir = codeFile.getParentFile();
14919            final File beforeCodeFile = codeFile;
14920            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14921
14922            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14923            try {
14924                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14925            } catch (ErrnoException e) {
14926                Slog.w(TAG, "Failed to rename", e);
14927                return false;
14928            }
14929
14930            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14931                Slog.w(TAG, "Failed to restorecon");
14932                return false;
14933            }
14934
14935            // Reflect the rename internally
14936            codeFile = afterCodeFile;
14937            resourceFile = afterCodeFile;
14938
14939            // Reflect the rename in scanned details
14940            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14941            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14942                    afterCodeFile, pkg.baseCodePath));
14943            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14944                    afterCodeFile, pkg.splitCodePaths));
14945
14946            // Reflect the rename in app info
14947            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14948            pkg.setApplicationInfoCodePath(pkg.codePath);
14949            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14950            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14951            pkg.setApplicationInfoResourcePath(pkg.codePath);
14952            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14953            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14954
14955            return true;
14956        }
14957
14958        int doPostInstall(int status, int uid) {
14959            if (status != PackageManager.INSTALL_SUCCEEDED) {
14960                cleanUp();
14961            }
14962            return status;
14963        }
14964
14965        @Override
14966        String getCodePath() {
14967            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14968        }
14969
14970        @Override
14971        String getResourcePath() {
14972            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14973        }
14974
14975        private boolean cleanUp() {
14976            if (codeFile == null || !codeFile.exists()) {
14977                return false;
14978            }
14979
14980            removeCodePathLI(codeFile);
14981
14982            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14983                resourceFile.delete();
14984            }
14985
14986            return true;
14987        }
14988
14989        void cleanUpResourcesLI() {
14990            // Try enumerating all code paths before deleting
14991            List<String> allCodePaths = Collections.EMPTY_LIST;
14992            if (codeFile != null && codeFile.exists()) {
14993                try {
14994                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14995                    allCodePaths = pkg.getAllCodePaths();
14996                } catch (PackageParserException e) {
14997                    // Ignored; we tried our best
14998                }
14999            }
15000
15001            cleanUp();
15002            removeDexFiles(allCodePaths, instructionSets);
15003        }
15004
15005        boolean doPostDeleteLI(boolean delete) {
15006            // XXX err, shouldn't we respect the delete flag?
15007            cleanUpResourcesLI();
15008            return true;
15009        }
15010    }
15011
15012    private boolean isAsecExternal(String cid) {
15013        final String asecPath = PackageHelper.getSdFilesystem(cid);
15014        return !asecPath.startsWith(mAsecInternalPath);
15015    }
15016
15017    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15018            PackageManagerException {
15019        if (copyRet < 0) {
15020            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15021                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15022                throw new PackageManagerException(copyRet, message);
15023            }
15024        }
15025    }
15026
15027    /**
15028     * Extract the StorageManagerService "container ID" from the full code path of an
15029     * .apk.
15030     */
15031    static String cidFromCodePath(String fullCodePath) {
15032        int eidx = fullCodePath.lastIndexOf("/");
15033        String subStr1 = fullCodePath.substring(0, eidx);
15034        int sidx = subStr1.lastIndexOf("/");
15035        return subStr1.substring(sidx+1, eidx);
15036    }
15037
15038    /**
15039     * Logic to handle installation of ASEC applications, including copying and
15040     * renaming logic.
15041     */
15042    class AsecInstallArgs extends InstallArgs {
15043        static final String RES_FILE_NAME = "pkg.apk";
15044        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15045
15046        String cid;
15047        String packagePath;
15048        String resourcePath;
15049
15050        /** New install */
15051        AsecInstallArgs(InstallParams params) {
15052            super(params.origin, params.move, params.observer, params.installFlags,
15053                    params.installerPackageName, params.volumeUuid,
15054                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15055                    params.grantedRuntimePermissions,
15056                    params.traceMethod, params.traceCookie, params.certificates,
15057                    params.installReason);
15058        }
15059
15060        /** Existing install */
15061        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15062                        boolean isExternal, boolean isForwardLocked) {
15063            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15064                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15065                    instructionSets, null, null, null, 0, null /*certificates*/,
15066                    PackageManager.INSTALL_REASON_UNKNOWN);
15067            // Hackily pretend we're still looking at a full code path
15068            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15069                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15070            }
15071
15072            // Extract cid from fullCodePath
15073            int eidx = fullCodePath.lastIndexOf("/");
15074            String subStr1 = fullCodePath.substring(0, eidx);
15075            int sidx = subStr1.lastIndexOf("/");
15076            cid = subStr1.substring(sidx+1, eidx);
15077            setMountPath(subStr1);
15078        }
15079
15080        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15081            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15082                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15083                    instructionSets, null, null, null, 0, null /*certificates*/,
15084                    PackageManager.INSTALL_REASON_UNKNOWN);
15085            this.cid = cid;
15086            setMountPath(PackageHelper.getSdDir(cid));
15087        }
15088
15089        void createCopyFile() {
15090            cid = mInstallerService.allocateExternalStageCidLegacy();
15091        }
15092
15093        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15094            if (origin.staged && origin.cid != null) {
15095                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15096                cid = origin.cid;
15097                setMountPath(PackageHelper.getSdDir(cid));
15098                return PackageManager.INSTALL_SUCCEEDED;
15099            }
15100
15101            if (temp) {
15102                createCopyFile();
15103            } else {
15104                /*
15105                 * Pre-emptively destroy the container since it's destroyed if
15106                 * copying fails due to it existing anyway.
15107                 */
15108                PackageHelper.destroySdDir(cid);
15109            }
15110
15111            final String newMountPath = imcs.copyPackageToContainer(
15112                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15113                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15114
15115            if (newMountPath != null) {
15116                setMountPath(newMountPath);
15117                return PackageManager.INSTALL_SUCCEEDED;
15118            } else {
15119                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15120            }
15121        }
15122
15123        @Override
15124        String getCodePath() {
15125            return packagePath;
15126        }
15127
15128        @Override
15129        String getResourcePath() {
15130            return resourcePath;
15131        }
15132
15133        int doPreInstall(int status) {
15134            if (status != PackageManager.INSTALL_SUCCEEDED) {
15135                // Destroy container
15136                PackageHelper.destroySdDir(cid);
15137            } else {
15138                boolean mounted = PackageHelper.isContainerMounted(cid);
15139                if (!mounted) {
15140                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15141                            Process.SYSTEM_UID);
15142                    if (newMountPath != null) {
15143                        setMountPath(newMountPath);
15144                    } else {
15145                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15146                    }
15147                }
15148            }
15149            return status;
15150        }
15151
15152        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15153            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15154            String newMountPath = null;
15155            if (PackageHelper.isContainerMounted(cid)) {
15156                // Unmount the container
15157                if (!PackageHelper.unMountSdDir(cid)) {
15158                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15159                    return false;
15160                }
15161            }
15162            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15163                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15164                        " which might be stale. Will try to clean up.");
15165                // Clean up the stale container and proceed to recreate.
15166                if (!PackageHelper.destroySdDir(newCacheId)) {
15167                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15168                    return false;
15169                }
15170                // Successfully cleaned up stale container. Try to rename again.
15171                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15172                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15173                            + " inspite of cleaning it up.");
15174                    return false;
15175                }
15176            }
15177            if (!PackageHelper.isContainerMounted(newCacheId)) {
15178                Slog.w(TAG, "Mounting container " + newCacheId);
15179                newMountPath = PackageHelper.mountSdDir(newCacheId,
15180                        getEncryptKey(), Process.SYSTEM_UID);
15181            } else {
15182                newMountPath = PackageHelper.getSdDir(newCacheId);
15183            }
15184            if (newMountPath == null) {
15185                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15186                return false;
15187            }
15188            Log.i(TAG, "Succesfully renamed " + cid +
15189                    " to " + newCacheId +
15190                    " at new path: " + newMountPath);
15191            cid = newCacheId;
15192
15193            final File beforeCodeFile = new File(packagePath);
15194            setMountPath(newMountPath);
15195            final File afterCodeFile = new File(packagePath);
15196
15197            // Reflect the rename in scanned details
15198            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15199            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15200                    afterCodeFile, pkg.baseCodePath));
15201            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15202                    afterCodeFile, pkg.splitCodePaths));
15203
15204            // Reflect the rename in app info
15205            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15206            pkg.setApplicationInfoCodePath(pkg.codePath);
15207            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15208            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15209            pkg.setApplicationInfoResourcePath(pkg.codePath);
15210            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15211            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15212
15213            return true;
15214        }
15215
15216        private void setMountPath(String mountPath) {
15217            final File mountFile = new File(mountPath);
15218
15219            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15220            if (monolithicFile.exists()) {
15221                packagePath = monolithicFile.getAbsolutePath();
15222                if (isFwdLocked()) {
15223                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15224                } else {
15225                    resourcePath = packagePath;
15226                }
15227            } else {
15228                packagePath = mountFile.getAbsolutePath();
15229                resourcePath = packagePath;
15230            }
15231        }
15232
15233        int doPostInstall(int status, int uid) {
15234            if (status != PackageManager.INSTALL_SUCCEEDED) {
15235                cleanUp();
15236            } else {
15237                final int groupOwner;
15238                final String protectedFile;
15239                if (isFwdLocked()) {
15240                    groupOwner = UserHandle.getSharedAppGid(uid);
15241                    protectedFile = RES_FILE_NAME;
15242                } else {
15243                    groupOwner = -1;
15244                    protectedFile = null;
15245                }
15246
15247                if (uid < Process.FIRST_APPLICATION_UID
15248                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15249                    Slog.e(TAG, "Failed to finalize " + cid);
15250                    PackageHelper.destroySdDir(cid);
15251                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15252                }
15253
15254                boolean mounted = PackageHelper.isContainerMounted(cid);
15255                if (!mounted) {
15256                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15257                }
15258            }
15259            return status;
15260        }
15261
15262        private void cleanUp() {
15263            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15264
15265            // Destroy secure container
15266            PackageHelper.destroySdDir(cid);
15267        }
15268
15269        private List<String> getAllCodePaths() {
15270            final File codeFile = new File(getCodePath());
15271            if (codeFile != null && codeFile.exists()) {
15272                try {
15273                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15274                    return pkg.getAllCodePaths();
15275                } catch (PackageParserException e) {
15276                    // Ignored; we tried our best
15277                }
15278            }
15279            return Collections.EMPTY_LIST;
15280        }
15281
15282        void cleanUpResourcesLI() {
15283            // Enumerate all code paths before deleting
15284            cleanUpResourcesLI(getAllCodePaths());
15285        }
15286
15287        private void cleanUpResourcesLI(List<String> allCodePaths) {
15288            cleanUp();
15289            removeDexFiles(allCodePaths, instructionSets);
15290        }
15291
15292        String getPackageName() {
15293            return getAsecPackageName(cid);
15294        }
15295
15296        boolean doPostDeleteLI(boolean delete) {
15297            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15298            final List<String> allCodePaths = getAllCodePaths();
15299            boolean mounted = PackageHelper.isContainerMounted(cid);
15300            if (mounted) {
15301                // Unmount first
15302                if (PackageHelper.unMountSdDir(cid)) {
15303                    mounted = false;
15304                }
15305            }
15306            if (!mounted && delete) {
15307                cleanUpResourcesLI(allCodePaths);
15308            }
15309            return !mounted;
15310        }
15311
15312        @Override
15313        int doPreCopy() {
15314            if (isFwdLocked()) {
15315                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15316                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15317                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15318                }
15319            }
15320
15321            return PackageManager.INSTALL_SUCCEEDED;
15322        }
15323
15324        @Override
15325        int doPostCopy(int uid) {
15326            if (isFwdLocked()) {
15327                if (uid < Process.FIRST_APPLICATION_UID
15328                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15329                                RES_FILE_NAME)) {
15330                    Slog.e(TAG, "Failed to finalize " + cid);
15331                    PackageHelper.destroySdDir(cid);
15332                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15333                }
15334            }
15335
15336            return PackageManager.INSTALL_SUCCEEDED;
15337        }
15338    }
15339
15340    /**
15341     * Logic to handle movement of existing installed applications.
15342     */
15343    class MoveInstallArgs extends InstallArgs {
15344        private File codeFile;
15345        private File resourceFile;
15346
15347        /** New install */
15348        MoveInstallArgs(InstallParams params) {
15349            super(params.origin, params.move, params.observer, params.installFlags,
15350                    params.installerPackageName, params.volumeUuid,
15351                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15352                    params.grantedRuntimePermissions,
15353                    params.traceMethod, params.traceCookie, params.certificates,
15354                    params.installReason);
15355        }
15356
15357        int copyApk(IMediaContainerService imcs, boolean temp) {
15358            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15359                    + move.fromUuid + " to " + move.toUuid);
15360            synchronized (mInstaller) {
15361                try {
15362                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15363                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15364                } catch (InstallerException e) {
15365                    Slog.w(TAG, "Failed to move app", e);
15366                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15367                }
15368            }
15369
15370            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15371            resourceFile = codeFile;
15372            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15373
15374            return PackageManager.INSTALL_SUCCEEDED;
15375        }
15376
15377        int doPreInstall(int status) {
15378            if (status != PackageManager.INSTALL_SUCCEEDED) {
15379                cleanUp(move.toUuid);
15380            }
15381            return status;
15382        }
15383
15384        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15385            if (status != PackageManager.INSTALL_SUCCEEDED) {
15386                cleanUp(move.toUuid);
15387                return false;
15388            }
15389
15390            // Reflect the move in app info
15391            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15392            pkg.setApplicationInfoCodePath(pkg.codePath);
15393            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15394            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15395            pkg.setApplicationInfoResourcePath(pkg.codePath);
15396            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15397            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15398
15399            return true;
15400        }
15401
15402        int doPostInstall(int status, int uid) {
15403            if (status == PackageManager.INSTALL_SUCCEEDED) {
15404                cleanUp(move.fromUuid);
15405            } else {
15406                cleanUp(move.toUuid);
15407            }
15408            return status;
15409        }
15410
15411        @Override
15412        String getCodePath() {
15413            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15414        }
15415
15416        @Override
15417        String getResourcePath() {
15418            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15419        }
15420
15421        private boolean cleanUp(String volumeUuid) {
15422            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15423                    move.dataAppName);
15424            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15425            final int[] userIds = sUserManager.getUserIds();
15426            synchronized (mInstallLock) {
15427                // Clean up both app data and code
15428                // All package moves are frozen until finished
15429                for (int userId : userIds) {
15430                    try {
15431                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15432                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15433                    } catch (InstallerException e) {
15434                        Slog.w(TAG, String.valueOf(e));
15435                    }
15436                }
15437                removeCodePathLI(codeFile);
15438            }
15439            return true;
15440        }
15441
15442        void cleanUpResourcesLI() {
15443            throw new UnsupportedOperationException();
15444        }
15445
15446        boolean doPostDeleteLI(boolean delete) {
15447            throw new UnsupportedOperationException();
15448        }
15449    }
15450
15451    static String getAsecPackageName(String packageCid) {
15452        int idx = packageCid.lastIndexOf("-");
15453        if (idx == -1) {
15454            return packageCid;
15455        }
15456        return packageCid.substring(0, idx);
15457    }
15458
15459    // Utility method used to create code paths based on package name and available index.
15460    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15461        String idxStr = "";
15462        int idx = 1;
15463        // Fall back to default value of idx=1 if prefix is not
15464        // part of oldCodePath
15465        if (oldCodePath != null) {
15466            String subStr = oldCodePath;
15467            // Drop the suffix right away
15468            if (suffix != null && subStr.endsWith(suffix)) {
15469                subStr = subStr.substring(0, subStr.length() - suffix.length());
15470            }
15471            // If oldCodePath already contains prefix find out the
15472            // ending index to either increment or decrement.
15473            int sidx = subStr.lastIndexOf(prefix);
15474            if (sidx != -1) {
15475                subStr = subStr.substring(sidx + prefix.length());
15476                if (subStr != null) {
15477                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15478                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15479                    }
15480                    try {
15481                        idx = Integer.parseInt(subStr);
15482                        if (idx <= 1) {
15483                            idx++;
15484                        } else {
15485                            idx--;
15486                        }
15487                    } catch(NumberFormatException e) {
15488                    }
15489                }
15490            }
15491        }
15492        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15493        return prefix + idxStr;
15494    }
15495
15496    private File getNextCodePath(File targetDir, String packageName) {
15497        File result;
15498        SecureRandom random = new SecureRandom();
15499        byte[] bytes = new byte[16];
15500        do {
15501            random.nextBytes(bytes);
15502            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15503            result = new File(targetDir, packageName + "-" + suffix);
15504        } while (result.exists());
15505        return result;
15506    }
15507
15508    // Utility method that returns the relative package path with respect
15509    // to the installation directory. Like say for /data/data/com.test-1.apk
15510    // string com.test-1 is returned.
15511    static String deriveCodePathName(String codePath) {
15512        if (codePath == null) {
15513            return null;
15514        }
15515        final File codeFile = new File(codePath);
15516        final String name = codeFile.getName();
15517        if (codeFile.isDirectory()) {
15518            return name;
15519        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15520            final int lastDot = name.lastIndexOf('.');
15521            return name.substring(0, lastDot);
15522        } else {
15523            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15524            return null;
15525        }
15526    }
15527
15528    static class PackageInstalledInfo {
15529        String name;
15530        int uid;
15531        // The set of users that originally had this package installed.
15532        int[] origUsers;
15533        // The set of users that now have this package installed.
15534        int[] newUsers;
15535        PackageParser.Package pkg;
15536        int returnCode;
15537        String returnMsg;
15538        PackageRemovedInfo removedInfo;
15539        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15540
15541        public void setError(int code, String msg) {
15542            setReturnCode(code);
15543            setReturnMessage(msg);
15544            Slog.w(TAG, msg);
15545        }
15546
15547        public void setError(String msg, PackageParserException e) {
15548            setReturnCode(e.error);
15549            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15550            Slog.w(TAG, msg, e);
15551        }
15552
15553        public void setError(String msg, PackageManagerException e) {
15554            returnCode = e.error;
15555            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15556            Slog.w(TAG, msg, e);
15557        }
15558
15559        public void setReturnCode(int returnCode) {
15560            this.returnCode = returnCode;
15561            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15562            for (int i = 0; i < childCount; i++) {
15563                addedChildPackages.valueAt(i).returnCode = returnCode;
15564            }
15565        }
15566
15567        private void setReturnMessage(String returnMsg) {
15568            this.returnMsg = returnMsg;
15569            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15570            for (int i = 0; i < childCount; i++) {
15571                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15572            }
15573        }
15574
15575        // In some error cases we want to convey more info back to the observer
15576        String origPackage;
15577        String origPermission;
15578    }
15579
15580    /*
15581     * Install a non-existing package.
15582     */
15583    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15584            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15585            PackageInstalledInfo res, int installReason) {
15586        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15587
15588        // Remember this for later, in case we need to rollback this install
15589        String pkgName = pkg.packageName;
15590
15591        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15592
15593        synchronized(mPackages) {
15594            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15595            if (renamedPackage != null) {
15596                // A package with the same name is already installed, though
15597                // it has been renamed to an older name.  The package we
15598                // are trying to install should be installed as an update to
15599                // the existing one, but that has not been requested, so bail.
15600                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15601                        + " without first uninstalling package running as "
15602                        + renamedPackage);
15603                return;
15604            }
15605            if (mPackages.containsKey(pkgName)) {
15606                // Don't allow installation over an existing package with the same name.
15607                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15608                        + " without first uninstalling.");
15609                return;
15610            }
15611        }
15612
15613        try {
15614            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15615                    System.currentTimeMillis(), user);
15616
15617            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15618
15619            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15620                prepareAppDataAfterInstallLIF(newPackage);
15621
15622            } else {
15623                // Remove package from internal structures, but keep around any
15624                // data that might have already existed
15625                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15626                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15627            }
15628        } catch (PackageManagerException e) {
15629            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15630        }
15631
15632        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15633    }
15634
15635    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15636        // Can't rotate keys during boot or if sharedUser.
15637        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15638                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15639            return false;
15640        }
15641        // app is using upgradeKeySets; make sure all are valid
15642        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15643        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15644        for (int i = 0; i < upgradeKeySets.length; i++) {
15645            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15646                Slog.wtf(TAG, "Package "
15647                         + (oldPs.name != null ? oldPs.name : "<null>")
15648                         + " contains upgrade-key-set reference to unknown key-set: "
15649                         + upgradeKeySets[i]
15650                         + " reverting to signatures check.");
15651                return false;
15652            }
15653        }
15654        return true;
15655    }
15656
15657    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15658        // Upgrade keysets are being used.  Determine if new package has a superset of the
15659        // required keys.
15660        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15661        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15662        for (int i = 0; i < upgradeKeySets.length; i++) {
15663            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15664            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15665                return true;
15666            }
15667        }
15668        return false;
15669    }
15670
15671    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15672        try (DigestInputStream digestStream =
15673                new DigestInputStream(new FileInputStream(file), digest)) {
15674            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15675        }
15676    }
15677
15678    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15679            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15680            int installReason) {
15681        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15682
15683        final PackageParser.Package oldPackage;
15684        final String pkgName = pkg.packageName;
15685        final int[] allUsers;
15686        final int[] installedUsers;
15687
15688        synchronized(mPackages) {
15689            oldPackage = mPackages.get(pkgName);
15690            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15691
15692            // don't allow upgrade to target a release SDK from a pre-release SDK
15693            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15694                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15695            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15696                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15697            if (oldTargetsPreRelease
15698                    && !newTargetsPreRelease
15699                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15700                Slog.w(TAG, "Can't install package targeting released sdk");
15701                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15702                return;
15703            }
15704
15705            // don't allow an upgrade from full to ephemeral
15706            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
15707            if (isEphemeral && !oldIsEphemeral) {
15708                // can't downgrade from full to ephemeral
15709                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15710                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15711                return;
15712            }
15713
15714            // verify signatures are valid
15715            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15716            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15717                if (!checkUpgradeKeySetLP(ps, pkg)) {
15718                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15719                            "New package not signed by keys specified by upgrade-keysets: "
15720                                    + pkgName);
15721                    return;
15722                }
15723            } else {
15724                // default to original signature matching
15725                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15726                        != PackageManager.SIGNATURE_MATCH) {
15727                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15728                            "New package has a different signature: " + pkgName);
15729                    return;
15730                }
15731            }
15732
15733            // don't allow a system upgrade unless the upgrade hash matches
15734            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15735                byte[] digestBytes = null;
15736                try {
15737                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15738                    updateDigest(digest, new File(pkg.baseCodePath));
15739                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15740                        for (String path : pkg.splitCodePaths) {
15741                            updateDigest(digest, new File(path));
15742                        }
15743                    }
15744                    digestBytes = digest.digest();
15745                } catch (NoSuchAlgorithmException | IOException e) {
15746                    res.setError(INSTALL_FAILED_INVALID_APK,
15747                            "Could not compute hash: " + pkgName);
15748                    return;
15749                }
15750                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15751                    res.setError(INSTALL_FAILED_INVALID_APK,
15752                            "New package fails restrict-update check: " + pkgName);
15753                    return;
15754                }
15755                // retain upgrade restriction
15756                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15757            }
15758
15759            // Check for shared user id changes
15760            String invalidPackageName =
15761                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15762            if (invalidPackageName != null) {
15763                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15764                        "Package " + invalidPackageName + " tried to change user "
15765                                + oldPackage.mSharedUserId);
15766                return;
15767            }
15768
15769            // In case of rollback, remember per-user/profile install state
15770            allUsers = sUserManager.getUserIds();
15771            installedUsers = ps.queryInstalledUsers(allUsers, true);
15772        }
15773
15774        // Update what is removed
15775        res.removedInfo = new PackageRemovedInfo();
15776        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15777        res.removedInfo.removedPackage = oldPackage.packageName;
15778        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15779        res.removedInfo.isUpdate = true;
15780        res.removedInfo.origUsers = installedUsers;
15781        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15782        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15783        for (int i = 0; i < installedUsers.length; i++) {
15784            final int userId = installedUsers[i];
15785            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15786        }
15787
15788        final int childCount = (oldPackage.childPackages != null)
15789                ? oldPackage.childPackages.size() : 0;
15790        for (int i = 0; i < childCount; i++) {
15791            boolean childPackageUpdated = false;
15792            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15793            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15794            if (res.addedChildPackages != null) {
15795                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15796                if (childRes != null) {
15797                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15798                    childRes.removedInfo.removedPackage = childPkg.packageName;
15799                    childRes.removedInfo.isUpdate = true;
15800                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15801                    childPackageUpdated = true;
15802                }
15803            }
15804            if (!childPackageUpdated) {
15805                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15806                childRemovedRes.removedPackage = childPkg.packageName;
15807                childRemovedRes.isUpdate = false;
15808                childRemovedRes.dataRemoved = true;
15809                synchronized (mPackages) {
15810                    if (childPs != null) {
15811                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15812                    }
15813                }
15814                if (res.removedInfo.removedChildPackages == null) {
15815                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15816                }
15817                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15818            }
15819        }
15820
15821        boolean sysPkg = (isSystemApp(oldPackage));
15822        if (sysPkg) {
15823            // Set the system/privileged flags as needed
15824            final boolean privileged =
15825                    (oldPackage.applicationInfo.privateFlags
15826                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15827            final int systemPolicyFlags = policyFlags
15828                    | PackageParser.PARSE_IS_SYSTEM
15829                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15830
15831            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15832                    user, allUsers, installerPackageName, res, installReason);
15833        } else {
15834            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15835                    user, allUsers, installerPackageName, res, installReason);
15836        }
15837    }
15838
15839    public List<String> getPreviousCodePaths(String packageName) {
15840        final PackageSetting ps = mSettings.mPackages.get(packageName);
15841        final List<String> result = new ArrayList<String>();
15842        if (ps != null && ps.oldCodePaths != null) {
15843            result.addAll(ps.oldCodePaths);
15844        }
15845        return result;
15846    }
15847
15848    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15849            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15850            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15851            int installReason) {
15852        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15853                + deletedPackage);
15854
15855        String pkgName = deletedPackage.packageName;
15856        boolean deletedPkg = true;
15857        boolean addedPkg = false;
15858        boolean updatedSettings = false;
15859        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15860        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15861                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15862
15863        final long origUpdateTime = (pkg.mExtras != null)
15864                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15865
15866        // First delete the existing package while retaining the data directory
15867        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15868                res.removedInfo, true, pkg)) {
15869            // If the existing package wasn't successfully deleted
15870            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15871            deletedPkg = false;
15872        } else {
15873            // Successfully deleted the old package; proceed with replace.
15874
15875            // If deleted package lived in a container, give users a chance to
15876            // relinquish resources before killing.
15877            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15878                if (DEBUG_INSTALL) {
15879                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15880                }
15881                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15882                final ArrayList<String> pkgList = new ArrayList<String>(1);
15883                pkgList.add(deletedPackage.applicationInfo.packageName);
15884                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15885            }
15886
15887            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15888                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15889            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15890
15891            try {
15892                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15893                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15894                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15895                        installReason);
15896
15897                // Update the in-memory copy of the previous code paths.
15898                PackageSetting ps = mSettings.mPackages.get(pkgName);
15899                if (!killApp) {
15900                    if (ps.oldCodePaths == null) {
15901                        ps.oldCodePaths = new ArraySet<>();
15902                    }
15903                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15904                    if (deletedPackage.splitCodePaths != null) {
15905                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15906                    }
15907                } else {
15908                    ps.oldCodePaths = null;
15909                }
15910                if (ps.childPackageNames != null) {
15911                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15912                        final String childPkgName = ps.childPackageNames.get(i);
15913                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15914                        childPs.oldCodePaths = ps.oldCodePaths;
15915                    }
15916                }
15917                prepareAppDataAfterInstallLIF(newPackage);
15918                addedPkg = true;
15919            } catch (PackageManagerException e) {
15920                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15921            }
15922        }
15923
15924        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15925            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15926
15927            // Revert all internal state mutations and added folders for the failed install
15928            if (addedPkg) {
15929                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15930                        res.removedInfo, true, null);
15931            }
15932
15933            // Restore the old package
15934            if (deletedPkg) {
15935                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15936                File restoreFile = new File(deletedPackage.codePath);
15937                // Parse old package
15938                boolean oldExternal = isExternal(deletedPackage);
15939                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15940                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15941                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15942                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15943                try {
15944                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15945                            null);
15946                } catch (PackageManagerException e) {
15947                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15948                            + e.getMessage());
15949                    return;
15950                }
15951
15952                synchronized (mPackages) {
15953                    // Ensure the installer package name up to date
15954                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15955
15956                    // Update permissions for restored package
15957                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15958
15959                    mSettings.writeLPr();
15960                }
15961
15962                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15963            }
15964        } else {
15965            synchronized (mPackages) {
15966                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15967                if (ps != null) {
15968                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15969                    if (res.removedInfo.removedChildPackages != null) {
15970                        final int childCount = res.removedInfo.removedChildPackages.size();
15971                        // Iterate in reverse as we may modify the collection
15972                        for (int i = childCount - 1; i >= 0; i--) {
15973                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15974                            if (res.addedChildPackages.containsKey(childPackageName)) {
15975                                res.removedInfo.removedChildPackages.removeAt(i);
15976                            } else {
15977                                PackageRemovedInfo childInfo = res.removedInfo
15978                                        .removedChildPackages.valueAt(i);
15979                                childInfo.removedForAllUsers = mPackages.get(
15980                                        childInfo.removedPackage) == null;
15981                            }
15982                        }
15983                    }
15984                }
15985            }
15986        }
15987    }
15988
15989    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15990            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15991            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15992            int installReason) {
15993        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15994                + ", old=" + deletedPackage);
15995
15996        final boolean disabledSystem;
15997
15998        // Remove existing system package
15999        removePackageLI(deletedPackage, true);
16000
16001        synchronized (mPackages) {
16002            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16003        }
16004        if (!disabledSystem) {
16005            // We didn't need to disable the .apk as a current system package,
16006            // which means we are replacing another update that is already
16007            // installed.  We need to make sure to delete the older one's .apk.
16008            res.removedInfo.args = createInstallArgsForExisting(0,
16009                    deletedPackage.applicationInfo.getCodePath(),
16010                    deletedPackage.applicationInfo.getResourcePath(),
16011                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16012        } else {
16013            res.removedInfo.args = null;
16014        }
16015
16016        // Successfully disabled the old package. Now proceed with re-installation
16017        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16018                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16019        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16020
16021        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16022        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16023                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16024
16025        PackageParser.Package newPackage = null;
16026        try {
16027            // Add the package to the internal data structures
16028            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16029
16030            // Set the update and install times
16031            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16032            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16033                    System.currentTimeMillis());
16034
16035            // Update the package dynamic state if succeeded
16036            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16037                // Now that the install succeeded make sure we remove data
16038                // directories for any child package the update removed.
16039                final int deletedChildCount = (deletedPackage.childPackages != null)
16040                        ? deletedPackage.childPackages.size() : 0;
16041                final int newChildCount = (newPackage.childPackages != null)
16042                        ? newPackage.childPackages.size() : 0;
16043                for (int i = 0; i < deletedChildCount; i++) {
16044                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16045                    boolean childPackageDeleted = true;
16046                    for (int j = 0; j < newChildCount; j++) {
16047                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16048                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16049                            childPackageDeleted = false;
16050                            break;
16051                        }
16052                    }
16053                    if (childPackageDeleted) {
16054                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16055                                deletedChildPkg.packageName);
16056                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16057                            PackageRemovedInfo removedChildRes = res.removedInfo
16058                                    .removedChildPackages.get(deletedChildPkg.packageName);
16059                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16060                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16061                        }
16062                    }
16063                }
16064
16065                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16066                        installReason);
16067                prepareAppDataAfterInstallLIF(newPackage);
16068            }
16069        } catch (PackageManagerException e) {
16070            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16071            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16072        }
16073
16074        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16075            // Re installation failed. Restore old information
16076            // Remove new pkg information
16077            if (newPackage != null) {
16078                removeInstalledPackageLI(newPackage, true);
16079            }
16080            // Add back the old system package
16081            try {
16082                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16083            } catch (PackageManagerException e) {
16084                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16085            }
16086
16087            synchronized (mPackages) {
16088                if (disabledSystem) {
16089                    enableSystemPackageLPw(deletedPackage);
16090                }
16091
16092                // Ensure the installer package name up to date
16093                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16094
16095                // Update permissions for restored package
16096                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16097
16098                mSettings.writeLPr();
16099            }
16100
16101            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16102                    + " after failed upgrade");
16103        }
16104    }
16105
16106    /**
16107     * Checks whether the parent or any of the child packages have a change shared
16108     * user. For a package to be a valid update the shred users of the parent and
16109     * the children should match. We may later support changing child shared users.
16110     * @param oldPkg The updated package.
16111     * @param newPkg The update package.
16112     * @return The shared user that change between the versions.
16113     */
16114    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16115            PackageParser.Package newPkg) {
16116        // Check parent shared user
16117        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16118            return newPkg.packageName;
16119        }
16120        // Check child shared users
16121        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16122        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16123        for (int i = 0; i < newChildCount; i++) {
16124            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16125            // If this child was present, did it have the same shared user?
16126            for (int j = 0; j < oldChildCount; j++) {
16127                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16128                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16129                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16130                    return newChildPkg.packageName;
16131                }
16132            }
16133        }
16134        return null;
16135    }
16136
16137    private void removeNativeBinariesLI(PackageSetting ps) {
16138        // Remove the lib path for the parent package
16139        if (ps != null) {
16140            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16141            // Remove the lib path for the child packages
16142            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16143            for (int i = 0; i < childCount; i++) {
16144                PackageSetting childPs = null;
16145                synchronized (mPackages) {
16146                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16147                }
16148                if (childPs != null) {
16149                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16150                            .legacyNativeLibraryPathString);
16151                }
16152            }
16153        }
16154    }
16155
16156    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16157        // Enable the parent package
16158        mSettings.enableSystemPackageLPw(pkg.packageName);
16159        // Enable the child packages
16160        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16161        for (int i = 0; i < childCount; i++) {
16162            PackageParser.Package childPkg = pkg.childPackages.get(i);
16163            mSettings.enableSystemPackageLPw(childPkg.packageName);
16164        }
16165    }
16166
16167    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16168            PackageParser.Package newPkg) {
16169        // Disable the parent package (parent always replaced)
16170        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16171        // Disable the child packages
16172        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16173        for (int i = 0; i < childCount; i++) {
16174            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16175            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16176            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16177        }
16178        return disabled;
16179    }
16180
16181    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16182            String installerPackageName) {
16183        // Enable the parent package
16184        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16185        // Enable the child packages
16186        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16187        for (int i = 0; i < childCount; i++) {
16188            PackageParser.Package childPkg = pkg.childPackages.get(i);
16189            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16190        }
16191    }
16192
16193    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16194        // Collect all used permissions in the UID
16195        ArraySet<String> usedPermissions = new ArraySet<>();
16196        final int packageCount = su.packages.size();
16197        for (int i = 0; i < packageCount; i++) {
16198            PackageSetting ps = su.packages.valueAt(i);
16199            if (ps.pkg == null) {
16200                continue;
16201            }
16202            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16203            for (int j = 0; j < requestedPermCount; j++) {
16204                String permission = ps.pkg.requestedPermissions.get(j);
16205                BasePermission bp = mSettings.mPermissions.get(permission);
16206                if (bp != null) {
16207                    usedPermissions.add(permission);
16208                }
16209            }
16210        }
16211
16212        PermissionsState permissionsState = su.getPermissionsState();
16213        // Prune install permissions
16214        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16215        final int installPermCount = installPermStates.size();
16216        for (int i = installPermCount - 1; i >= 0;  i--) {
16217            PermissionState permissionState = installPermStates.get(i);
16218            if (!usedPermissions.contains(permissionState.getName())) {
16219                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16220                if (bp != null) {
16221                    permissionsState.revokeInstallPermission(bp);
16222                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16223                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16224                }
16225            }
16226        }
16227
16228        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16229
16230        // Prune runtime permissions
16231        for (int userId : allUserIds) {
16232            List<PermissionState> runtimePermStates = permissionsState
16233                    .getRuntimePermissionStates(userId);
16234            final int runtimePermCount = runtimePermStates.size();
16235            for (int i = runtimePermCount - 1; i >= 0; i--) {
16236                PermissionState permissionState = runtimePermStates.get(i);
16237                if (!usedPermissions.contains(permissionState.getName())) {
16238                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16239                    if (bp != null) {
16240                        permissionsState.revokeRuntimePermission(bp, userId);
16241                        permissionsState.updatePermissionFlags(bp, userId,
16242                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16243                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16244                                runtimePermissionChangedUserIds, userId);
16245                    }
16246                }
16247            }
16248        }
16249
16250        return runtimePermissionChangedUserIds;
16251    }
16252
16253    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16254            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16255        // Update the parent package setting
16256        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16257                res, user, installReason);
16258        // Update the child packages setting
16259        final int childCount = (newPackage.childPackages != null)
16260                ? newPackage.childPackages.size() : 0;
16261        for (int i = 0; i < childCount; i++) {
16262            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16263            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16264            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16265                    childRes.origUsers, childRes, user, installReason);
16266        }
16267    }
16268
16269    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16270            String installerPackageName, int[] allUsers, int[] installedForUsers,
16271            PackageInstalledInfo res, UserHandle user, int installReason) {
16272        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16273
16274        String pkgName = newPackage.packageName;
16275        synchronized (mPackages) {
16276            //write settings. the installStatus will be incomplete at this stage.
16277            //note that the new package setting would have already been
16278            //added to mPackages. It hasn't been persisted yet.
16279            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16280            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16281            mSettings.writeLPr();
16282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16283        }
16284
16285        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16286        synchronized (mPackages) {
16287            updatePermissionsLPw(newPackage.packageName, newPackage,
16288                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16289                            ? UPDATE_PERMISSIONS_ALL : 0));
16290            // For system-bundled packages, we assume that installing an upgraded version
16291            // of the package implies that the user actually wants to run that new code,
16292            // so we enable the package.
16293            PackageSetting ps = mSettings.mPackages.get(pkgName);
16294            final int userId = user.getIdentifier();
16295            if (ps != null) {
16296                if (isSystemApp(newPackage)) {
16297                    if (DEBUG_INSTALL) {
16298                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16299                    }
16300                    // Enable system package for requested users
16301                    if (res.origUsers != null) {
16302                        for (int origUserId : res.origUsers) {
16303                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16304                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16305                                        origUserId, installerPackageName);
16306                            }
16307                        }
16308                    }
16309                    // Also convey the prior install/uninstall state
16310                    if (allUsers != null && installedForUsers != null) {
16311                        for (int currentUserId : allUsers) {
16312                            final boolean installed = ArrayUtils.contains(
16313                                    installedForUsers, currentUserId);
16314                            if (DEBUG_INSTALL) {
16315                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16316                            }
16317                            ps.setInstalled(installed, currentUserId);
16318                        }
16319                        // these install state changes will be persisted in the
16320                        // upcoming call to mSettings.writeLPr().
16321                    }
16322                }
16323                // It's implied that when a user requests installation, they want the app to be
16324                // installed and enabled.
16325                if (userId != UserHandle.USER_ALL) {
16326                    ps.setInstalled(true, userId);
16327                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16328                }
16329
16330                // When replacing an existing package, preserve the original install reason for all
16331                // users that had the package installed before.
16332                final Set<Integer> previousUserIds = new ArraySet<>();
16333                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16334                    final int installReasonCount = res.removedInfo.installReasons.size();
16335                    for (int i = 0; i < installReasonCount; i++) {
16336                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16337                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16338                        ps.setInstallReason(previousInstallReason, previousUserId);
16339                        previousUserIds.add(previousUserId);
16340                    }
16341                }
16342
16343                // Set install reason for users that are having the package newly installed.
16344                if (userId == UserHandle.USER_ALL) {
16345                    for (int currentUserId : sUserManager.getUserIds()) {
16346                        if (!previousUserIds.contains(currentUserId)) {
16347                            ps.setInstallReason(installReason, currentUserId);
16348                        }
16349                    }
16350                } else if (!previousUserIds.contains(userId)) {
16351                    ps.setInstallReason(installReason, userId);
16352                }
16353            }
16354            res.name = pkgName;
16355            res.uid = newPackage.applicationInfo.uid;
16356            res.pkg = newPackage;
16357            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16358            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16359            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16360            //to update install status
16361            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16362            mSettings.writeLPr();
16363            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16364        }
16365
16366        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16367    }
16368
16369    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16370        try {
16371            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16372            installPackageLI(args, res);
16373        } finally {
16374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16375        }
16376    }
16377
16378    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16379        final int installFlags = args.installFlags;
16380        final String installerPackageName = args.installerPackageName;
16381        final String volumeUuid = args.volumeUuid;
16382        final File tmpPackageFile = new File(args.getCodePath());
16383        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16384        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16385                || (args.volumeUuid != null));
16386        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16387        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16388        boolean replace = false;
16389        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16390        if (args.move != null) {
16391            // moving a complete application; perform an initial scan on the new install location
16392            scanFlags |= SCAN_INITIAL;
16393        }
16394        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16395            scanFlags |= SCAN_DONT_KILL_APP;
16396        }
16397
16398        // Result object to be returned
16399        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16400
16401        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16402
16403        // Sanity check
16404        if (ephemeral && (forwardLocked || onExternal)) {
16405            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16406                    + " external=" + onExternal);
16407            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16408            return;
16409        }
16410
16411        // Retrieve PackageSettings and parse package
16412        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16413                | PackageParser.PARSE_ENFORCE_CODE
16414                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16415                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16416                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16417                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16418        PackageParser pp = new PackageParser();
16419        pp.setSeparateProcesses(mSeparateProcesses);
16420        pp.setDisplayMetrics(mMetrics);
16421
16422        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16423        final PackageParser.Package pkg;
16424        try {
16425            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16426        } catch (PackageParserException e) {
16427            res.setError("Failed parse during installPackageLI", e);
16428            return;
16429        } finally {
16430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16431        }
16432
16433        // Ephemeral apps must have target SDK >= O.
16434        // TODO: Update conditional and error message when O gets locked down
16435        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16436            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16437                    "Ephemeral apps must have target SDK version of at least O");
16438            return;
16439        }
16440
16441        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16442            // Static shared libraries have synthetic package names
16443            renameStaticSharedLibraryPackage(pkg);
16444
16445            // No static shared libs on external storage
16446            if (onExternal) {
16447                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16448                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16449                        "Packages declaring static-shared libs cannot be updated");
16450                return;
16451            }
16452        }
16453
16454        // If we are installing a clustered package add results for the children
16455        if (pkg.childPackages != null) {
16456            synchronized (mPackages) {
16457                final int childCount = pkg.childPackages.size();
16458                for (int i = 0; i < childCount; i++) {
16459                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16460                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16461                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16462                    childRes.pkg = childPkg;
16463                    childRes.name = childPkg.packageName;
16464                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16465                    if (childPs != null) {
16466                        childRes.origUsers = childPs.queryInstalledUsers(
16467                                sUserManager.getUserIds(), true);
16468                    }
16469                    if ((mPackages.containsKey(childPkg.packageName))) {
16470                        childRes.removedInfo = new PackageRemovedInfo();
16471                        childRes.removedInfo.removedPackage = childPkg.packageName;
16472                    }
16473                    if (res.addedChildPackages == null) {
16474                        res.addedChildPackages = new ArrayMap<>();
16475                    }
16476                    res.addedChildPackages.put(childPkg.packageName, childRes);
16477                }
16478            }
16479        }
16480
16481        // If package doesn't declare API override, mark that we have an install
16482        // time CPU ABI override.
16483        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16484            pkg.cpuAbiOverride = args.abiOverride;
16485        }
16486
16487        String pkgName = res.name = pkg.packageName;
16488        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16489            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16490                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16491                return;
16492            }
16493        }
16494
16495        try {
16496            // either use what we've been given or parse directly from the APK
16497            if (args.certificates != null) {
16498                try {
16499                    PackageParser.populateCertificates(pkg, args.certificates);
16500                } catch (PackageParserException e) {
16501                    // there was something wrong with the certificates we were given;
16502                    // try to pull them from the APK
16503                    PackageParser.collectCertificates(pkg, parseFlags);
16504                }
16505            } else {
16506                PackageParser.collectCertificates(pkg, parseFlags);
16507            }
16508        } catch (PackageParserException e) {
16509            res.setError("Failed collect during installPackageLI", e);
16510            return;
16511        }
16512
16513        // Get rid of all references to package scan path via parser.
16514        pp = null;
16515        String oldCodePath = null;
16516        boolean systemApp = false;
16517        synchronized (mPackages) {
16518            // Check if installing already existing package
16519            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16520                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16521                if (pkg.mOriginalPackages != null
16522                        && pkg.mOriginalPackages.contains(oldName)
16523                        && mPackages.containsKey(oldName)) {
16524                    // This package is derived from an original package,
16525                    // and this device has been updating from that original
16526                    // name.  We must continue using the original name, so
16527                    // rename the new package here.
16528                    pkg.setPackageName(oldName);
16529                    pkgName = pkg.packageName;
16530                    replace = true;
16531                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16532                            + oldName + " pkgName=" + pkgName);
16533                } else if (mPackages.containsKey(pkgName)) {
16534                    // This package, under its official name, already exists
16535                    // on the device; we should replace it.
16536                    replace = true;
16537                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16538                }
16539
16540                // Child packages are installed through the parent package
16541                if (pkg.parentPackage != null) {
16542                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16543                            "Package " + pkg.packageName + " is child of package "
16544                                    + pkg.parentPackage.parentPackage + ". Child packages "
16545                                    + "can be updated only through the parent package.");
16546                    return;
16547                }
16548
16549                if (replace) {
16550                    // Prevent apps opting out from runtime permissions
16551                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16552                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16553                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16554                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16555                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16556                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16557                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16558                                        + " doesn't support runtime permissions but the old"
16559                                        + " target SDK " + oldTargetSdk + " does.");
16560                        return;
16561                    }
16562
16563                    // Prevent installing of child packages
16564                    if (oldPackage.parentPackage != null) {
16565                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16566                                "Package " + pkg.packageName + " is child of package "
16567                                        + oldPackage.parentPackage + ". Child packages "
16568                                        + "can be updated only through the parent package.");
16569                        return;
16570                    }
16571                }
16572            }
16573
16574            PackageSetting ps = mSettings.mPackages.get(pkgName);
16575            if (ps != null) {
16576                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16577
16578                // Static shared libs have same package with different versions where
16579                // we internally use a synthetic package name to allow multiple versions
16580                // of the same package, therefore we need to compare signatures against
16581                // the package setting for the latest library version.
16582                PackageSetting signatureCheckPs = ps;
16583                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16584                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16585                    if (libraryEntry != null) {
16586                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16587                    }
16588                }
16589
16590                // Quick sanity check that we're signed correctly if updating;
16591                // we'll check this again later when scanning, but we want to
16592                // bail early here before tripping over redefined permissions.
16593                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16594                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16595                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16596                                + pkg.packageName + " upgrade keys do not match the "
16597                                + "previously installed version");
16598                        return;
16599                    }
16600                } else {
16601                    try {
16602                        verifySignaturesLP(signatureCheckPs, pkg);
16603                    } catch (PackageManagerException e) {
16604                        res.setError(e.error, e.getMessage());
16605                        return;
16606                    }
16607                }
16608
16609                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16610                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16611                    systemApp = (ps.pkg.applicationInfo.flags &
16612                            ApplicationInfo.FLAG_SYSTEM) != 0;
16613                }
16614                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16615            }
16616
16617            // Check whether the newly-scanned package wants to define an already-defined perm
16618            int N = pkg.permissions.size();
16619            for (int i = N-1; i >= 0; i--) {
16620                PackageParser.Permission perm = pkg.permissions.get(i);
16621                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16622                if (bp != null) {
16623                    // If the defining package is signed with our cert, it's okay.  This
16624                    // also includes the "updating the same package" case, of course.
16625                    // "updating same package" could also involve key-rotation.
16626                    final boolean sigsOk;
16627                    if (bp.sourcePackage.equals(pkg.packageName)
16628                            && (bp.packageSetting instanceof PackageSetting)
16629                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16630                                    scanFlags))) {
16631                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16632                    } else {
16633                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16634                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16635                    }
16636                    if (!sigsOk) {
16637                        // If the owning package is the system itself, we log but allow
16638                        // install to proceed; we fail the install on all other permission
16639                        // redefinitions.
16640                        if (!bp.sourcePackage.equals("android")) {
16641                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16642                                    + pkg.packageName + " attempting to redeclare permission "
16643                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16644                            res.origPermission = perm.info.name;
16645                            res.origPackage = bp.sourcePackage;
16646                            return;
16647                        } else {
16648                            Slog.w(TAG, "Package " + pkg.packageName
16649                                    + " attempting to redeclare system permission "
16650                                    + perm.info.name + "; ignoring new declaration");
16651                            pkg.permissions.remove(i);
16652                        }
16653                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16654                        // Prevent apps to change protection level to dangerous from any other
16655                        // type as this would allow a privilege escalation where an app adds a
16656                        // normal/signature permission in other app's group and later redefines
16657                        // it as dangerous leading to the group auto-grant.
16658                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16659                                == PermissionInfo.PROTECTION_DANGEROUS) {
16660                            if (bp != null && !bp.isRuntime()) {
16661                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16662                                        + "non-runtime permission " + perm.info.name
16663                                        + " to runtime; keeping old protection level");
16664                                perm.info.protectionLevel = bp.protectionLevel;
16665                            }
16666                        }
16667                    }
16668                }
16669            }
16670        }
16671
16672        if (systemApp) {
16673            if (onExternal) {
16674                // Abort update; system app can't be replaced with app on sdcard
16675                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16676                        "Cannot install updates to system apps on sdcard");
16677                return;
16678            } else if (ephemeral) {
16679                // Abort update; system app can't be replaced with an ephemeral app
16680                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16681                        "Cannot update a system app with an ephemeral app");
16682                return;
16683            }
16684        }
16685
16686        if (args.move != null) {
16687            // We did an in-place move, so dex is ready to roll
16688            scanFlags |= SCAN_NO_DEX;
16689            scanFlags |= SCAN_MOVE;
16690
16691            synchronized (mPackages) {
16692                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16693                if (ps == null) {
16694                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16695                            "Missing settings for moved package " + pkgName);
16696                }
16697
16698                // We moved the entire application as-is, so bring over the
16699                // previously derived ABI information.
16700                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16701                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16702            }
16703
16704        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16705            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16706            scanFlags |= SCAN_NO_DEX;
16707
16708            try {
16709                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16710                    args.abiOverride : pkg.cpuAbiOverride);
16711                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16712                        true /*extractLibs*/, mAppLib32InstallDir);
16713            } catch (PackageManagerException pme) {
16714                Slog.e(TAG, "Error deriving application ABI", pme);
16715                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16716                return;
16717            }
16718
16719            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16720            // Do not run PackageDexOptimizer through the local performDexOpt
16721            // method because `pkg` may not be in `mPackages` yet.
16722            //
16723            // Also, don't fail application installs if the dexopt step fails.
16724            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16725                    null /* instructionSets */, false /* checkProfiles */,
16726                    getCompilerFilterForReason(REASON_INSTALL),
16727                    getOrCreateCompilerPackageStats(pkg));
16728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16729
16730            // Notify BackgroundDexOptService that the package has been changed.
16731            // If this is an update of a package which used to fail to compile,
16732            // BDOS will remove it from its blacklist.
16733            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16734        }
16735
16736        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16737            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16738            return;
16739        }
16740
16741        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16742
16743        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16744                "installPackageLI")) {
16745            if (replace) {
16746                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16747                    // Static libs have a synthetic package name containing the version
16748                    // and cannot be updated as an update would get a new package name,
16749                    // unless this is the exact same version code which is useful for
16750                    // development.
16751                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16752                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16753                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16754                                + "static-shared libs cannot be updated");
16755                        return;
16756                    }
16757                }
16758                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16759                        installerPackageName, res, args.installReason);
16760            } else {
16761                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16762                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16763            }
16764        }
16765        synchronized (mPackages) {
16766            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16767            if (ps != null) {
16768                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16769            }
16770
16771            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16772            for (int i = 0; i < childCount; i++) {
16773                PackageParser.Package childPkg = pkg.childPackages.get(i);
16774                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16775                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16776                if (childPs != null) {
16777                    childRes.newUsers = childPs.queryInstalledUsers(
16778                            sUserManager.getUserIds(), true);
16779                }
16780            }
16781        }
16782    }
16783
16784    private void startIntentFilterVerifications(int userId, boolean replacing,
16785            PackageParser.Package pkg) {
16786        if (mIntentFilterVerifierComponent == null) {
16787            Slog.w(TAG, "No IntentFilter verification will not be done as "
16788                    + "there is no IntentFilterVerifier available!");
16789            return;
16790        }
16791
16792        final int verifierUid = getPackageUid(
16793                mIntentFilterVerifierComponent.getPackageName(),
16794                MATCH_DEBUG_TRIAGED_MISSING,
16795                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16796
16797        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16798        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16799        mHandler.sendMessage(msg);
16800
16801        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16802        for (int i = 0; i < childCount; i++) {
16803            PackageParser.Package childPkg = pkg.childPackages.get(i);
16804            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16805            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16806            mHandler.sendMessage(msg);
16807        }
16808    }
16809
16810    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16811            PackageParser.Package pkg) {
16812        int size = pkg.activities.size();
16813        if (size == 0) {
16814            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16815                    "No activity, so no need to verify any IntentFilter!");
16816            return;
16817        }
16818
16819        final boolean hasDomainURLs = hasDomainURLs(pkg);
16820        if (!hasDomainURLs) {
16821            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16822                    "No domain URLs, so no need to verify any IntentFilter!");
16823            return;
16824        }
16825
16826        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16827                + " if any IntentFilter from the " + size
16828                + " Activities needs verification ...");
16829
16830        int count = 0;
16831        final String packageName = pkg.packageName;
16832
16833        synchronized (mPackages) {
16834            // If this is a new install and we see that we've already run verification for this
16835            // package, we have nothing to do: it means the state was restored from backup.
16836            if (!replacing) {
16837                IntentFilterVerificationInfo ivi =
16838                        mSettings.getIntentFilterVerificationLPr(packageName);
16839                if (ivi != null) {
16840                    if (DEBUG_DOMAIN_VERIFICATION) {
16841                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16842                                + ivi.getStatusString());
16843                    }
16844                    return;
16845                }
16846            }
16847
16848            // If any filters need to be verified, then all need to be.
16849            boolean needToVerify = false;
16850            for (PackageParser.Activity a : pkg.activities) {
16851                for (ActivityIntentInfo filter : a.intents) {
16852                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16853                        if (DEBUG_DOMAIN_VERIFICATION) {
16854                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16855                        }
16856                        needToVerify = true;
16857                        break;
16858                    }
16859                }
16860            }
16861
16862            if (needToVerify) {
16863                final int verificationId = mIntentFilterVerificationToken++;
16864                for (PackageParser.Activity a : pkg.activities) {
16865                    for (ActivityIntentInfo filter : a.intents) {
16866                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16867                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16868                                    "Verification needed for IntentFilter:" + filter.toString());
16869                            mIntentFilterVerifier.addOneIntentFilterVerification(
16870                                    verifierUid, userId, verificationId, filter, packageName);
16871                            count++;
16872                        }
16873                    }
16874                }
16875            }
16876        }
16877
16878        if (count > 0) {
16879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16880                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16881                    +  " for userId:" + userId);
16882            mIntentFilterVerifier.startVerifications(userId);
16883        } else {
16884            if (DEBUG_DOMAIN_VERIFICATION) {
16885                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16886            }
16887        }
16888    }
16889
16890    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16891        final ComponentName cn  = filter.activity.getComponentName();
16892        final String packageName = cn.getPackageName();
16893
16894        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16895                packageName);
16896        if (ivi == null) {
16897            return true;
16898        }
16899        int status = ivi.getStatus();
16900        switch (status) {
16901            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16902            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16903                return true;
16904
16905            default:
16906                // Nothing to do
16907                return false;
16908        }
16909    }
16910
16911    private static boolean isMultiArch(ApplicationInfo info) {
16912        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16913    }
16914
16915    private static boolean isExternal(PackageParser.Package pkg) {
16916        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16917    }
16918
16919    private static boolean isExternal(PackageSetting ps) {
16920        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16921    }
16922
16923    private static boolean isEphemeral(PackageParser.Package pkg) {
16924        return pkg.applicationInfo.isEphemeralApp();
16925    }
16926
16927    private static boolean isEphemeral(PackageSetting ps) {
16928        return ps.pkg != null && isEphemeral(ps.pkg);
16929    }
16930
16931    private static boolean isSystemApp(PackageParser.Package pkg) {
16932        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16933    }
16934
16935    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16936        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16937    }
16938
16939    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16940        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16941    }
16942
16943    private static boolean isSystemApp(PackageSetting ps) {
16944        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16945    }
16946
16947    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16948        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16949    }
16950
16951    private int packageFlagsToInstallFlags(PackageSetting ps) {
16952        int installFlags = 0;
16953        if (isEphemeral(ps)) {
16954            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16955        }
16956        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16957            // This existing package was an external ASEC install when we have
16958            // the external flag without a UUID
16959            installFlags |= PackageManager.INSTALL_EXTERNAL;
16960        }
16961        if (ps.isForwardLocked()) {
16962            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16963        }
16964        return installFlags;
16965    }
16966
16967    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16968        if (isExternal(pkg)) {
16969            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16970                return StorageManager.UUID_PRIMARY_PHYSICAL;
16971            } else {
16972                return pkg.volumeUuid;
16973            }
16974        } else {
16975            return StorageManager.UUID_PRIVATE_INTERNAL;
16976        }
16977    }
16978
16979    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16980        if (isExternal(pkg)) {
16981            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16982                return mSettings.getExternalVersion();
16983            } else {
16984                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16985            }
16986        } else {
16987            return mSettings.getInternalVersion();
16988        }
16989    }
16990
16991    private void deleteTempPackageFiles() {
16992        final FilenameFilter filter = new FilenameFilter() {
16993            public boolean accept(File dir, String name) {
16994                return name.startsWith("vmdl") && name.endsWith(".tmp");
16995            }
16996        };
16997        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16998            file.delete();
16999        }
17000    }
17001
17002    @Override
17003    public void deletePackageAsUser(String packageName, int versionCode,
17004            IPackageDeleteObserver observer, int userId, int flags) {
17005        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17006                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17007    }
17008
17009    @Override
17010    public void deletePackageVersioned(VersionedPackage versionedPackage,
17011            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17012        mContext.enforceCallingOrSelfPermission(
17013                android.Manifest.permission.DELETE_PACKAGES, null);
17014        Preconditions.checkNotNull(versionedPackage);
17015        Preconditions.checkNotNull(observer);
17016        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17017                PackageManager.VERSION_CODE_HIGHEST,
17018                Integer.MAX_VALUE, "versionCode must be >= -1");
17019
17020        final String packageName = versionedPackage.getPackageName();
17021        // TODO: We will change version code to long, so in the new API it is long
17022        final int versionCode = (int) versionedPackage.getVersionCode();
17023        final String internalPackageName;
17024        synchronized (mPackages) {
17025            // Normalize package name to handle renamed packages and static libs
17026            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17027                    // TODO: We will change version code to long, so in the new API it is long
17028                    (int) versionedPackage.getVersionCode());
17029        }
17030
17031        final int uid = Binder.getCallingUid();
17032        if (!isOrphaned(internalPackageName)
17033                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17034            try {
17035                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17036                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17037                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17038                observer.onUserActionRequired(intent);
17039            } catch (RemoteException re) {
17040            }
17041            return;
17042        }
17043        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17044        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17045        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17046            mContext.enforceCallingOrSelfPermission(
17047                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17048                    "deletePackage for user " + userId);
17049        }
17050
17051        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17052            try {
17053                observer.onPackageDeleted(packageName,
17054                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17055            } catch (RemoteException re) {
17056            }
17057            return;
17058        }
17059
17060        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17061            try {
17062                observer.onPackageDeleted(packageName,
17063                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17064            } catch (RemoteException re) {
17065            }
17066            return;
17067        }
17068
17069        if (DEBUG_REMOVE) {
17070            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17071                    + " deleteAllUsers: " + deleteAllUsers + " version="
17072                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17073                    ? "VERSION_CODE_HIGHEST" : versionCode));
17074        }
17075        // Queue up an async operation since the package deletion may take a little while.
17076        mHandler.post(new Runnable() {
17077            public void run() {
17078                mHandler.removeCallbacks(this);
17079                int returnCode;
17080                if (!deleteAllUsers) {
17081                    returnCode = deletePackageX(internalPackageName, versionCode,
17082                            userId, deleteFlags);
17083                } else {
17084                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17085                            internalPackageName, users);
17086                    // If nobody is blocking uninstall, proceed with delete for all users
17087                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17088                        returnCode = deletePackageX(internalPackageName, versionCode,
17089                                userId, deleteFlags);
17090                    } else {
17091                        // Otherwise uninstall individually for users with blockUninstalls=false
17092                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17093                        for (int userId : users) {
17094                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17095                                returnCode = deletePackageX(internalPackageName, versionCode,
17096                                        userId, userFlags);
17097                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17098                                    Slog.w(TAG, "Package delete failed for user " + userId
17099                                            + ", returnCode " + returnCode);
17100                                }
17101                            }
17102                        }
17103                        // The app has only been marked uninstalled for certain users.
17104                        // We still need to report that delete was blocked
17105                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17106                    }
17107                }
17108                try {
17109                    observer.onPackageDeleted(packageName, returnCode, null);
17110                } catch (RemoteException e) {
17111                    Log.i(TAG, "Observer no longer exists.");
17112                } //end catch
17113            } //end run
17114        });
17115    }
17116
17117    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17118        if (pkg.staticSharedLibName != null) {
17119            return pkg.manifestPackageName;
17120        }
17121        return pkg.packageName;
17122    }
17123
17124    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17125        // Handle renamed packages
17126        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17127        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17128
17129        // Is this a static library?
17130        SparseArray<SharedLibraryEntry> versionedLib =
17131                mStaticLibsByDeclaringPackage.get(packageName);
17132        if (versionedLib == null || versionedLib.size() <= 0) {
17133            return packageName;
17134        }
17135
17136        // Figure out which lib versions the caller can see
17137        SparseIntArray versionsCallerCanSee = null;
17138        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17139        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17140                && callingAppId != Process.ROOT_UID) {
17141            versionsCallerCanSee = new SparseIntArray();
17142            String libName = versionedLib.valueAt(0).info.getName();
17143            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17144            if (uidPackages != null) {
17145                for (String uidPackage : uidPackages) {
17146                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17147                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17148                    if (libIdx >= 0) {
17149                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17150                        versionsCallerCanSee.append(libVersion, libVersion);
17151                    }
17152                }
17153            }
17154        }
17155
17156        // Caller can see nothing - done
17157        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17158            return packageName;
17159        }
17160
17161        // Find the version the caller can see and the app version code
17162        SharedLibraryEntry highestVersion = null;
17163        final int versionCount = versionedLib.size();
17164        for (int i = 0; i < versionCount; i++) {
17165            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17166            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17167                    libEntry.info.getVersion()) < 0) {
17168                continue;
17169            }
17170            // TODO: We will change version code to long, so in the new API it is long
17171            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17172            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17173                if (libVersionCode == versionCode) {
17174                    return libEntry.apk;
17175                }
17176            } else if (highestVersion == null) {
17177                highestVersion = libEntry;
17178            } else if (libVersionCode  > highestVersion.info
17179                    .getDeclaringPackage().getVersionCode()) {
17180                highestVersion = libEntry;
17181            }
17182        }
17183
17184        if (highestVersion != null) {
17185            return highestVersion.apk;
17186        }
17187
17188        return packageName;
17189    }
17190
17191    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17192        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17193              || callingUid == Process.SYSTEM_UID) {
17194            return true;
17195        }
17196        final int callingUserId = UserHandle.getUserId(callingUid);
17197        // If the caller installed the pkgName, then allow it to silently uninstall.
17198        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17199            return true;
17200        }
17201
17202        // Allow package verifier to silently uninstall.
17203        if (mRequiredVerifierPackage != null &&
17204                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17205            return true;
17206        }
17207
17208        // Allow package uninstaller to silently uninstall.
17209        if (mRequiredUninstallerPackage != null &&
17210                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17211            return true;
17212        }
17213
17214        // Allow storage manager to silently uninstall.
17215        if (mStorageManagerPackage != null &&
17216                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17217            return true;
17218        }
17219        return false;
17220    }
17221
17222    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17223        int[] result = EMPTY_INT_ARRAY;
17224        for (int userId : userIds) {
17225            if (getBlockUninstallForUser(packageName, userId)) {
17226                result = ArrayUtils.appendInt(result, userId);
17227            }
17228        }
17229        return result;
17230    }
17231
17232    @Override
17233    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17234        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17235    }
17236
17237    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17238        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17239                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17240        try {
17241            if (dpm != null) {
17242                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17243                        /* callingUserOnly =*/ false);
17244                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17245                        : deviceOwnerComponentName.getPackageName();
17246                // Does the package contains the device owner?
17247                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17248                // this check is probably not needed, since DO should be registered as a device
17249                // admin on some user too. (Original bug for this: b/17657954)
17250                if (packageName.equals(deviceOwnerPackageName)) {
17251                    return true;
17252                }
17253                // Does it contain a device admin for any user?
17254                int[] users;
17255                if (userId == UserHandle.USER_ALL) {
17256                    users = sUserManager.getUserIds();
17257                } else {
17258                    users = new int[]{userId};
17259                }
17260                for (int i = 0; i < users.length; ++i) {
17261                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17262                        return true;
17263                    }
17264                }
17265            }
17266        } catch (RemoteException e) {
17267        }
17268        return false;
17269    }
17270
17271    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17272        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17273    }
17274
17275    /**
17276     *  This method is an internal method that could be get invoked either
17277     *  to delete an installed package or to clean up a failed installation.
17278     *  After deleting an installed package, a broadcast is sent to notify any
17279     *  listeners that the package has been removed. For cleaning up a failed
17280     *  installation, the broadcast is not necessary since the package's
17281     *  installation wouldn't have sent the initial broadcast either
17282     *  The key steps in deleting a package are
17283     *  deleting the package information in internal structures like mPackages,
17284     *  deleting the packages base directories through installd
17285     *  updating mSettings to reflect current status
17286     *  persisting settings for later use
17287     *  sending a broadcast if necessary
17288     */
17289    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17290        final PackageRemovedInfo info = new PackageRemovedInfo();
17291        final boolean res;
17292
17293        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17294                ? UserHandle.USER_ALL : userId;
17295
17296        if (isPackageDeviceAdmin(packageName, removeUser)) {
17297            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17298            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17299        }
17300
17301        PackageSetting uninstalledPs = null;
17302
17303        // for the uninstall-updates case and restricted profiles, remember the per-
17304        // user handle installed state
17305        int[] allUsers;
17306        synchronized (mPackages) {
17307            uninstalledPs = mSettings.mPackages.get(packageName);
17308            if (uninstalledPs == null) {
17309                Slog.w(TAG, "Not removing non-existent package " + packageName);
17310                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17311            }
17312
17313            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17314                    && uninstalledPs.versionCode != versionCode) {
17315                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17316                        + uninstalledPs.versionCode + " != " + versionCode);
17317                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17318            }
17319
17320            // Static shared libs can be declared by any package, so let us not
17321            // allow removing a package if it provides a lib others depend on.
17322            PackageParser.Package pkg = mPackages.get(packageName);
17323            if (pkg != null && pkg.staticSharedLibName != null) {
17324                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17325                        pkg.staticSharedLibVersion);
17326                if (libEntry != null) {
17327                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17328                            libEntry.info, 0, userId);
17329                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17330                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17331                                + " hosting lib " + libEntry.info.getName() + " version "
17332                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17333                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17334                    }
17335                }
17336            }
17337
17338            allUsers = sUserManager.getUserIds();
17339            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17340        }
17341
17342        final int freezeUser;
17343        if (isUpdatedSystemApp(uninstalledPs)
17344                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17345            // We're downgrading a system app, which will apply to all users, so
17346            // freeze them all during the downgrade
17347            freezeUser = UserHandle.USER_ALL;
17348        } else {
17349            freezeUser = removeUser;
17350        }
17351
17352        synchronized (mInstallLock) {
17353            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17354            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17355                    deleteFlags, "deletePackageX")) {
17356                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17357                        deleteFlags | REMOVE_CHATTY, info, true, null);
17358            }
17359            synchronized (mPackages) {
17360                if (res) {
17361                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
17362                }
17363            }
17364        }
17365
17366        if (res) {
17367            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17368            info.sendPackageRemovedBroadcasts(killApp);
17369            info.sendSystemPackageUpdatedBroadcasts();
17370            info.sendSystemPackageAppearedBroadcasts();
17371        }
17372        // Force a gc here.
17373        Runtime.getRuntime().gc();
17374        // Delete the resources here after sending the broadcast to let
17375        // other processes clean up before deleting resources.
17376        if (info.args != null) {
17377            synchronized (mInstallLock) {
17378                info.args.doPostDeleteLI(true);
17379            }
17380        }
17381
17382        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17383    }
17384
17385    class PackageRemovedInfo {
17386        String removedPackage;
17387        int uid = -1;
17388        int removedAppId = -1;
17389        int[] origUsers;
17390        int[] removedUsers = null;
17391        SparseArray<Integer> installReasons;
17392        boolean isRemovedPackageSystemUpdate = false;
17393        boolean isUpdate;
17394        boolean dataRemoved;
17395        boolean removedForAllUsers;
17396        boolean isStaticSharedLib;
17397        // Clean up resources deleted packages.
17398        InstallArgs args = null;
17399        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17400        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17401
17402        void sendPackageRemovedBroadcasts(boolean killApp) {
17403            sendPackageRemovedBroadcastInternal(killApp);
17404            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17405            for (int i = 0; i < childCount; i++) {
17406                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17407                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17408            }
17409        }
17410
17411        void sendSystemPackageUpdatedBroadcasts() {
17412            if (isRemovedPackageSystemUpdate) {
17413                sendSystemPackageUpdatedBroadcastsInternal();
17414                final int childCount = (removedChildPackages != null)
17415                        ? removedChildPackages.size() : 0;
17416                for (int i = 0; i < childCount; i++) {
17417                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17418                    if (childInfo.isRemovedPackageSystemUpdate) {
17419                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17420                    }
17421                }
17422            }
17423        }
17424
17425        void sendSystemPackageAppearedBroadcasts() {
17426            final int packageCount = (appearedChildPackages != null)
17427                    ? appearedChildPackages.size() : 0;
17428            for (int i = 0; i < packageCount; i++) {
17429                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17430                sendPackageAddedForNewUsers(installedInfo.name, true,
17431                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17432            }
17433        }
17434
17435        private void sendSystemPackageUpdatedBroadcastsInternal() {
17436            Bundle extras = new Bundle(2);
17437            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17438            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17439            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17440                    extras, 0, null, null, null);
17441            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17442                    extras, 0, null, null, null);
17443            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17444                    null, 0, removedPackage, null, null);
17445        }
17446
17447        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17448            // Don't send static shared library removal broadcasts as these
17449            // libs are visible only the the apps that depend on them an one
17450            // cannot remove the library if it has a dependency.
17451            if (isStaticSharedLib) {
17452                return;
17453            }
17454            Bundle extras = new Bundle(2);
17455            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17456            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17457            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17458            if (isUpdate || isRemovedPackageSystemUpdate) {
17459                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17460            }
17461            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17462            if (removedPackage != null) {
17463                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17464                        extras, 0, null, null, removedUsers);
17465                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17466                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17467                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17468                            null, null, removedUsers);
17469                }
17470            }
17471            if (removedAppId >= 0) {
17472                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17473                        removedUsers);
17474            }
17475        }
17476    }
17477
17478    /*
17479     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17480     * flag is not set, the data directory is removed as well.
17481     * make sure this flag is set for partially installed apps. If not its meaningless to
17482     * delete a partially installed application.
17483     */
17484    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17485            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17486        String packageName = ps.name;
17487        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17488        // Retrieve object to delete permissions for shared user later on
17489        final PackageParser.Package deletedPkg;
17490        final PackageSetting deletedPs;
17491        // reader
17492        synchronized (mPackages) {
17493            deletedPkg = mPackages.get(packageName);
17494            deletedPs = mSettings.mPackages.get(packageName);
17495            if (outInfo != null) {
17496                outInfo.removedPackage = packageName;
17497                outInfo.isStaticSharedLib = deletedPkg != null
17498                        && deletedPkg.staticSharedLibName != null;
17499                outInfo.removedUsers = deletedPs != null
17500                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17501                        : null;
17502            }
17503        }
17504
17505        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17506
17507        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17508            final PackageParser.Package resolvedPkg;
17509            if (deletedPkg != null) {
17510                resolvedPkg = deletedPkg;
17511            } else {
17512                // We don't have a parsed package when it lives on an ejected
17513                // adopted storage device, so fake something together
17514                resolvedPkg = new PackageParser.Package(ps.name);
17515                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17516            }
17517            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17518                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17519            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17520            if (outInfo != null) {
17521                outInfo.dataRemoved = true;
17522            }
17523            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17524        }
17525
17526        int removedAppId = -1;
17527
17528        // writer
17529        synchronized (mPackages) {
17530            if (deletedPs != null) {
17531                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17532                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17533                    clearDefaultBrowserIfNeeded(packageName);
17534                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17535                    removedAppId = mSettings.removePackageLPw(packageName);
17536                    if (outInfo != null) {
17537                        outInfo.removedAppId = removedAppId;
17538                    }
17539                    updatePermissionsLPw(deletedPs.name, null, 0);
17540                    if (deletedPs.sharedUser != null) {
17541                        // Remove permissions associated with package. Since runtime
17542                        // permissions are per user we have to kill the removed package
17543                        // or packages running under the shared user of the removed
17544                        // package if revoking the permissions requested only by the removed
17545                        // package is successful and this causes a change in gids.
17546                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17547                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17548                                    userId);
17549                            if (userIdToKill == UserHandle.USER_ALL
17550                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17551                                // If gids changed for this user, kill all affected packages.
17552                                mHandler.post(new Runnable() {
17553                                    @Override
17554                                    public void run() {
17555                                        // This has to happen with no lock held.
17556                                        killApplication(deletedPs.name, deletedPs.appId,
17557                                                KILL_APP_REASON_GIDS_CHANGED);
17558                                    }
17559                                });
17560                                break;
17561                            }
17562                        }
17563                    }
17564                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17565                }
17566                // make sure to preserve per-user disabled state if this removal was just
17567                // a downgrade of a system app to the factory package
17568                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17569                    if (DEBUG_REMOVE) {
17570                        Slog.d(TAG, "Propagating install state across downgrade");
17571                    }
17572                    for (int userId : allUserHandles) {
17573                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17574                        if (DEBUG_REMOVE) {
17575                            Slog.d(TAG, "    user " + userId + " => " + installed);
17576                        }
17577                        ps.setInstalled(installed, userId);
17578                    }
17579                }
17580            }
17581            // can downgrade to reader
17582            if (writeSettings) {
17583                // Save settings now
17584                mSettings.writeLPr();
17585            }
17586        }
17587        if (removedAppId != -1) {
17588            // A user ID was deleted here. Go through all users and remove it
17589            // from KeyStore.
17590            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17591        }
17592    }
17593
17594    static boolean locationIsPrivileged(File path) {
17595        try {
17596            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17597                    .getCanonicalPath();
17598            return path.getCanonicalPath().startsWith(privilegedAppDir);
17599        } catch (IOException e) {
17600            Slog.e(TAG, "Unable to access code path " + path);
17601        }
17602        return false;
17603    }
17604
17605    /*
17606     * Tries to delete system package.
17607     */
17608    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17609            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17610            boolean writeSettings) {
17611        if (deletedPs.parentPackageName != null) {
17612            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17613            return false;
17614        }
17615
17616        final boolean applyUserRestrictions
17617                = (allUserHandles != null) && (outInfo.origUsers != null);
17618        final PackageSetting disabledPs;
17619        // Confirm if the system package has been updated
17620        // An updated system app can be deleted. This will also have to restore
17621        // the system pkg from system partition
17622        // reader
17623        synchronized (mPackages) {
17624            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17625        }
17626
17627        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17628                + " disabledPs=" + disabledPs);
17629
17630        if (disabledPs == null) {
17631            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17632            return false;
17633        } else if (DEBUG_REMOVE) {
17634            Slog.d(TAG, "Deleting system pkg from data partition");
17635        }
17636
17637        if (DEBUG_REMOVE) {
17638            if (applyUserRestrictions) {
17639                Slog.d(TAG, "Remembering install states:");
17640                for (int userId : allUserHandles) {
17641                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17642                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17643                }
17644            }
17645        }
17646
17647        // Delete the updated package
17648        outInfo.isRemovedPackageSystemUpdate = true;
17649        if (outInfo.removedChildPackages != null) {
17650            final int childCount = (deletedPs.childPackageNames != null)
17651                    ? deletedPs.childPackageNames.size() : 0;
17652            for (int i = 0; i < childCount; i++) {
17653                String childPackageName = deletedPs.childPackageNames.get(i);
17654                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17655                        .contains(childPackageName)) {
17656                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17657                            childPackageName);
17658                    if (childInfo != null) {
17659                        childInfo.isRemovedPackageSystemUpdate = true;
17660                    }
17661                }
17662            }
17663        }
17664
17665        if (disabledPs.versionCode < deletedPs.versionCode) {
17666            // Delete data for downgrades
17667            flags &= ~PackageManager.DELETE_KEEP_DATA;
17668        } else {
17669            // Preserve data by setting flag
17670            flags |= PackageManager.DELETE_KEEP_DATA;
17671        }
17672
17673        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17674                outInfo, writeSettings, disabledPs.pkg);
17675        if (!ret) {
17676            return false;
17677        }
17678
17679        // writer
17680        synchronized (mPackages) {
17681            // Reinstate the old system package
17682            enableSystemPackageLPw(disabledPs.pkg);
17683            // Remove any native libraries from the upgraded package.
17684            removeNativeBinariesLI(deletedPs);
17685        }
17686
17687        // Install the system package
17688        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17689        int parseFlags = mDefParseFlags
17690                | PackageParser.PARSE_MUST_BE_APK
17691                | PackageParser.PARSE_IS_SYSTEM
17692                | PackageParser.PARSE_IS_SYSTEM_DIR;
17693        if (locationIsPrivileged(disabledPs.codePath)) {
17694            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17695        }
17696
17697        final PackageParser.Package newPkg;
17698        try {
17699            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17700                0 /* currentTime */, null);
17701        } catch (PackageManagerException e) {
17702            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17703                    + e.getMessage());
17704            return false;
17705        }
17706
17707        prepareAppDataAfterInstallLIF(newPkg);
17708
17709        // writer
17710        synchronized (mPackages) {
17711            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17712
17713            // Propagate the permissions state as we do not want to drop on the floor
17714            // runtime permissions. The update permissions method below will take
17715            // care of removing obsolete permissions and grant install permissions.
17716            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17717            updatePermissionsLPw(newPkg.packageName, newPkg,
17718                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17719
17720            if (applyUserRestrictions) {
17721                if (DEBUG_REMOVE) {
17722                    Slog.d(TAG, "Propagating install state across reinstall");
17723                }
17724                for (int userId : allUserHandles) {
17725                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17726                    if (DEBUG_REMOVE) {
17727                        Slog.d(TAG, "    user " + userId + " => " + installed);
17728                    }
17729                    ps.setInstalled(installed, userId);
17730
17731                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17732                }
17733                // Regardless of writeSettings we need to ensure that this restriction
17734                // state propagation is persisted
17735                mSettings.writeAllUsersPackageRestrictionsLPr();
17736            }
17737            // can downgrade to reader here
17738            if (writeSettings) {
17739                mSettings.writeLPr();
17740            }
17741        }
17742        return true;
17743    }
17744
17745    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17746            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17747            PackageRemovedInfo outInfo, boolean writeSettings,
17748            PackageParser.Package replacingPackage) {
17749        synchronized (mPackages) {
17750            if (outInfo != null) {
17751                outInfo.uid = ps.appId;
17752            }
17753
17754            if (outInfo != null && outInfo.removedChildPackages != null) {
17755                final int childCount = (ps.childPackageNames != null)
17756                        ? ps.childPackageNames.size() : 0;
17757                for (int i = 0; i < childCount; i++) {
17758                    String childPackageName = ps.childPackageNames.get(i);
17759                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17760                    if (childPs == null) {
17761                        return false;
17762                    }
17763                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17764                            childPackageName);
17765                    if (childInfo != null) {
17766                        childInfo.uid = childPs.appId;
17767                    }
17768                }
17769            }
17770        }
17771
17772        // Delete package data from internal structures and also remove data if flag is set
17773        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17774
17775        // Delete the child packages data
17776        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17777        for (int i = 0; i < childCount; i++) {
17778            PackageSetting childPs;
17779            synchronized (mPackages) {
17780                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17781            }
17782            if (childPs != null) {
17783                PackageRemovedInfo childOutInfo = (outInfo != null
17784                        && outInfo.removedChildPackages != null)
17785                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17786                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17787                        && (replacingPackage != null
17788                        && !replacingPackage.hasChildPackage(childPs.name))
17789                        ? flags & ~DELETE_KEEP_DATA : flags;
17790                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17791                        deleteFlags, writeSettings);
17792            }
17793        }
17794
17795        // Delete application code and resources only for parent packages
17796        if (ps.parentPackageName == null) {
17797            if (deleteCodeAndResources && (outInfo != null)) {
17798                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17799                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17800                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17801            }
17802        }
17803
17804        return true;
17805    }
17806
17807    @Override
17808    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17809            int userId) {
17810        mContext.enforceCallingOrSelfPermission(
17811                android.Manifest.permission.DELETE_PACKAGES, null);
17812        synchronized (mPackages) {
17813            PackageSetting ps = mSettings.mPackages.get(packageName);
17814            if (ps == null) {
17815                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17816                return false;
17817            }
17818            // Cannot block uninstall of static shared libs as they are
17819            // considered a part of the using app (emulating static linking).
17820            // Also static libs are installed always on internal storage.
17821            PackageParser.Package pkg = mPackages.get(packageName);
17822            if (pkg != null && pkg.staticSharedLibName != null) {
17823                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17824                        + " providing static shared library: " + pkg.staticSharedLibName);
17825                return false;
17826            }
17827            if (!ps.getInstalled(userId)) {
17828                // Can't block uninstall for an app that is not installed or enabled.
17829                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17830                return false;
17831            }
17832            ps.setBlockUninstall(blockUninstall, userId);
17833            mSettings.writePackageRestrictionsLPr(userId);
17834        }
17835        return true;
17836    }
17837
17838    @Override
17839    public boolean getBlockUninstallForUser(String packageName, int userId) {
17840        synchronized (mPackages) {
17841            PackageSetting ps = mSettings.mPackages.get(packageName);
17842            if (ps == null) {
17843                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17844                return false;
17845            }
17846            return ps.getBlockUninstall(userId);
17847        }
17848    }
17849
17850    @Override
17851    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17852        int callingUid = Binder.getCallingUid();
17853        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17854            throw new SecurityException(
17855                    "setRequiredForSystemUser can only be run by the system or root");
17856        }
17857        synchronized (mPackages) {
17858            PackageSetting ps = mSettings.mPackages.get(packageName);
17859            if (ps == null) {
17860                Log.w(TAG, "Package doesn't exist: " + packageName);
17861                return false;
17862            }
17863            if (systemUserApp) {
17864                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17865            } else {
17866                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17867            }
17868            mSettings.writeLPr();
17869        }
17870        return true;
17871    }
17872
17873    /*
17874     * This method handles package deletion in general
17875     */
17876    private boolean deletePackageLIF(String packageName, UserHandle user,
17877            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17878            PackageRemovedInfo outInfo, boolean writeSettings,
17879            PackageParser.Package replacingPackage) {
17880        if (packageName == null) {
17881            Slog.w(TAG, "Attempt to delete null packageName.");
17882            return false;
17883        }
17884
17885        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17886
17887        PackageSetting ps;
17888        synchronized (mPackages) {
17889            ps = mSettings.mPackages.get(packageName);
17890            if (ps == null) {
17891                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17892                return false;
17893            }
17894
17895            if (ps.parentPackageName != null && (!isSystemApp(ps)
17896                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17897                if (DEBUG_REMOVE) {
17898                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17899                            + ((user == null) ? UserHandle.USER_ALL : user));
17900                }
17901                final int removedUserId = (user != null) ? user.getIdentifier()
17902                        : UserHandle.USER_ALL;
17903                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17904                    return false;
17905                }
17906                markPackageUninstalledForUserLPw(ps, user);
17907                scheduleWritePackageRestrictionsLocked(user);
17908                return true;
17909            }
17910        }
17911
17912        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17913                && user.getIdentifier() != UserHandle.USER_ALL)) {
17914            // The caller is asking that the package only be deleted for a single
17915            // user.  To do this, we just mark its uninstalled state and delete
17916            // its data. If this is a system app, we only allow this to happen if
17917            // they have set the special DELETE_SYSTEM_APP which requests different
17918            // semantics than normal for uninstalling system apps.
17919            markPackageUninstalledForUserLPw(ps, user);
17920
17921            if (!isSystemApp(ps)) {
17922                // Do not uninstall the APK if an app should be cached
17923                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17924                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17925                    // Other user still have this package installed, so all
17926                    // we need to do is clear this user's data and save that
17927                    // it is uninstalled.
17928                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17929                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17930                        return false;
17931                    }
17932                    scheduleWritePackageRestrictionsLocked(user);
17933                    return true;
17934                } else {
17935                    // We need to set it back to 'installed' so the uninstall
17936                    // broadcasts will be sent correctly.
17937                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17938                    ps.setInstalled(true, user.getIdentifier());
17939                }
17940            } else {
17941                // This is a system app, so we assume that the
17942                // other users still have this package installed, so all
17943                // we need to do is clear this user's data and save that
17944                // it is uninstalled.
17945                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17946                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17947                    return false;
17948                }
17949                scheduleWritePackageRestrictionsLocked(user);
17950                return true;
17951            }
17952        }
17953
17954        // If we are deleting a composite package for all users, keep track
17955        // of result for each child.
17956        if (ps.childPackageNames != null && outInfo != null) {
17957            synchronized (mPackages) {
17958                final int childCount = ps.childPackageNames.size();
17959                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17960                for (int i = 0; i < childCount; i++) {
17961                    String childPackageName = ps.childPackageNames.get(i);
17962                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17963                    childInfo.removedPackage = childPackageName;
17964                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17965                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17966                    if (childPs != null) {
17967                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17968                    }
17969                }
17970            }
17971        }
17972
17973        boolean ret = false;
17974        if (isSystemApp(ps)) {
17975            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17976            // When an updated system application is deleted we delete the existing resources
17977            // as well and fall back to existing code in system partition
17978            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17979        } else {
17980            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17981            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17982                    outInfo, writeSettings, replacingPackage);
17983        }
17984
17985        // Take a note whether we deleted the package for all users
17986        if (outInfo != null) {
17987            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17988            if (outInfo.removedChildPackages != null) {
17989                synchronized (mPackages) {
17990                    final int childCount = outInfo.removedChildPackages.size();
17991                    for (int i = 0; i < childCount; i++) {
17992                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17993                        if (childInfo != null) {
17994                            childInfo.removedForAllUsers = mPackages.get(
17995                                    childInfo.removedPackage) == null;
17996                        }
17997                    }
17998                }
17999            }
18000            // If we uninstalled an update to a system app there may be some
18001            // child packages that appeared as they are declared in the system
18002            // app but were not declared in the update.
18003            if (isSystemApp(ps)) {
18004                synchronized (mPackages) {
18005                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18006                    final int childCount = (updatedPs.childPackageNames != null)
18007                            ? updatedPs.childPackageNames.size() : 0;
18008                    for (int i = 0; i < childCount; i++) {
18009                        String childPackageName = updatedPs.childPackageNames.get(i);
18010                        if (outInfo.removedChildPackages == null
18011                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18012                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18013                            if (childPs == null) {
18014                                continue;
18015                            }
18016                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18017                            installRes.name = childPackageName;
18018                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18019                            installRes.pkg = mPackages.get(childPackageName);
18020                            installRes.uid = childPs.pkg.applicationInfo.uid;
18021                            if (outInfo.appearedChildPackages == null) {
18022                                outInfo.appearedChildPackages = new ArrayMap<>();
18023                            }
18024                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18025                        }
18026                    }
18027                }
18028            }
18029        }
18030
18031        return ret;
18032    }
18033
18034    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18035        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18036                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18037        for (int nextUserId : userIds) {
18038            if (DEBUG_REMOVE) {
18039                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18040            }
18041            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18042                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18043                    false /*hidden*/, false /*suspended*/, null, null, null,
18044                    false /*blockUninstall*/,
18045                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18046                    PackageManager.INSTALL_REASON_UNKNOWN);
18047        }
18048    }
18049
18050    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18051            PackageRemovedInfo outInfo) {
18052        final PackageParser.Package pkg;
18053        synchronized (mPackages) {
18054            pkg = mPackages.get(ps.name);
18055        }
18056
18057        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18058                : new int[] {userId};
18059        for (int nextUserId : userIds) {
18060            if (DEBUG_REMOVE) {
18061                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18062                        + nextUserId);
18063            }
18064
18065            destroyAppDataLIF(pkg, userId,
18066                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18067            destroyAppProfilesLIF(pkg, userId);
18068            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18069            schedulePackageCleaning(ps.name, nextUserId, false);
18070            synchronized (mPackages) {
18071                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18072                    scheduleWritePackageRestrictionsLocked(nextUserId);
18073                }
18074                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18075            }
18076        }
18077
18078        if (outInfo != null) {
18079            outInfo.removedPackage = ps.name;
18080            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18081            outInfo.removedAppId = ps.appId;
18082            outInfo.removedUsers = userIds;
18083        }
18084
18085        return true;
18086    }
18087
18088    private final class ClearStorageConnection implements ServiceConnection {
18089        IMediaContainerService mContainerService;
18090
18091        @Override
18092        public void onServiceConnected(ComponentName name, IBinder service) {
18093            synchronized (this) {
18094                mContainerService = IMediaContainerService.Stub
18095                        .asInterface(Binder.allowBlocking(service));
18096                notifyAll();
18097            }
18098        }
18099
18100        @Override
18101        public void onServiceDisconnected(ComponentName name) {
18102        }
18103    }
18104
18105    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18106        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18107
18108        final boolean mounted;
18109        if (Environment.isExternalStorageEmulated()) {
18110            mounted = true;
18111        } else {
18112            final String status = Environment.getExternalStorageState();
18113
18114            mounted = status.equals(Environment.MEDIA_MOUNTED)
18115                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18116        }
18117
18118        if (!mounted) {
18119            return;
18120        }
18121
18122        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18123        int[] users;
18124        if (userId == UserHandle.USER_ALL) {
18125            users = sUserManager.getUserIds();
18126        } else {
18127            users = new int[] { userId };
18128        }
18129        final ClearStorageConnection conn = new ClearStorageConnection();
18130        if (mContext.bindServiceAsUser(
18131                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18132            try {
18133                for (int curUser : users) {
18134                    long timeout = SystemClock.uptimeMillis() + 5000;
18135                    synchronized (conn) {
18136                        long now;
18137                        while (conn.mContainerService == null &&
18138                                (now = SystemClock.uptimeMillis()) < timeout) {
18139                            try {
18140                                conn.wait(timeout - now);
18141                            } catch (InterruptedException e) {
18142                            }
18143                        }
18144                    }
18145                    if (conn.mContainerService == null) {
18146                        return;
18147                    }
18148
18149                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18150                    clearDirectory(conn.mContainerService,
18151                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18152                    if (allData) {
18153                        clearDirectory(conn.mContainerService,
18154                                userEnv.buildExternalStorageAppDataDirs(packageName));
18155                        clearDirectory(conn.mContainerService,
18156                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18157                    }
18158                }
18159            } finally {
18160                mContext.unbindService(conn);
18161            }
18162        }
18163    }
18164
18165    @Override
18166    public void clearApplicationProfileData(String packageName) {
18167        enforceSystemOrRoot("Only the system can clear all profile data");
18168
18169        final PackageParser.Package pkg;
18170        synchronized (mPackages) {
18171            pkg = mPackages.get(packageName);
18172        }
18173
18174        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18175            synchronized (mInstallLock) {
18176                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18177                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18178                        true /* removeBaseMarker */);
18179            }
18180        }
18181    }
18182
18183    @Override
18184    public void clearApplicationUserData(final String packageName,
18185            final IPackageDataObserver observer, final int userId) {
18186        mContext.enforceCallingOrSelfPermission(
18187                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18188
18189        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18190                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18191
18192        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18193            throw new SecurityException("Cannot clear data for a protected package: "
18194                    + packageName);
18195        }
18196        // Queue up an async operation since the package deletion may take a little while.
18197        mHandler.post(new Runnable() {
18198            public void run() {
18199                mHandler.removeCallbacks(this);
18200                final boolean succeeded;
18201                try (PackageFreezer freezer = freezePackage(packageName,
18202                        "clearApplicationUserData")) {
18203                    synchronized (mInstallLock) {
18204                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18205                    }
18206                    clearExternalStorageDataSync(packageName, userId, true);
18207                }
18208                if (succeeded) {
18209                    // invoke DeviceStorageMonitor's update method to clear any notifications
18210                    DeviceStorageMonitorInternal dsm = LocalServices
18211                            .getService(DeviceStorageMonitorInternal.class);
18212                    if (dsm != null) {
18213                        dsm.checkMemory();
18214                    }
18215                }
18216                if(observer != null) {
18217                    try {
18218                        observer.onRemoveCompleted(packageName, succeeded);
18219                    } catch (RemoteException e) {
18220                        Log.i(TAG, "Observer no longer exists.");
18221                    }
18222                } //end if observer
18223            } //end run
18224        });
18225    }
18226
18227    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18228        if (packageName == null) {
18229            Slog.w(TAG, "Attempt to delete null packageName.");
18230            return false;
18231        }
18232
18233        // Try finding details about the requested package
18234        PackageParser.Package pkg;
18235        synchronized (mPackages) {
18236            pkg = mPackages.get(packageName);
18237            if (pkg == null) {
18238                final PackageSetting ps = mSettings.mPackages.get(packageName);
18239                if (ps != null) {
18240                    pkg = ps.pkg;
18241                }
18242            }
18243
18244            if (pkg == null) {
18245                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18246                return false;
18247            }
18248
18249            PackageSetting ps = (PackageSetting) pkg.mExtras;
18250            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18251        }
18252
18253        clearAppDataLIF(pkg, userId,
18254                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18255
18256        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18257        removeKeystoreDataIfNeeded(userId, appId);
18258
18259        UserManagerInternal umInternal = getUserManagerInternal();
18260        final int flags;
18261        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18262            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18263        } else if (umInternal.isUserRunning(userId)) {
18264            flags = StorageManager.FLAG_STORAGE_DE;
18265        } else {
18266            flags = 0;
18267        }
18268        prepareAppDataContentsLIF(pkg, userId, flags);
18269
18270        return true;
18271    }
18272
18273    /**
18274     * Reverts user permission state changes (permissions and flags) in
18275     * all packages for a given user.
18276     *
18277     * @param userId The device user for which to do a reset.
18278     */
18279    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18280        final int packageCount = mPackages.size();
18281        for (int i = 0; i < packageCount; i++) {
18282            PackageParser.Package pkg = mPackages.valueAt(i);
18283            PackageSetting ps = (PackageSetting) pkg.mExtras;
18284            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18285        }
18286    }
18287
18288    private void resetNetworkPolicies(int userId) {
18289        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18290    }
18291
18292    /**
18293     * Reverts user permission state changes (permissions and flags).
18294     *
18295     * @param ps The package for which to reset.
18296     * @param userId The device user for which to do a reset.
18297     */
18298    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18299            final PackageSetting ps, final int userId) {
18300        if (ps.pkg == null) {
18301            return;
18302        }
18303
18304        // These are flags that can change base on user actions.
18305        final int userSettableMask = FLAG_PERMISSION_USER_SET
18306                | FLAG_PERMISSION_USER_FIXED
18307                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18308                | FLAG_PERMISSION_REVIEW_REQUIRED;
18309
18310        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18311                | FLAG_PERMISSION_POLICY_FIXED;
18312
18313        boolean writeInstallPermissions = false;
18314        boolean writeRuntimePermissions = false;
18315
18316        final int permissionCount = ps.pkg.requestedPermissions.size();
18317        for (int i = 0; i < permissionCount; i++) {
18318            String permission = ps.pkg.requestedPermissions.get(i);
18319
18320            BasePermission bp = mSettings.mPermissions.get(permission);
18321            if (bp == null) {
18322                continue;
18323            }
18324
18325            // If shared user we just reset the state to which only this app contributed.
18326            if (ps.sharedUser != null) {
18327                boolean used = false;
18328                final int packageCount = ps.sharedUser.packages.size();
18329                for (int j = 0; j < packageCount; j++) {
18330                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18331                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18332                            && pkg.pkg.requestedPermissions.contains(permission)) {
18333                        used = true;
18334                        break;
18335                    }
18336                }
18337                if (used) {
18338                    continue;
18339                }
18340            }
18341
18342            PermissionsState permissionsState = ps.getPermissionsState();
18343
18344            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18345
18346            // Always clear the user settable flags.
18347            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18348                    bp.name) != null;
18349            // If permission review is enabled and this is a legacy app, mark the
18350            // permission as requiring a review as this is the initial state.
18351            int flags = 0;
18352            if (mPermissionReviewRequired
18353                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18354                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18355            }
18356            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18357                if (hasInstallState) {
18358                    writeInstallPermissions = true;
18359                } else {
18360                    writeRuntimePermissions = true;
18361                }
18362            }
18363
18364            // Below is only runtime permission handling.
18365            if (!bp.isRuntime()) {
18366                continue;
18367            }
18368
18369            // Never clobber system or policy.
18370            if ((oldFlags & policyOrSystemFlags) != 0) {
18371                continue;
18372            }
18373
18374            // If this permission was granted by default, make sure it is.
18375            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18376                if (permissionsState.grantRuntimePermission(bp, userId)
18377                        != PERMISSION_OPERATION_FAILURE) {
18378                    writeRuntimePermissions = true;
18379                }
18380            // If permission review is enabled the permissions for a legacy apps
18381            // are represented as constantly granted runtime ones, so don't revoke.
18382            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18383                // Otherwise, reset the permission.
18384                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18385                switch (revokeResult) {
18386                    case PERMISSION_OPERATION_SUCCESS:
18387                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18388                        writeRuntimePermissions = true;
18389                        final int appId = ps.appId;
18390                        mHandler.post(new Runnable() {
18391                            @Override
18392                            public void run() {
18393                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18394                            }
18395                        });
18396                    } break;
18397                }
18398            }
18399        }
18400
18401        // Synchronously write as we are taking permissions away.
18402        if (writeRuntimePermissions) {
18403            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18404        }
18405
18406        // Synchronously write as we are taking permissions away.
18407        if (writeInstallPermissions) {
18408            mSettings.writeLPr();
18409        }
18410    }
18411
18412    /**
18413     * Remove entries from the keystore daemon. Will only remove it if the
18414     * {@code appId} is valid.
18415     */
18416    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18417        if (appId < 0) {
18418            return;
18419        }
18420
18421        final KeyStore keyStore = KeyStore.getInstance();
18422        if (keyStore != null) {
18423            if (userId == UserHandle.USER_ALL) {
18424                for (final int individual : sUserManager.getUserIds()) {
18425                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18426                }
18427            } else {
18428                keyStore.clearUid(UserHandle.getUid(userId, appId));
18429            }
18430        } else {
18431            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18432        }
18433    }
18434
18435    @Override
18436    public void deleteApplicationCacheFiles(final String packageName,
18437            final IPackageDataObserver observer) {
18438        final int userId = UserHandle.getCallingUserId();
18439        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18440    }
18441
18442    @Override
18443    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18444            final IPackageDataObserver observer) {
18445        mContext.enforceCallingOrSelfPermission(
18446                android.Manifest.permission.DELETE_CACHE_FILES, null);
18447        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18448                /* requireFullPermission= */ true, /* checkShell= */ false,
18449                "delete application cache files");
18450
18451        final PackageParser.Package pkg;
18452        synchronized (mPackages) {
18453            pkg = mPackages.get(packageName);
18454        }
18455
18456        // Queue up an async operation since the package deletion may take a little while.
18457        mHandler.post(new Runnable() {
18458            public void run() {
18459                synchronized (mInstallLock) {
18460                    final int flags = StorageManager.FLAG_STORAGE_DE
18461                            | StorageManager.FLAG_STORAGE_CE;
18462                    // We're only clearing cache files, so we don't care if the
18463                    // app is unfrozen and still able to run
18464                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18465                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18466                }
18467                clearExternalStorageDataSync(packageName, userId, false);
18468                if (observer != null) {
18469                    try {
18470                        observer.onRemoveCompleted(packageName, true);
18471                    } catch (RemoteException e) {
18472                        Log.i(TAG, "Observer no longer exists.");
18473                    }
18474                }
18475            }
18476        });
18477    }
18478
18479    @Override
18480    public void getPackageSizeInfo(final String packageName, int userHandle,
18481            final IPackageStatsObserver observer) {
18482        mContext.enforceCallingOrSelfPermission(
18483                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18484        if (packageName == null) {
18485            throw new IllegalArgumentException("Attempt to get size of null packageName");
18486        }
18487
18488        PackageStats stats = new PackageStats(packageName, userHandle);
18489
18490        /*
18491         * Queue up an async operation since the package measurement may take a
18492         * little while.
18493         */
18494        Message msg = mHandler.obtainMessage(INIT_COPY);
18495        msg.obj = new MeasureParams(stats, observer);
18496        mHandler.sendMessage(msg);
18497    }
18498
18499    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18500        final PackageSetting ps;
18501        synchronized (mPackages) {
18502            ps = mSettings.mPackages.get(packageName);
18503            if (ps == null) {
18504                Slog.w(TAG, "Failed to find settings for " + packageName);
18505                return false;
18506            }
18507        }
18508
18509        final String[] packageNames = { packageName };
18510        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18511        final String[] codePaths = { ps.codePathString };
18512
18513        try {
18514            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18515                    ps.appId, ceDataInodes, codePaths, stats);
18516
18517            // For now, ignore code size of packages on system partition
18518            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18519                stats.codeSize = 0;
18520            }
18521
18522            // External clients expect these to be tracked separately
18523            stats.dataSize -= stats.cacheSize;
18524
18525        } catch (InstallerException e) {
18526            Slog.w(TAG, String.valueOf(e));
18527            return false;
18528        }
18529
18530        return true;
18531    }
18532
18533    private int getUidTargetSdkVersionLockedLPr(int uid) {
18534        Object obj = mSettings.getUserIdLPr(uid);
18535        if (obj instanceof SharedUserSetting) {
18536            final SharedUserSetting sus = (SharedUserSetting) obj;
18537            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18538            final Iterator<PackageSetting> it = sus.packages.iterator();
18539            while (it.hasNext()) {
18540                final PackageSetting ps = it.next();
18541                if (ps.pkg != null) {
18542                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18543                    if (v < vers) vers = v;
18544                }
18545            }
18546            return vers;
18547        } else if (obj instanceof PackageSetting) {
18548            final PackageSetting ps = (PackageSetting) obj;
18549            if (ps.pkg != null) {
18550                return ps.pkg.applicationInfo.targetSdkVersion;
18551            }
18552        }
18553        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18554    }
18555
18556    @Override
18557    public void addPreferredActivity(IntentFilter filter, int match,
18558            ComponentName[] set, ComponentName activity, int userId) {
18559        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18560                "Adding preferred");
18561    }
18562
18563    private void addPreferredActivityInternal(IntentFilter filter, int match,
18564            ComponentName[] set, ComponentName activity, boolean always, int userId,
18565            String opname) {
18566        // writer
18567        int callingUid = Binder.getCallingUid();
18568        enforceCrossUserPermission(callingUid, userId,
18569                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18570        if (filter.countActions() == 0) {
18571            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18572            return;
18573        }
18574        synchronized (mPackages) {
18575            if (mContext.checkCallingOrSelfPermission(
18576                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18577                    != PackageManager.PERMISSION_GRANTED) {
18578                if (getUidTargetSdkVersionLockedLPr(callingUid)
18579                        < Build.VERSION_CODES.FROYO) {
18580                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18581                            + callingUid);
18582                    return;
18583                }
18584                mContext.enforceCallingOrSelfPermission(
18585                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18586            }
18587
18588            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18589            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18590                    + userId + ":");
18591            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18592            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18593            scheduleWritePackageRestrictionsLocked(userId);
18594            postPreferredActivityChangedBroadcast(userId);
18595        }
18596    }
18597
18598    private void postPreferredActivityChangedBroadcast(int userId) {
18599        mHandler.post(() -> {
18600            final IActivityManager am = ActivityManager.getService();
18601            if (am == null) {
18602                return;
18603            }
18604
18605            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18606            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18607            try {
18608                am.broadcastIntent(null, intent, null, null,
18609                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18610                        null, false, false, userId);
18611            } catch (RemoteException e) {
18612            }
18613        });
18614    }
18615
18616    @Override
18617    public void replacePreferredActivity(IntentFilter filter, int match,
18618            ComponentName[] set, ComponentName activity, int userId) {
18619        if (filter.countActions() != 1) {
18620            throw new IllegalArgumentException(
18621                    "replacePreferredActivity expects filter to have only 1 action.");
18622        }
18623        if (filter.countDataAuthorities() != 0
18624                || filter.countDataPaths() != 0
18625                || filter.countDataSchemes() > 1
18626                || filter.countDataTypes() != 0) {
18627            throw new IllegalArgumentException(
18628                    "replacePreferredActivity expects filter to have no data authorities, " +
18629                    "paths, or types; and at most one scheme.");
18630        }
18631
18632        final int callingUid = Binder.getCallingUid();
18633        enforceCrossUserPermission(callingUid, userId,
18634                true /* requireFullPermission */, false /* checkShell */,
18635                "replace preferred activity");
18636        synchronized (mPackages) {
18637            if (mContext.checkCallingOrSelfPermission(
18638                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18639                    != PackageManager.PERMISSION_GRANTED) {
18640                if (getUidTargetSdkVersionLockedLPr(callingUid)
18641                        < Build.VERSION_CODES.FROYO) {
18642                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18643                            + Binder.getCallingUid());
18644                    return;
18645                }
18646                mContext.enforceCallingOrSelfPermission(
18647                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18648            }
18649
18650            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18651            if (pir != null) {
18652                // Get all of the existing entries that exactly match this filter.
18653                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18654                if (existing != null && existing.size() == 1) {
18655                    PreferredActivity cur = existing.get(0);
18656                    if (DEBUG_PREFERRED) {
18657                        Slog.i(TAG, "Checking replace of preferred:");
18658                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18659                        if (!cur.mPref.mAlways) {
18660                            Slog.i(TAG, "  -- CUR; not mAlways!");
18661                        } else {
18662                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18663                            Slog.i(TAG, "  -- CUR: mSet="
18664                                    + Arrays.toString(cur.mPref.mSetComponents));
18665                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18666                            Slog.i(TAG, "  -- NEW: mMatch="
18667                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18668                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18669                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18670                        }
18671                    }
18672                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18673                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18674                            && cur.mPref.sameSet(set)) {
18675                        // Setting the preferred activity to what it happens to be already
18676                        if (DEBUG_PREFERRED) {
18677                            Slog.i(TAG, "Replacing with same preferred activity "
18678                                    + cur.mPref.mShortComponent + " for user "
18679                                    + userId + ":");
18680                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18681                        }
18682                        return;
18683                    }
18684                }
18685
18686                if (existing != null) {
18687                    if (DEBUG_PREFERRED) {
18688                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18689                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18690                    }
18691                    for (int i = 0; i < existing.size(); i++) {
18692                        PreferredActivity pa = existing.get(i);
18693                        if (DEBUG_PREFERRED) {
18694                            Slog.i(TAG, "Removing existing preferred activity "
18695                                    + pa.mPref.mComponent + ":");
18696                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18697                        }
18698                        pir.removeFilter(pa);
18699                    }
18700                }
18701            }
18702            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18703                    "Replacing preferred");
18704        }
18705    }
18706
18707    @Override
18708    public void clearPackagePreferredActivities(String packageName) {
18709        final int uid = Binder.getCallingUid();
18710        // writer
18711        synchronized (mPackages) {
18712            PackageParser.Package pkg = mPackages.get(packageName);
18713            if (pkg == null || pkg.applicationInfo.uid != uid) {
18714                if (mContext.checkCallingOrSelfPermission(
18715                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18716                        != PackageManager.PERMISSION_GRANTED) {
18717                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18718                            < Build.VERSION_CODES.FROYO) {
18719                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18720                                + Binder.getCallingUid());
18721                        return;
18722                    }
18723                    mContext.enforceCallingOrSelfPermission(
18724                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18725                }
18726            }
18727
18728            int user = UserHandle.getCallingUserId();
18729            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18730                scheduleWritePackageRestrictionsLocked(user);
18731            }
18732        }
18733    }
18734
18735    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18736    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18737        ArrayList<PreferredActivity> removed = null;
18738        boolean changed = false;
18739        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18740            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18741            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18742            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18743                continue;
18744            }
18745            Iterator<PreferredActivity> it = pir.filterIterator();
18746            while (it.hasNext()) {
18747                PreferredActivity pa = it.next();
18748                // Mark entry for removal only if it matches the package name
18749                // and the entry is of type "always".
18750                if (packageName == null ||
18751                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18752                                && pa.mPref.mAlways)) {
18753                    if (removed == null) {
18754                        removed = new ArrayList<PreferredActivity>();
18755                    }
18756                    removed.add(pa);
18757                }
18758            }
18759            if (removed != null) {
18760                for (int j=0; j<removed.size(); j++) {
18761                    PreferredActivity pa = removed.get(j);
18762                    pir.removeFilter(pa);
18763                }
18764                changed = true;
18765            }
18766        }
18767        if (changed) {
18768            postPreferredActivityChangedBroadcast(userId);
18769        }
18770        return changed;
18771    }
18772
18773    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18774    private void clearIntentFilterVerificationsLPw(int userId) {
18775        final int packageCount = mPackages.size();
18776        for (int i = 0; i < packageCount; i++) {
18777            PackageParser.Package pkg = mPackages.valueAt(i);
18778            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18779        }
18780    }
18781
18782    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18783    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18784        if (userId == UserHandle.USER_ALL) {
18785            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18786                    sUserManager.getUserIds())) {
18787                for (int oneUserId : sUserManager.getUserIds()) {
18788                    scheduleWritePackageRestrictionsLocked(oneUserId);
18789                }
18790            }
18791        } else {
18792            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18793                scheduleWritePackageRestrictionsLocked(userId);
18794            }
18795        }
18796    }
18797
18798    void clearDefaultBrowserIfNeeded(String packageName) {
18799        for (int oneUserId : sUserManager.getUserIds()) {
18800            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18801            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18802            if (packageName.equals(defaultBrowserPackageName)) {
18803                setDefaultBrowserPackageName(null, oneUserId);
18804            }
18805        }
18806    }
18807
18808    @Override
18809    public void resetApplicationPreferences(int userId) {
18810        mContext.enforceCallingOrSelfPermission(
18811                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18812        final long identity = Binder.clearCallingIdentity();
18813        // writer
18814        try {
18815            synchronized (mPackages) {
18816                clearPackagePreferredActivitiesLPw(null, userId);
18817                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18818                // TODO: We have to reset the default SMS and Phone. This requires
18819                // significant refactoring to keep all default apps in the package
18820                // manager (cleaner but more work) or have the services provide
18821                // callbacks to the package manager to request a default app reset.
18822                applyFactoryDefaultBrowserLPw(userId);
18823                clearIntentFilterVerificationsLPw(userId);
18824                primeDomainVerificationsLPw(userId);
18825                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18826                scheduleWritePackageRestrictionsLocked(userId);
18827            }
18828            resetNetworkPolicies(userId);
18829        } finally {
18830            Binder.restoreCallingIdentity(identity);
18831        }
18832    }
18833
18834    @Override
18835    public int getPreferredActivities(List<IntentFilter> outFilters,
18836            List<ComponentName> outActivities, String packageName) {
18837
18838        int num = 0;
18839        final int userId = UserHandle.getCallingUserId();
18840        // reader
18841        synchronized (mPackages) {
18842            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18843            if (pir != null) {
18844                final Iterator<PreferredActivity> it = pir.filterIterator();
18845                while (it.hasNext()) {
18846                    final PreferredActivity pa = it.next();
18847                    if (packageName == null
18848                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18849                                    && pa.mPref.mAlways)) {
18850                        if (outFilters != null) {
18851                            outFilters.add(new IntentFilter(pa));
18852                        }
18853                        if (outActivities != null) {
18854                            outActivities.add(pa.mPref.mComponent);
18855                        }
18856                    }
18857                }
18858            }
18859        }
18860
18861        return num;
18862    }
18863
18864    @Override
18865    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18866            int userId) {
18867        int callingUid = Binder.getCallingUid();
18868        if (callingUid != Process.SYSTEM_UID) {
18869            throw new SecurityException(
18870                    "addPersistentPreferredActivity can only be run by the system");
18871        }
18872        if (filter.countActions() == 0) {
18873            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18874            return;
18875        }
18876        synchronized (mPackages) {
18877            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18878                    ":");
18879            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18880            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18881                    new PersistentPreferredActivity(filter, activity));
18882            scheduleWritePackageRestrictionsLocked(userId);
18883            postPreferredActivityChangedBroadcast(userId);
18884        }
18885    }
18886
18887    @Override
18888    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18889        int callingUid = Binder.getCallingUid();
18890        if (callingUid != Process.SYSTEM_UID) {
18891            throw new SecurityException(
18892                    "clearPackagePersistentPreferredActivities can only be run by the system");
18893        }
18894        ArrayList<PersistentPreferredActivity> removed = null;
18895        boolean changed = false;
18896        synchronized (mPackages) {
18897            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18898                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18899                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18900                        .valueAt(i);
18901                if (userId != thisUserId) {
18902                    continue;
18903                }
18904                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18905                while (it.hasNext()) {
18906                    PersistentPreferredActivity ppa = it.next();
18907                    // Mark entry for removal only if it matches the package name.
18908                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18909                        if (removed == null) {
18910                            removed = new ArrayList<PersistentPreferredActivity>();
18911                        }
18912                        removed.add(ppa);
18913                    }
18914                }
18915                if (removed != null) {
18916                    for (int j=0; j<removed.size(); j++) {
18917                        PersistentPreferredActivity ppa = removed.get(j);
18918                        ppir.removeFilter(ppa);
18919                    }
18920                    changed = true;
18921                }
18922            }
18923
18924            if (changed) {
18925                scheduleWritePackageRestrictionsLocked(userId);
18926                postPreferredActivityChangedBroadcast(userId);
18927            }
18928        }
18929    }
18930
18931    /**
18932     * Common machinery for picking apart a restored XML blob and passing
18933     * it to a caller-supplied functor to be applied to the running system.
18934     */
18935    private void restoreFromXml(XmlPullParser parser, int userId,
18936            String expectedStartTag, BlobXmlRestorer functor)
18937            throws IOException, XmlPullParserException {
18938        int type;
18939        while ((type = parser.next()) != XmlPullParser.START_TAG
18940                && type != XmlPullParser.END_DOCUMENT) {
18941        }
18942        if (type != XmlPullParser.START_TAG) {
18943            // oops didn't find a start tag?!
18944            if (DEBUG_BACKUP) {
18945                Slog.e(TAG, "Didn't find start tag during restore");
18946            }
18947            return;
18948        }
18949Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18950        // this is supposed to be TAG_PREFERRED_BACKUP
18951        if (!expectedStartTag.equals(parser.getName())) {
18952            if (DEBUG_BACKUP) {
18953                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18954            }
18955            return;
18956        }
18957
18958        // skip interfering stuff, then we're aligned with the backing implementation
18959        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18960Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18961        functor.apply(parser, userId);
18962    }
18963
18964    private interface BlobXmlRestorer {
18965        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18966    }
18967
18968    /**
18969     * Non-Binder method, support for the backup/restore mechanism: write the
18970     * full set of preferred activities in its canonical XML format.  Returns the
18971     * XML output as a byte array, or null if there is none.
18972     */
18973    @Override
18974    public byte[] getPreferredActivityBackup(int userId) {
18975        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18976            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18977        }
18978
18979        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18980        try {
18981            final XmlSerializer serializer = new FastXmlSerializer();
18982            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18983            serializer.startDocument(null, true);
18984            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18985
18986            synchronized (mPackages) {
18987                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18988            }
18989
18990            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18991            serializer.endDocument();
18992            serializer.flush();
18993        } catch (Exception e) {
18994            if (DEBUG_BACKUP) {
18995                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18996            }
18997            return null;
18998        }
18999
19000        return dataStream.toByteArray();
19001    }
19002
19003    @Override
19004    public void restorePreferredActivities(byte[] backup, int userId) {
19005        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19006            throw new SecurityException("Only the system may call restorePreferredActivities()");
19007        }
19008
19009        try {
19010            final XmlPullParser parser = Xml.newPullParser();
19011            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19012            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19013                    new BlobXmlRestorer() {
19014                        @Override
19015                        public void apply(XmlPullParser parser, int userId)
19016                                throws XmlPullParserException, IOException {
19017                            synchronized (mPackages) {
19018                                mSettings.readPreferredActivitiesLPw(parser, userId);
19019                            }
19020                        }
19021                    } );
19022        } catch (Exception e) {
19023            if (DEBUG_BACKUP) {
19024                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19025            }
19026        }
19027    }
19028
19029    /**
19030     * Non-Binder method, support for the backup/restore mechanism: write the
19031     * default browser (etc) settings in its canonical XML format.  Returns the default
19032     * browser XML representation as a byte array, or null if there is none.
19033     */
19034    @Override
19035    public byte[] getDefaultAppsBackup(int userId) {
19036        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19037            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19038        }
19039
19040        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19041        try {
19042            final XmlSerializer serializer = new FastXmlSerializer();
19043            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19044            serializer.startDocument(null, true);
19045            serializer.startTag(null, TAG_DEFAULT_APPS);
19046
19047            synchronized (mPackages) {
19048                mSettings.writeDefaultAppsLPr(serializer, userId);
19049            }
19050
19051            serializer.endTag(null, TAG_DEFAULT_APPS);
19052            serializer.endDocument();
19053            serializer.flush();
19054        } catch (Exception e) {
19055            if (DEBUG_BACKUP) {
19056                Slog.e(TAG, "Unable to write default apps for backup", e);
19057            }
19058            return null;
19059        }
19060
19061        return dataStream.toByteArray();
19062    }
19063
19064    @Override
19065    public void restoreDefaultApps(byte[] backup, int userId) {
19066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19067            throw new SecurityException("Only the system may call restoreDefaultApps()");
19068        }
19069
19070        try {
19071            final XmlPullParser parser = Xml.newPullParser();
19072            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19073            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19074                    new BlobXmlRestorer() {
19075                        @Override
19076                        public void apply(XmlPullParser parser, int userId)
19077                                throws XmlPullParserException, IOException {
19078                            synchronized (mPackages) {
19079                                mSettings.readDefaultAppsLPw(parser, userId);
19080                            }
19081                        }
19082                    } );
19083        } catch (Exception e) {
19084            if (DEBUG_BACKUP) {
19085                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19086            }
19087        }
19088    }
19089
19090    @Override
19091    public byte[] getIntentFilterVerificationBackup(int userId) {
19092        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19093            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19094        }
19095
19096        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19097        try {
19098            final XmlSerializer serializer = new FastXmlSerializer();
19099            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19100            serializer.startDocument(null, true);
19101            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19102
19103            synchronized (mPackages) {
19104                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19105            }
19106
19107            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19108            serializer.endDocument();
19109            serializer.flush();
19110        } catch (Exception e) {
19111            if (DEBUG_BACKUP) {
19112                Slog.e(TAG, "Unable to write default apps for backup", e);
19113            }
19114            return null;
19115        }
19116
19117        return dataStream.toByteArray();
19118    }
19119
19120    @Override
19121    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19122        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19123            throw new SecurityException("Only the system may call restorePreferredActivities()");
19124        }
19125
19126        try {
19127            final XmlPullParser parser = Xml.newPullParser();
19128            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19129            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19130                    new BlobXmlRestorer() {
19131                        @Override
19132                        public void apply(XmlPullParser parser, int userId)
19133                                throws XmlPullParserException, IOException {
19134                            synchronized (mPackages) {
19135                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19136                                mSettings.writeLPr();
19137                            }
19138                        }
19139                    } );
19140        } catch (Exception e) {
19141            if (DEBUG_BACKUP) {
19142                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19143            }
19144        }
19145    }
19146
19147    @Override
19148    public byte[] getPermissionGrantBackup(int userId) {
19149        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19150            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19151        }
19152
19153        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19154        try {
19155            final XmlSerializer serializer = new FastXmlSerializer();
19156            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19157            serializer.startDocument(null, true);
19158            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19159
19160            synchronized (mPackages) {
19161                serializeRuntimePermissionGrantsLPr(serializer, userId);
19162            }
19163
19164            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19165            serializer.endDocument();
19166            serializer.flush();
19167        } catch (Exception e) {
19168            if (DEBUG_BACKUP) {
19169                Slog.e(TAG, "Unable to write default apps for backup", e);
19170            }
19171            return null;
19172        }
19173
19174        return dataStream.toByteArray();
19175    }
19176
19177    @Override
19178    public void restorePermissionGrants(byte[] backup, int userId) {
19179        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19180            throw new SecurityException("Only the system may call restorePermissionGrants()");
19181        }
19182
19183        try {
19184            final XmlPullParser parser = Xml.newPullParser();
19185            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19186            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19187                    new BlobXmlRestorer() {
19188                        @Override
19189                        public void apply(XmlPullParser parser, int userId)
19190                                throws XmlPullParserException, IOException {
19191                            synchronized (mPackages) {
19192                                processRestoredPermissionGrantsLPr(parser, userId);
19193                            }
19194                        }
19195                    } );
19196        } catch (Exception e) {
19197            if (DEBUG_BACKUP) {
19198                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19199            }
19200        }
19201    }
19202
19203    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19204            throws IOException {
19205        serializer.startTag(null, TAG_ALL_GRANTS);
19206
19207        final int N = mSettings.mPackages.size();
19208        for (int i = 0; i < N; i++) {
19209            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19210            boolean pkgGrantsKnown = false;
19211
19212            PermissionsState packagePerms = ps.getPermissionsState();
19213
19214            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19215                final int grantFlags = state.getFlags();
19216                // only look at grants that are not system/policy fixed
19217                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19218                    final boolean isGranted = state.isGranted();
19219                    // And only back up the user-twiddled state bits
19220                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19221                        final String packageName = mSettings.mPackages.keyAt(i);
19222                        if (!pkgGrantsKnown) {
19223                            serializer.startTag(null, TAG_GRANT);
19224                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19225                            pkgGrantsKnown = true;
19226                        }
19227
19228                        final boolean userSet =
19229                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19230                        final boolean userFixed =
19231                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19232                        final boolean revoke =
19233                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19234
19235                        serializer.startTag(null, TAG_PERMISSION);
19236                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19237                        if (isGranted) {
19238                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19239                        }
19240                        if (userSet) {
19241                            serializer.attribute(null, ATTR_USER_SET, "true");
19242                        }
19243                        if (userFixed) {
19244                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19245                        }
19246                        if (revoke) {
19247                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19248                        }
19249                        serializer.endTag(null, TAG_PERMISSION);
19250                    }
19251                }
19252            }
19253
19254            if (pkgGrantsKnown) {
19255                serializer.endTag(null, TAG_GRANT);
19256            }
19257        }
19258
19259        serializer.endTag(null, TAG_ALL_GRANTS);
19260    }
19261
19262    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19263            throws XmlPullParserException, IOException {
19264        String pkgName = null;
19265        int outerDepth = parser.getDepth();
19266        int type;
19267        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19268                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19269            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19270                continue;
19271            }
19272
19273            final String tagName = parser.getName();
19274            if (tagName.equals(TAG_GRANT)) {
19275                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19276                if (DEBUG_BACKUP) {
19277                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19278                }
19279            } else if (tagName.equals(TAG_PERMISSION)) {
19280
19281                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19282                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19283
19284                int newFlagSet = 0;
19285                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19286                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19287                }
19288                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19289                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19290                }
19291                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19292                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19293                }
19294                if (DEBUG_BACKUP) {
19295                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19296                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19297                }
19298                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19299                if (ps != null) {
19300                    // Already installed so we apply the grant immediately
19301                    if (DEBUG_BACKUP) {
19302                        Slog.v(TAG, "        + already installed; applying");
19303                    }
19304                    PermissionsState perms = ps.getPermissionsState();
19305                    BasePermission bp = mSettings.mPermissions.get(permName);
19306                    if (bp != null) {
19307                        if (isGranted) {
19308                            perms.grantRuntimePermission(bp, userId);
19309                        }
19310                        if (newFlagSet != 0) {
19311                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19312                        }
19313                    }
19314                } else {
19315                    // Need to wait for post-restore install to apply the grant
19316                    if (DEBUG_BACKUP) {
19317                        Slog.v(TAG, "        - not yet installed; saving for later");
19318                    }
19319                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19320                            isGranted, newFlagSet, userId);
19321                }
19322            } else {
19323                PackageManagerService.reportSettingsProblem(Log.WARN,
19324                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19325                XmlUtils.skipCurrentTag(parser);
19326            }
19327        }
19328
19329        scheduleWriteSettingsLocked();
19330        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19331    }
19332
19333    @Override
19334    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19335            int sourceUserId, int targetUserId, int flags) {
19336        mContext.enforceCallingOrSelfPermission(
19337                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19338        int callingUid = Binder.getCallingUid();
19339        enforceOwnerRights(ownerPackage, callingUid);
19340        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19341        if (intentFilter.countActions() == 0) {
19342            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19343            return;
19344        }
19345        synchronized (mPackages) {
19346            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19347                    ownerPackage, targetUserId, flags);
19348            CrossProfileIntentResolver resolver =
19349                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19350            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19351            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19352            if (existing != null) {
19353                int size = existing.size();
19354                for (int i = 0; i < size; i++) {
19355                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19356                        return;
19357                    }
19358                }
19359            }
19360            resolver.addFilter(newFilter);
19361            scheduleWritePackageRestrictionsLocked(sourceUserId);
19362        }
19363    }
19364
19365    @Override
19366    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19367        mContext.enforceCallingOrSelfPermission(
19368                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19369        int callingUid = Binder.getCallingUid();
19370        enforceOwnerRights(ownerPackage, callingUid);
19371        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19372        synchronized (mPackages) {
19373            CrossProfileIntentResolver resolver =
19374                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19375            ArraySet<CrossProfileIntentFilter> set =
19376                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19377            for (CrossProfileIntentFilter filter : set) {
19378                if (filter.getOwnerPackage().equals(ownerPackage)) {
19379                    resolver.removeFilter(filter);
19380                }
19381            }
19382            scheduleWritePackageRestrictionsLocked(sourceUserId);
19383        }
19384    }
19385
19386    // Enforcing that callingUid is owning pkg on userId
19387    private void enforceOwnerRights(String pkg, int callingUid) {
19388        // The system owns everything.
19389        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19390            return;
19391        }
19392        int callingUserId = UserHandle.getUserId(callingUid);
19393        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19394        if (pi == null) {
19395            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19396                    + callingUserId);
19397        }
19398        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19399            throw new SecurityException("Calling uid " + callingUid
19400                    + " does not own package " + pkg);
19401        }
19402    }
19403
19404    @Override
19405    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19406        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19407    }
19408
19409    private Intent getHomeIntent() {
19410        Intent intent = new Intent(Intent.ACTION_MAIN);
19411        intent.addCategory(Intent.CATEGORY_HOME);
19412        intent.addCategory(Intent.CATEGORY_DEFAULT);
19413        return intent;
19414    }
19415
19416    private IntentFilter getHomeFilter() {
19417        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19418        filter.addCategory(Intent.CATEGORY_HOME);
19419        filter.addCategory(Intent.CATEGORY_DEFAULT);
19420        return filter;
19421    }
19422
19423    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19424            int userId) {
19425        Intent intent  = getHomeIntent();
19426        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19427                PackageManager.GET_META_DATA, userId);
19428        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19429                true, false, false, userId);
19430
19431        allHomeCandidates.clear();
19432        if (list != null) {
19433            for (ResolveInfo ri : list) {
19434                allHomeCandidates.add(ri);
19435            }
19436        }
19437        return (preferred == null || preferred.activityInfo == null)
19438                ? null
19439                : new ComponentName(preferred.activityInfo.packageName,
19440                        preferred.activityInfo.name);
19441    }
19442
19443    @Override
19444    public void setHomeActivity(ComponentName comp, int userId) {
19445        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19446        getHomeActivitiesAsUser(homeActivities, userId);
19447
19448        boolean found = false;
19449
19450        final int size = homeActivities.size();
19451        final ComponentName[] set = new ComponentName[size];
19452        for (int i = 0; i < size; i++) {
19453            final ResolveInfo candidate = homeActivities.get(i);
19454            final ActivityInfo info = candidate.activityInfo;
19455            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19456            set[i] = activityName;
19457            if (!found && activityName.equals(comp)) {
19458                found = true;
19459            }
19460        }
19461        if (!found) {
19462            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19463                    + userId);
19464        }
19465        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19466                set, comp, userId);
19467    }
19468
19469    private @Nullable String getSetupWizardPackageName() {
19470        final Intent intent = new Intent(Intent.ACTION_MAIN);
19471        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19472
19473        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19474                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19475                        | MATCH_DISABLED_COMPONENTS,
19476                UserHandle.myUserId());
19477        if (matches.size() == 1) {
19478            return matches.get(0).getComponentInfo().packageName;
19479        } else {
19480            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19481                    + ": matches=" + matches);
19482            return null;
19483        }
19484    }
19485
19486    private @Nullable String getStorageManagerPackageName() {
19487        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19488
19489        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19490                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19491                        | MATCH_DISABLED_COMPONENTS,
19492                UserHandle.myUserId());
19493        if (matches.size() == 1) {
19494            return matches.get(0).getComponentInfo().packageName;
19495        } else {
19496            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19497                    + matches.size() + ": matches=" + matches);
19498            return null;
19499        }
19500    }
19501
19502    @Override
19503    public void setApplicationEnabledSetting(String appPackageName,
19504            int newState, int flags, int userId, String callingPackage) {
19505        if (!sUserManager.exists(userId)) return;
19506        if (callingPackage == null) {
19507            callingPackage = Integer.toString(Binder.getCallingUid());
19508        }
19509        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19510    }
19511
19512    @Override
19513    public void setComponentEnabledSetting(ComponentName componentName,
19514            int newState, int flags, int userId) {
19515        if (!sUserManager.exists(userId)) return;
19516        setEnabledSetting(componentName.getPackageName(),
19517                componentName.getClassName(), newState, flags, userId, null);
19518    }
19519
19520    private void setEnabledSetting(final String packageName, String className, int newState,
19521            final int flags, int userId, String callingPackage) {
19522        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19523              || newState == COMPONENT_ENABLED_STATE_ENABLED
19524              || newState == COMPONENT_ENABLED_STATE_DISABLED
19525              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19526              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19527            throw new IllegalArgumentException("Invalid new component state: "
19528                    + newState);
19529        }
19530        PackageSetting pkgSetting;
19531        final int uid = Binder.getCallingUid();
19532        final int permission;
19533        if (uid == Process.SYSTEM_UID) {
19534            permission = PackageManager.PERMISSION_GRANTED;
19535        } else {
19536            permission = mContext.checkCallingOrSelfPermission(
19537                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19538        }
19539        enforceCrossUserPermission(uid, userId,
19540                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19541        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19542        boolean sendNow = false;
19543        boolean isApp = (className == null);
19544        String componentName = isApp ? packageName : className;
19545        int packageUid = -1;
19546        ArrayList<String> components;
19547
19548        // writer
19549        synchronized (mPackages) {
19550            pkgSetting = mSettings.mPackages.get(packageName);
19551            if (pkgSetting == null) {
19552                if (className == null) {
19553                    throw new IllegalArgumentException("Unknown package: " + packageName);
19554                }
19555                throw new IllegalArgumentException(
19556                        "Unknown component: " + packageName + "/" + className);
19557            }
19558        }
19559
19560        // Limit who can change which apps
19561        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19562            // Don't allow apps that don't have permission to modify other apps
19563            if (!allowedByPermission) {
19564                throw new SecurityException(
19565                        "Permission Denial: attempt to change component state from pid="
19566                        + Binder.getCallingPid()
19567                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19568            }
19569            // Don't allow changing protected packages.
19570            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19571                throw new SecurityException("Cannot disable a protected package: " + packageName);
19572            }
19573        }
19574
19575        synchronized (mPackages) {
19576            if (uid == Process.SHELL_UID
19577                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19578                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19579                // unless it is a test package.
19580                int oldState = pkgSetting.getEnabled(userId);
19581                if (className == null
19582                    &&
19583                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19584                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19585                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19586                    &&
19587                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19588                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19589                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19590                    // ok
19591                } else {
19592                    throw new SecurityException(
19593                            "Shell cannot change component state for " + packageName + "/"
19594                            + className + " to " + newState);
19595                }
19596            }
19597            if (className == null) {
19598                // We're dealing with an application/package level state change
19599                if (pkgSetting.getEnabled(userId) == newState) {
19600                    // Nothing to do
19601                    return;
19602                }
19603                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19604                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19605                    // Don't care about who enables an app.
19606                    callingPackage = null;
19607                }
19608                pkgSetting.setEnabled(newState, userId, callingPackage);
19609                // pkgSetting.pkg.mSetEnabled = newState;
19610            } else {
19611                // We're dealing with a component level state change
19612                // First, verify that this is a valid class name.
19613                PackageParser.Package pkg = pkgSetting.pkg;
19614                if (pkg == null || !pkg.hasComponentClassName(className)) {
19615                    if (pkg != null &&
19616                            pkg.applicationInfo.targetSdkVersion >=
19617                                    Build.VERSION_CODES.JELLY_BEAN) {
19618                        throw new IllegalArgumentException("Component class " + className
19619                                + " does not exist in " + packageName);
19620                    } else {
19621                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19622                                + className + " does not exist in " + packageName);
19623                    }
19624                }
19625                switch (newState) {
19626                case COMPONENT_ENABLED_STATE_ENABLED:
19627                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19628                        return;
19629                    }
19630                    break;
19631                case COMPONENT_ENABLED_STATE_DISABLED:
19632                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19633                        return;
19634                    }
19635                    break;
19636                case COMPONENT_ENABLED_STATE_DEFAULT:
19637                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19638                        return;
19639                    }
19640                    break;
19641                default:
19642                    Slog.e(TAG, "Invalid new component state: " + newState);
19643                    return;
19644                }
19645            }
19646            scheduleWritePackageRestrictionsLocked(userId);
19647            components = mPendingBroadcasts.get(userId, packageName);
19648            final boolean newPackage = components == null;
19649            if (newPackage) {
19650                components = new ArrayList<String>();
19651            }
19652            if (!components.contains(componentName)) {
19653                components.add(componentName);
19654            }
19655            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19656                sendNow = true;
19657                // Purge entry from pending broadcast list if another one exists already
19658                // since we are sending one right away.
19659                mPendingBroadcasts.remove(userId, packageName);
19660            } else {
19661                if (newPackage) {
19662                    mPendingBroadcasts.put(userId, packageName, components);
19663                }
19664                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19665                    // Schedule a message
19666                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19667                }
19668            }
19669        }
19670
19671        long callingId = Binder.clearCallingIdentity();
19672        try {
19673            if (sendNow) {
19674                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19675                sendPackageChangedBroadcast(packageName,
19676                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19677            }
19678        } finally {
19679            Binder.restoreCallingIdentity(callingId);
19680        }
19681    }
19682
19683    @Override
19684    public void flushPackageRestrictionsAsUser(int userId) {
19685        if (!sUserManager.exists(userId)) {
19686            return;
19687        }
19688        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19689                false /* checkShell */, "flushPackageRestrictions");
19690        synchronized (mPackages) {
19691            mSettings.writePackageRestrictionsLPr(userId);
19692            mDirtyUsers.remove(userId);
19693            if (mDirtyUsers.isEmpty()) {
19694                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19695            }
19696        }
19697    }
19698
19699    private void sendPackageChangedBroadcast(String packageName,
19700            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19701        if (DEBUG_INSTALL)
19702            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19703                    + componentNames);
19704        Bundle extras = new Bundle(4);
19705        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19706        String nameList[] = new String[componentNames.size()];
19707        componentNames.toArray(nameList);
19708        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19709        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19710        extras.putInt(Intent.EXTRA_UID, packageUid);
19711        // If this is not reporting a change of the overall package, then only send it
19712        // to registered receivers.  We don't want to launch a swath of apps for every
19713        // little component state change.
19714        final int flags = !componentNames.contains(packageName)
19715                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19716        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19717                new int[] {UserHandle.getUserId(packageUid)});
19718    }
19719
19720    @Override
19721    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19722        if (!sUserManager.exists(userId)) return;
19723        final int uid = Binder.getCallingUid();
19724        final int permission = mContext.checkCallingOrSelfPermission(
19725                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19726        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19727        enforceCrossUserPermission(uid, userId,
19728                true /* requireFullPermission */, true /* checkShell */, "stop package");
19729        // writer
19730        synchronized (mPackages) {
19731            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19732                    allowedByPermission, uid, userId)) {
19733                scheduleWritePackageRestrictionsLocked(userId);
19734            }
19735        }
19736    }
19737
19738    @Override
19739    public String getInstallerPackageName(String packageName) {
19740        // reader
19741        synchronized (mPackages) {
19742            return mSettings.getInstallerPackageNameLPr(packageName);
19743        }
19744    }
19745
19746    public boolean isOrphaned(String packageName) {
19747        // reader
19748        synchronized (mPackages) {
19749            return mSettings.isOrphaned(packageName);
19750        }
19751    }
19752
19753    @Override
19754    public int getApplicationEnabledSetting(String packageName, int userId) {
19755        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19756        int uid = Binder.getCallingUid();
19757        enforceCrossUserPermission(uid, userId,
19758                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19759        // reader
19760        synchronized (mPackages) {
19761            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19762        }
19763    }
19764
19765    @Override
19766    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19767        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19768        int uid = Binder.getCallingUid();
19769        enforceCrossUserPermission(uid, userId,
19770                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19771        // reader
19772        synchronized (mPackages) {
19773            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19774        }
19775    }
19776
19777    @Override
19778    public void enterSafeMode() {
19779        enforceSystemOrRoot("Only the system can request entering safe mode");
19780
19781        if (!mSystemReady) {
19782            mSafeMode = true;
19783        }
19784    }
19785
19786    @Override
19787    public void systemReady() {
19788        mSystemReady = true;
19789
19790        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19791        // disabled after already being started.
19792        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19793                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19794
19795        // Read the compatibilty setting when the system is ready.
19796        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19797                mContext.getContentResolver(),
19798                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19799        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19800        if (DEBUG_SETTINGS) {
19801            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19802        }
19803
19804        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19805
19806        synchronized (mPackages) {
19807            // Verify that all of the preferred activity components actually
19808            // exist.  It is possible for applications to be updated and at
19809            // that point remove a previously declared activity component that
19810            // had been set as a preferred activity.  We try to clean this up
19811            // the next time we encounter that preferred activity, but it is
19812            // possible for the user flow to never be able to return to that
19813            // situation so here we do a sanity check to make sure we haven't
19814            // left any junk around.
19815            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19816            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19817                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19818                removed.clear();
19819                for (PreferredActivity pa : pir.filterSet()) {
19820                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19821                        removed.add(pa);
19822                    }
19823                }
19824                if (removed.size() > 0) {
19825                    for (int r=0; r<removed.size(); r++) {
19826                        PreferredActivity pa = removed.get(r);
19827                        Slog.w(TAG, "Removing dangling preferred activity: "
19828                                + pa.mPref.mComponent);
19829                        pir.removeFilter(pa);
19830                    }
19831                    mSettings.writePackageRestrictionsLPr(
19832                            mSettings.mPreferredActivities.keyAt(i));
19833                }
19834            }
19835
19836            for (int userId : UserManagerService.getInstance().getUserIds()) {
19837                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19838                    grantPermissionsUserIds = ArrayUtils.appendInt(
19839                            grantPermissionsUserIds, userId);
19840                }
19841            }
19842        }
19843        sUserManager.systemReady();
19844
19845        // If we upgraded grant all default permissions before kicking off.
19846        for (int userId : grantPermissionsUserIds) {
19847            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19848        }
19849
19850        // If we did not grant default permissions, we preload from this the
19851        // default permission exceptions lazily to ensure we don't hit the
19852        // disk on a new user creation.
19853        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19854            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19855        }
19856
19857        // Kick off any messages waiting for system ready
19858        if (mPostSystemReadyMessages != null) {
19859            for (Message msg : mPostSystemReadyMessages) {
19860                msg.sendToTarget();
19861            }
19862            mPostSystemReadyMessages = null;
19863        }
19864
19865        // Watch for external volumes that come and go over time
19866        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19867        storage.registerListener(mStorageListener);
19868
19869        mInstallerService.systemReady();
19870        mPackageDexOptimizer.systemReady();
19871
19872        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19873                StorageManagerInternal.class);
19874        StorageManagerInternal.addExternalStoragePolicy(
19875                new StorageManagerInternal.ExternalStorageMountPolicy() {
19876            @Override
19877            public int getMountMode(int uid, String packageName) {
19878                if (Process.isIsolated(uid)) {
19879                    return Zygote.MOUNT_EXTERNAL_NONE;
19880                }
19881                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19882                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19883                }
19884                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19885                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19886                }
19887                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19888                    return Zygote.MOUNT_EXTERNAL_READ;
19889                }
19890                return Zygote.MOUNT_EXTERNAL_WRITE;
19891            }
19892
19893            @Override
19894            public boolean hasExternalStorage(int uid, String packageName) {
19895                return true;
19896            }
19897        });
19898
19899        // Now that we're mostly running, clean up stale users and apps
19900        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19901        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19902    }
19903
19904    @Override
19905    public boolean isSafeMode() {
19906        return mSafeMode;
19907    }
19908
19909    @Override
19910    public boolean hasSystemUidErrors() {
19911        return mHasSystemUidErrors;
19912    }
19913
19914    static String arrayToString(int[] array) {
19915        StringBuffer buf = new StringBuffer(128);
19916        buf.append('[');
19917        if (array != null) {
19918            for (int i=0; i<array.length; i++) {
19919                if (i > 0) buf.append(", ");
19920                buf.append(array[i]);
19921            }
19922        }
19923        buf.append(']');
19924        return buf.toString();
19925    }
19926
19927    static class DumpState {
19928        public static final int DUMP_LIBS = 1 << 0;
19929        public static final int DUMP_FEATURES = 1 << 1;
19930        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19931        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19932        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19933        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19934        public static final int DUMP_PERMISSIONS = 1 << 6;
19935        public static final int DUMP_PACKAGES = 1 << 7;
19936        public static final int DUMP_SHARED_USERS = 1 << 8;
19937        public static final int DUMP_MESSAGES = 1 << 9;
19938        public static final int DUMP_PROVIDERS = 1 << 10;
19939        public static final int DUMP_VERIFIERS = 1 << 11;
19940        public static final int DUMP_PREFERRED = 1 << 12;
19941        public static final int DUMP_PREFERRED_XML = 1 << 13;
19942        public static final int DUMP_KEYSETS = 1 << 14;
19943        public static final int DUMP_VERSION = 1 << 15;
19944        public static final int DUMP_INSTALLS = 1 << 16;
19945        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19946        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19947        public static final int DUMP_FROZEN = 1 << 19;
19948        public static final int DUMP_DEXOPT = 1 << 20;
19949        public static final int DUMP_COMPILER_STATS = 1 << 21;
19950
19951        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19952
19953        private int mTypes;
19954
19955        private int mOptions;
19956
19957        private boolean mTitlePrinted;
19958
19959        private SharedUserSetting mSharedUser;
19960
19961        public boolean isDumping(int type) {
19962            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19963                return true;
19964            }
19965
19966            return (mTypes & type) != 0;
19967        }
19968
19969        public void setDump(int type) {
19970            mTypes |= type;
19971        }
19972
19973        public boolean isOptionEnabled(int option) {
19974            return (mOptions & option) != 0;
19975        }
19976
19977        public void setOptionEnabled(int option) {
19978            mOptions |= option;
19979        }
19980
19981        public boolean onTitlePrinted() {
19982            final boolean printed = mTitlePrinted;
19983            mTitlePrinted = true;
19984            return printed;
19985        }
19986
19987        public boolean getTitlePrinted() {
19988            return mTitlePrinted;
19989        }
19990
19991        public void setTitlePrinted(boolean enabled) {
19992            mTitlePrinted = enabled;
19993        }
19994
19995        public SharedUserSetting getSharedUser() {
19996            return mSharedUser;
19997        }
19998
19999        public void setSharedUser(SharedUserSetting user) {
20000            mSharedUser = user;
20001        }
20002    }
20003
20004    @Override
20005    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20006            FileDescriptor err, String[] args, ShellCallback callback,
20007            ResultReceiver resultReceiver) {
20008        (new PackageManagerShellCommand(this)).exec(
20009                this, in, out, err, args, callback, resultReceiver);
20010    }
20011
20012    @Override
20013    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20014        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20015                != PackageManager.PERMISSION_GRANTED) {
20016            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20017                    + Binder.getCallingPid()
20018                    + ", uid=" + Binder.getCallingUid()
20019                    + " without permission "
20020                    + android.Manifest.permission.DUMP);
20021            return;
20022        }
20023
20024        DumpState dumpState = new DumpState();
20025        boolean fullPreferred = false;
20026        boolean checkin = false;
20027
20028        String packageName = null;
20029        ArraySet<String> permissionNames = null;
20030
20031        int opti = 0;
20032        while (opti < args.length) {
20033            String opt = args[opti];
20034            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20035                break;
20036            }
20037            opti++;
20038
20039            if ("-a".equals(opt)) {
20040                // Right now we only know how to print all.
20041            } else if ("-h".equals(opt)) {
20042                pw.println("Package manager dump options:");
20043                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20044                pw.println("    --checkin: dump for a checkin");
20045                pw.println("    -f: print details of intent filters");
20046                pw.println("    -h: print this help");
20047                pw.println("  cmd may be one of:");
20048                pw.println("    l[ibraries]: list known shared libraries");
20049                pw.println("    f[eatures]: list device features");
20050                pw.println("    k[eysets]: print known keysets");
20051                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20052                pw.println("    perm[issions]: dump permissions");
20053                pw.println("    permission [name ...]: dump declaration and use of given permission");
20054                pw.println("    pref[erred]: print preferred package settings");
20055                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20056                pw.println("    prov[iders]: dump content providers");
20057                pw.println("    p[ackages]: dump installed packages");
20058                pw.println("    s[hared-users]: dump shared user IDs");
20059                pw.println("    m[essages]: print collected runtime messages");
20060                pw.println("    v[erifiers]: print package verifier info");
20061                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20062                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20063                pw.println("    version: print database version info");
20064                pw.println("    write: write current settings now");
20065                pw.println("    installs: details about install sessions");
20066                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20067                pw.println("    dexopt: dump dexopt state");
20068                pw.println("    compiler-stats: dump compiler statistics");
20069                pw.println("    <package.name>: info about given package");
20070                return;
20071            } else if ("--checkin".equals(opt)) {
20072                checkin = true;
20073            } else if ("-f".equals(opt)) {
20074                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20075            } else {
20076                pw.println("Unknown argument: " + opt + "; use -h for help");
20077            }
20078        }
20079
20080        // Is the caller requesting to dump a particular piece of data?
20081        if (opti < args.length) {
20082            String cmd = args[opti];
20083            opti++;
20084            // Is this a package name?
20085            if ("android".equals(cmd) || cmd.contains(".")) {
20086                packageName = cmd;
20087                // When dumping a single package, we always dump all of its
20088                // filter information since the amount of data will be reasonable.
20089                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20090            } else if ("check-permission".equals(cmd)) {
20091                if (opti >= args.length) {
20092                    pw.println("Error: check-permission missing permission argument");
20093                    return;
20094                }
20095                String perm = args[opti];
20096                opti++;
20097                if (opti >= args.length) {
20098                    pw.println("Error: check-permission missing package argument");
20099                    return;
20100                }
20101
20102                String pkg = args[opti];
20103                opti++;
20104                int user = UserHandle.getUserId(Binder.getCallingUid());
20105                if (opti < args.length) {
20106                    try {
20107                        user = Integer.parseInt(args[opti]);
20108                    } catch (NumberFormatException e) {
20109                        pw.println("Error: check-permission user argument is not a number: "
20110                                + args[opti]);
20111                        return;
20112                    }
20113                }
20114
20115                // Normalize package name to handle renamed packages and static libs
20116                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20117
20118                pw.println(checkPermission(perm, pkg, user));
20119                return;
20120            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20121                dumpState.setDump(DumpState.DUMP_LIBS);
20122            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20123                dumpState.setDump(DumpState.DUMP_FEATURES);
20124            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20125                if (opti >= args.length) {
20126                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20127                            | DumpState.DUMP_SERVICE_RESOLVERS
20128                            | DumpState.DUMP_RECEIVER_RESOLVERS
20129                            | DumpState.DUMP_CONTENT_RESOLVERS);
20130                } else {
20131                    while (opti < args.length) {
20132                        String name = args[opti];
20133                        if ("a".equals(name) || "activity".equals(name)) {
20134                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20135                        } else if ("s".equals(name) || "service".equals(name)) {
20136                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20137                        } else if ("r".equals(name) || "receiver".equals(name)) {
20138                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20139                        } else if ("c".equals(name) || "content".equals(name)) {
20140                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20141                        } else {
20142                            pw.println("Error: unknown resolver table type: " + name);
20143                            return;
20144                        }
20145                        opti++;
20146                    }
20147                }
20148            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20149                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20150            } else if ("permission".equals(cmd)) {
20151                if (opti >= args.length) {
20152                    pw.println("Error: permission requires permission name");
20153                    return;
20154                }
20155                permissionNames = new ArraySet<>();
20156                while (opti < args.length) {
20157                    permissionNames.add(args[opti]);
20158                    opti++;
20159                }
20160                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20161                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20162            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20163                dumpState.setDump(DumpState.DUMP_PREFERRED);
20164            } else if ("preferred-xml".equals(cmd)) {
20165                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20166                if (opti < args.length && "--full".equals(args[opti])) {
20167                    fullPreferred = true;
20168                    opti++;
20169                }
20170            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20171                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20172            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20173                dumpState.setDump(DumpState.DUMP_PACKAGES);
20174            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20175                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20176            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20177                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20178            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20179                dumpState.setDump(DumpState.DUMP_MESSAGES);
20180            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20181                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20182            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20183                    || "intent-filter-verifiers".equals(cmd)) {
20184                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20185            } else if ("version".equals(cmd)) {
20186                dumpState.setDump(DumpState.DUMP_VERSION);
20187            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20188                dumpState.setDump(DumpState.DUMP_KEYSETS);
20189            } else if ("installs".equals(cmd)) {
20190                dumpState.setDump(DumpState.DUMP_INSTALLS);
20191            } else if ("frozen".equals(cmd)) {
20192                dumpState.setDump(DumpState.DUMP_FROZEN);
20193            } else if ("dexopt".equals(cmd)) {
20194                dumpState.setDump(DumpState.DUMP_DEXOPT);
20195            } else if ("compiler-stats".equals(cmd)) {
20196                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20197            } else if ("write".equals(cmd)) {
20198                synchronized (mPackages) {
20199                    mSettings.writeLPr();
20200                    pw.println("Settings written.");
20201                    return;
20202                }
20203            }
20204        }
20205
20206        if (checkin) {
20207            pw.println("vers,1");
20208        }
20209
20210        // reader
20211        synchronized (mPackages) {
20212            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20213                if (!checkin) {
20214                    if (dumpState.onTitlePrinted())
20215                        pw.println();
20216                    pw.println("Database versions:");
20217                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20218                }
20219            }
20220
20221            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20222                if (!checkin) {
20223                    if (dumpState.onTitlePrinted())
20224                        pw.println();
20225                    pw.println("Verifiers:");
20226                    pw.print("  Required: ");
20227                    pw.print(mRequiredVerifierPackage);
20228                    pw.print(" (uid=");
20229                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20230                            UserHandle.USER_SYSTEM));
20231                    pw.println(")");
20232                } else if (mRequiredVerifierPackage != null) {
20233                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20234                    pw.print(",");
20235                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20236                            UserHandle.USER_SYSTEM));
20237                }
20238            }
20239
20240            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20241                    packageName == null) {
20242                if (mIntentFilterVerifierComponent != null) {
20243                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20244                    if (!checkin) {
20245                        if (dumpState.onTitlePrinted())
20246                            pw.println();
20247                        pw.println("Intent Filter Verifier:");
20248                        pw.print("  Using: ");
20249                        pw.print(verifierPackageName);
20250                        pw.print(" (uid=");
20251                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20252                                UserHandle.USER_SYSTEM));
20253                        pw.println(")");
20254                    } else if (verifierPackageName != null) {
20255                        pw.print("ifv,"); pw.print(verifierPackageName);
20256                        pw.print(",");
20257                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20258                                UserHandle.USER_SYSTEM));
20259                    }
20260                } else {
20261                    pw.println();
20262                    pw.println("No Intent Filter Verifier available!");
20263                }
20264            }
20265
20266            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20267                boolean printedHeader = false;
20268                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20269                while (it.hasNext()) {
20270                    String libName = it.next();
20271                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20272                    if (versionedLib == null) {
20273                        continue;
20274                    }
20275                    final int versionCount = versionedLib.size();
20276                    for (int i = 0; i < versionCount; i++) {
20277                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20278                        if (!checkin) {
20279                            if (!printedHeader) {
20280                                if (dumpState.onTitlePrinted())
20281                                    pw.println();
20282                                pw.println("Libraries:");
20283                                printedHeader = true;
20284                            }
20285                            pw.print("  ");
20286                        } else {
20287                            pw.print("lib,");
20288                        }
20289                        pw.print(libEntry.info.getName());
20290                        if (libEntry.info.isStatic()) {
20291                            pw.print(" version=" + libEntry.info.getVersion());
20292                        }
20293                        if (!checkin) {
20294                            pw.print(" -> ");
20295                        }
20296                        if (libEntry.path != null) {
20297                            pw.print(" (jar) ");
20298                            pw.print(libEntry.path);
20299                        } else {
20300                            pw.print(" (apk) ");
20301                            pw.print(libEntry.apk);
20302                        }
20303                        pw.println();
20304                    }
20305                }
20306            }
20307
20308            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20309                if (dumpState.onTitlePrinted())
20310                    pw.println();
20311                if (!checkin) {
20312                    pw.println("Features:");
20313                }
20314
20315                for (FeatureInfo feat : mAvailableFeatures.values()) {
20316                    if (checkin) {
20317                        pw.print("feat,");
20318                        pw.print(feat.name);
20319                        pw.print(",");
20320                        pw.println(feat.version);
20321                    } else {
20322                        pw.print("  ");
20323                        pw.print(feat.name);
20324                        if (feat.version > 0) {
20325                            pw.print(" version=");
20326                            pw.print(feat.version);
20327                        }
20328                        pw.println();
20329                    }
20330                }
20331            }
20332
20333            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20334                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20335                        : "Activity Resolver Table:", "  ", packageName,
20336                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20337                    dumpState.setTitlePrinted(true);
20338                }
20339            }
20340            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20341                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20342                        : "Receiver Resolver Table:", "  ", packageName,
20343                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20344                    dumpState.setTitlePrinted(true);
20345                }
20346            }
20347            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20348                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20349                        : "Service Resolver Table:", "  ", packageName,
20350                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20351                    dumpState.setTitlePrinted(true);
20352                }
20353            }
20354            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20355                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20356                        : "Provider Resolver Table:", "  ", packageName,
20357                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20358                    dumpState.setTitlePrinted(true);
20359                }
20360            }
20361
20362            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20363                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20364                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20365                    int user = mSettings.mPreferredActivities.keyAt(i);
20366                    if (pir.dump(pw,
20367                            dumpState.getTitlePrinted()
20368                                ? "\nPreferred Activities User " + user + ":"
20369                                : "Preferred Activities User " + user + ":", "  ",
20370                            packageName, true, false)) {
20371                        dumpState.setTitlePrinted(true);
20372                    }
20373                }
20374            }
20375
20376            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20377                pw.flush();
20378                FileOutputStream fout = new FileOutputStream(fd);
20379                BufferedOutputStream str = new BufferedOutputStream(fout);
20380                XmlSerializer serializer = new FastXmlSerializer();
20381                try {
20382                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20383                    serializer.startDocument(null, true);
20384                    serializer.setFeature(
20385                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20386                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20387                    serializer.endDocument();
20388                    serializer.flush();
20389                } catch (IllegalArgumentException e) {
20390                    pw.println("Failed writing: " + e);
20391                } catch (IllegalStateException e) {
20392                    pw.println("Failed writing: " + e);
20393                } catch (IOException e) {
20394                    pw.println("Failed writing: " + e);
20395                }
20396            }
20397
20398            if (!checkin
20399                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20400                    && packageName == null) {
20401                pw.println();
20402                int count = mSettings.mPackages.size();
20403                if (count == 0) {
20404                    pw.println("No applications!");
20405                    pw.println();
20406                } else {
20407                    final String prefix = "  ";
20408                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20409                    if (allPackageSettings.size() == 0) {
20410                        pw.println("No domain preferred apps!");
20411                        pw.println();
20412                    } else {
20413                        pw.println("App verification status:");
20414                        pw.println();
20415                        count = 0;
20416                        for (PackageSetting ps : allPackageSettings) {
20417                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20418                            if (ivi == null || ivi.getPackageName() == null) continue;
20419                            pw.println(prefix + "Package: " + ivi.getPackageName());
20420                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20421                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20422                            pw.println();
20423                            count++;
20424                        }
20425                        if (count == 0) {
20426                            pw.println(prefix + "No app verification established.");
20427                            pw.println();
20428                        }
20429                        for (int userId : sUserManager.getUserIds()) {
20430                            pw.println("App linkages for user " + userId + ":");
20431                            pw.println();
20432                            count = 0;
20433                            for (PackageSetting ps : allPackageSettings) {
20434                                final long status = ps.getDomainVerificationStatusForUser(userId);
20435                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20436                                        && !DEBUG_DOMAIN_VERIFICATION) {
20437                                    continue;
20438                                }
20439                                pw.println(prefix + "Package: " + ps.name);
20440                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20441                                String statusStr = IntentFilterVerificationInfo.
20442                                        getStatusStringFromValue(status);
20443                                pw.println(prefix + "Status:  " + statusStr);
20444                                pw.println();
20445                                count++;
20446                            }
20447                            if (count == 0) {
20448                                pw.println(prefix + "No configured app linkages.");
20449                                pw.println();
20450                            }
20451                        }
20452                    }
20453                }
20454            }
20455
20456            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20457                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20458                if (packageName == null && permissionNames == null) {
20459                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20460                        if (iperm == 0) {
20461                            if (dumpState.onTitlePrinted())
20462                                pw.println();
20463                            pw.println("AppOp Permissions:");
20464                        }
20465                        pw.print("  AppOp Permission ");
20466                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20467                        pw.println(":");
20468                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20469                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20470                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20471                        }
20472                    }
20473                }
20474            }
20475
20476            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20477                boolean printedSomething = false;
20478                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20479                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20480                        continue;
20481                    }
20482                    if (!printedSomething) {
20483                        if (dumpState.onTitlePrinted())
20484                            pw.println();
20485                        pw.println("Registered ContentProviders:");
20486                        printedSomething = true;
20487                    }
20488                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20489                    pw.print("    "); pw.println(p.toString());
20490                }
20491                printedSomething = false;
20492                for (Map.Entry<String, PackageParser.Provider> entry :
20493                        mProvidersByAuthority.entrySet()) {
20494                    PackageParser.Provider p = entry.getValue();
20495                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20496                        continue;
20497                    }
20498                    if (!printedSomething) {
20499                        if (dumpState.onTitlePrinted())
20500                            pw.println();
20501                        pw.println("ContentProvider Authorities:");
20502                        printedSomething = true;
20503                    }
20504                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20505                    pw.print("    "); pw.println(p.toString());
20506                    if (p.info != null && p.info.applicationInfo != null) {
20507                        final String appInfo = p.info.applicationInfo.toString();
20508                        pw.print("      applicationInfo="); pw.println(appInfo);
20509                    }
20510                }
20511            }
20512
20513            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20514                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20515            }
20516
20517            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20518                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20519            }
20520
20521            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20522                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20523            }
20524
20525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20526                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20527            }
20528
20529            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20530                // XXX should handle packageName != null by dumping only install data that
20531                // the given package is involved with.
20532                if (dumpState.onTitlePrinted()) pw.println();
20533                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20534            }
20535
20536            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20537                // XXX should handle packageName != null by dumping only install data that
20538                // the given package is involved with.
20539                if (dumpState.onTitlePrinted()) pw.println();
20540
20541                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20542                ipw.println();
20543                ipw.println("Frozen packages:");
20544                ipw.increaseIndent();
20545                if (mFrozenPackages.size() == 0) {
20546                    ipw.println("(none)");
20547                } else {
20548                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20549                        ipw.println(mFrozenPackages.valueAt(i));
20550                    }
20551                }
20552                ipw.decreaseIndent();
20553            }
20554
20555            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20556                if (dumpState.onTitlePrinted()) pw.println();
20557                dumpDexoptStateLPr(pw, packageName);
20558            }
20559
20560            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20561                if (dumpState.onTitlePrinted()) pw.println();
20562                dumpCompilerStatsLPr(pw, packageName);
20563            }
20564
20565            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20566                if (dumpState.onTitlePrinted()) pw.println();
20567                mSettings.dumpReadMessagesLPr(pw, dumpState);
20568
20569                pw.println();
20570                pw.println("Package warning messages:");
20571                BufferedReader in = null;
20572                String line = null;
20573                try {
20574                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20575                    while ((line = in.readLine()) != null) {
20576                        if (line.contains("ignored: updated version")) continue;
20577                        pw.println(line);
20578                    }
20579                } catch (IOException ignored) {
20580                } finally {
20581                    IoUtils.closeQuietly(in);
20582                }
20583            }
20584
20585            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20586                BufferedReader in = null;
20587                String line = null;
20588                try {
20589                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20590                    while ((line = in.readLine()) != null) {
20591                        if (line.contains("ignored: updated version")) continue;
20592                        pw.print("msg,");
20593                        pw.println(line);
20594                    }
20595                } catch (IOException ignored) {
20596                } finally {
20597                    IoUtils.closeQuietly(in);
20598                }
20599            }
20600        }
20601    }
20602
20603    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20604        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20605        ipw.println();
20606        ipw.println("Dexopt state:");
20607        ipw.increaseIndent();
20608        Collection<PackageParser.Package> packages = null;
20609        if (packageName != null) {
20610            PackageParser.Package targetPackage = mPackages.get(packageName);
20611            if (targetPackage != null) {
20612                packages = Collections.singletonList(targetPackage);
20613            } else {
20614                ipw.println("Unable to find package: " + packageName);
20615                return;
20616            }
20617        } else {
20618            packages = mPackages.values();
20619        }
20620
20621        for (PackageParser.Package pkg : packages) {
20622            ipw.println("[" + pkg.packageName + "]");
20623            ipw.increaseIndent();
20624            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20625            ipw.decreaseIndent();
20626        }
20627    }
20628
20629    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20630        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20631        ipw.println();
20632        ipw.println("Compiler stats:");
20633        ipw.increaseIndent();
20634        Collection<PackageParser.Package> packages = null;
20635        if (packageName != null) {
20636            PackageParser.Package targetPackage = mPackages.get(packageName);
20637            if (targetPackage != null) {
20638                packages = Collections.singletonList(targetPackage);
20639            } else {
20640                ipw.println("Unable to find package: " + packageName);
20641                return;
20642            }
20643        } else {
20644            packages = mPackages.values();
20645        }
20646
20647        for (PackageParser.Package pkg : packages) {
20648            ipw.println("[" + pkg.packageName + "]");
20649            ipw.increaseIndent();
20650
20651            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20652            if (stats == null) {
20653                ipw.println("(No recorded stats)");
20654            } else {
20655                stats.dump(ipw);
20656            }
20657            ipw.decreaseIndent();
20658        }
20659    }
20660
20661    private String dumpDomainString(String packageName) {
20662        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20663                .getList();
20664        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20665
20666        ArraySet<String> result = new ArraySet<>();
20667        if (iviList.size() > 0) {
20668            for (IntentFilterVerificationInfo ivi : iviList) {
20669                for (String host : ivi.getDomains()) {
20670                    result.add(host);
20671                }
20672            }
20673        }
20674        if (filters != null && filters.size() > 0) {
20675            for (IntentFilter filter : filters) {
20676                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20677                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20678                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20679                    result.addAll(filter.getHostsList());
20680                }
20681            }
20682        }
20683
20684        StringBuilder sb = new StringBuilder(result.size() * 16);
20685        for (String domain : result) {
20686            if (sb.length() > 0) sb.append(" ");
20687            sb.append(domain);
20688        }
20689        return sb.toString();
20690    }
20691
20692    // ------- apps on sdcard specific code -------
20693    static final boolean DEBUG_SD_INSTALL = false;
20694
20695    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20696
20697    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20698
20699    private boolean mMediaMounted = false;
20700
20701    static String getEncryptKey() {
20702        try {
20703            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20704                    SD_ENCRYPTION_KEYSTORE_NAME);
20705            if (sdEncKey == null) {
20706                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20707                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20708                if (sdEncKey == null) {
20709                    Slog.e(TAG, "Failed to create encryption keys");
20710                    return null;
20711                }
20712            }
20713            return sdEncKey;
20714        } catch (NoSuchAlgorithmException nsae) {
20715            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20716            return null;
20717        } catch (IOException ioe) {
20718            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20719            return null;
20720        }
20721    }
20722
20723    /*
20724     * Update media status on PackageManager.
20725     */
20726    @Override
20727    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20728        int callingUid = Binder.getCallingUid();
20729        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20730            throw new SecurityException("Media status can only be updated by the system");
20731        }
20732        // reader; this apparently protects mMediaMounted, but should probably
20733        // be a different lock in that case.
20734        synchronized (mPackages) {
20735            Log.i(TAG, "Updating external media status from "
20736                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20737                    + (mediaStatus ? "mounted" : "unmounted"));
20738            if (DEBUG_SD_INSTALL)
20739                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20740                        + ", mMediaMounted=" + mMediaMounted);
20741            if (mediaStatus == mMediaMounted) {
20742                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20743                        : 0, -1);
20744                mHandler.sendMessage(msg);
20745                return;
20746            }
20747            mMediaMounted = mediaStatus;
20748        }
20749        // Queue up an async operation since the package installation may take a
20750        // little while.
20751        mHandler.post(new Runnable() {
20752            public void run() {
20753                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20754            }
20755        });
20756    }
20757
20758    /**
20759     * Called by StorageManagerService when the initial ASECs to scan are available.
20760     * Should block until all the ASEC containers are finished being scanned.
20761     */
20762    public void scanAvailableAsecs() {
20763        updateExternalMediaStatusInner(true, false, false);
20764    }
20765
20766    /*
20767     * Collect information of applications on external media, map them against
20768     * existing containers and update information based on current mount status.
20769     * Please note that we always have to report status if reportStatus has been
20770     * set to true especially when unloading packages.
20771     */
20772    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20773            boolean externalStorage) {
20774        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20775        int[] uidArr = EmptyArray.INT;
20776
20777        final String[] list = PackageHelper.getSecureContainerList();
20778        if (ArrayUtils.isEmpty(list)) {
20779            Log.i(TAG, "No secure containers found");
20780        } else {
20781            // Process list of secure containers and categorize them
20782            // as active or stale based on their package internal state.
20783
20784            // reader
20785            synchronized (mPackages) {
20786                for (String cid : list) {
20787                    // Leave stages untouched for now; installer service owns them
20788                    if (PackageInstallerService.isStageName(cid)) continue;
20789
20790                    if (DEBUG_SD_INSTALL)
20791                        Log.i(TAG, "Processing container " + cid);
20792                    String pkgName = getAsecPackageName(cid);
20793                    if (pkgName == null) {
20794                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20795                        continue;
20796                    }
20797                    if (DEBUG_SD_INSTALL)
20798                        Log.i(TAG, "Looking for pkg : " + pkgName);
20799
20800                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20801                    if (ps == null) {
20802                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20803                        continue;
20804                    }
20805
20806                    /*
20807                     * Skip packages that are not external if we're unmounting
20808                     * external storage.
20809                     */
20810                    if (externalStorage && !isMounted && !isExternal(ps)) {
20811                        continue;
20812                    }
20813
20814                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20815                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20816                    // The package status is changed only if the code path
20817                    // matches between settings and the container id.
20818                    if (ps.codePathString != null
20819                            && ps.codePathString.startsWith(args.getCodePath())) {
20820                        if (DEBUG_SD_INSTALL) {
20821                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20822                                    + " at code path: " + ps.codePathString);
20823                        }
20824
20825                        // We do have a valid package installed on sdcard
20826                        processCids.put(args, ps.codePathString);
20827                        final int uid = ps.appId;
20828                        if (uid != -1) {
20829                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20830                        }
20831                    } else {
20832                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20833                                + ps.codePathString);
20834                    }
20835                }
20836            }
20837
20838            Arrays.sort(uidArr);
20839        }
20840
20841        // Process packages with valid entries.
20842        if (isMounted) {
20843            if (DEBUG_SD_INSTALL)
20844                Log.i(TAG, "Loading packages");
20845            loadMediaPackages(processCids, uidArr, externalStorage);
20846            startCleaningPackages();
20847            mInstallerService.onSecureContainersAvailable();
20848        } else {
20849            if (DEBUG_SD_INSTALL)
20850                Log.i(TAG, "Unloading packages");
20851            unloadMediaPackages(processCids, uidArr, reportStatus);
20852        }
20853    }
20854
20855    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20856            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20857        final int size = infos.size();
20858        final String[] packageNames = new String[size];
20859        final int[] packageUids = new int[size];
20860        for (int i = 0; i < size; i++) {
20861            final ApplicationInfo info = infos.get(i);
20862            packageNames[i] = info.packageName;
20863            packageUids[i] = info.uid;
20864        }
20865        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20866                finishedReceiver);
20867    }
20868
20869    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20870            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20871        sendResourcesChangedBroadcast(mediaStatus, replacing,
20872                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20873    }
20874
20875    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20876            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20877        int size = pkgList.length;
20878        if (size > 0) {
20879            // Send broadcasts here
20880            Bundle extras = new Bundle();
20881            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20882            if (uidArr != null) {
20883                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20884            }
20885            if (replacing) {
20886                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20887            }
20888            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20889                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20890            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20891        }
20892    }
20893
20894   /*
20895     * Look at potentially valid container ids from processCids If package
20896     * information doesn't match the one on record or package scanning fails,
20897     * the cid is added to list of removeCids. We currently don't delete stale
20898     * containers.
20899     */
20900    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20901            boolean externalStorage) {
20902        ArrayList<String> pkgList = new ArrayList<String>();
20903        Set<AsecInstallArgs> keys = processCids.keySet();
20904
20905        for (AsecInstallArgs args : keys) {
20906            String codePath = processCids.get(args);
20907            if (DEBUG_SD_INSTALL)
20908                Log.i(TAG, "Loading container : " + args.cid);
20909            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20910            try {
20911                // Make sure there are no container errors first.
20912                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20913                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20914                            + " when installing from sdcard");
20915                    continue;
20916                }
20917                // Check code path here.
20918                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20919                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20920                            + " does not match one in settings " + codePath);
20921                    continue;
20922                }
20923                // Parse package
20924                int parseFlags = mDefParseFlags;
20925                if (args.isExternalAsec()) {
20926                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20927                }
20928                if (args.isFwdLocked()) {
20929                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20930                }
20931
20932                synchronized (mInstallLock) {
20933                    PackageParser.Package pkg = null;
20934                    try {
20935                        // Sadly we don't know the package name yet to freeze it
20936                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20937                                SCAN_IGNORE_FROZEN, 0, null);
20938                    } catch (PackageManagerException e) {
20939                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20940                    }
20941                    // Scan the package
20942                    if (pkg != null) {
20943                        /*
20944                         * TODO why is the lock being held? doPostInstall is
20945                         * called in other places without the lock. This needs
20946                         * to be straightened out.
20947                         */
20948                        // writer
20949                        synchronized (mPackages) {
20950                            retCode = PackageManager.INSTALL_SUCCEEDED;
20951                            pkgList.add(pkg.packageName);
20952                            // Post process args
20953                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20954                                    pkg.applicationInfo.uid);
20955                        }
20956                    } else {
20957                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20958                    }
20959                }
20960
20961            } finally {
20962                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20963                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20964                }
20965            }
20966        }
20967        // writer
20968        synchronized (mPackages) {
20969            // If the platform SDK has changed since the last time we booted,
20970            // we need to re-grant app permission to catch any new ones that
20971            // appear. This is really a hack, and means that apps can in some
20972            // cases get permissions that the user didn't initially explicitly
20973            // allow... it would be nice to have some better way to handle
20974            // this situation.
20975            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20976                    : mSettings.getInternalVersion();
20977            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20978                    : StorageManager.UUID_PRIVATE_INTERNAL;
20979
20980            int updateFlags = UPDATE_PERMISSIONS_ALL;
20981            if (ver.sdkVersion != mSdkVersion) {
20982                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20983                        + mSdkVersion + "; regranting permissions for external");
20984                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20985            }
20986            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20987
20988            // Yay, everything is now upgraded
20989            ver.forceCurrent();
20990
20991            // can downgrade to reader
20992            // Persist settings
20993            mSettings.writeLPr();
20994        }
20995        // Send a broadcast to let everyone know we are done processing
20996        if (pkgList.size() > 0) {
20997            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20998        }
20999    }
21000
21001   /*
21002     * Utility method to unload a list of specified containers
21003     */
21004    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21005        // Just unmount all valid containers.
21006        for (AsecInstallArgs arg : cidArgs) {
21007            synchronized (mInstallLock) {
21008                arg.doPostDeleteLI(false);
21009           }
21010       }
21011   }
21012
21013    /*
21014     * Unload packages mounted on external media. This involves deleting package
21015     * data from internal structures, sending broadcasts about disabled packages,
21016     * gc'ing to free up references, unmounting all secure containers
21017     * corresponding to packages on external media, and posting a
21018     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21019     * that we always have to post this message if status has been requested no
21020     * matter what.
21021     */
21022    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21023            final boolean reportStatus) {
21024        if (DEBUG_SD_INSTALL)
21025            Log.i(TAG, "unloading media packages");
21026        ArrayList<String> pkgList = new ArrayList<String>();
21027        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21028        final Set<AsecInstallArgs> keys = processCids.keySet();
21029        for (AsecInstallArgs args : keys) {
21030            String pkgName = args.getPackageName();
21031            if (DEBUG_SD_INSTALL)
21032                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21033            // Delete package internally
21034            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21035            synchronized (mInstallLock) {
21036                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21037                final boolean res;
21038                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21039                        "unloadMediaPackages")) {
21040                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21041                            null);
21042                }
21043                if (res) {
21044                    pkgList.add(pkgName);
21045                } else {
21046                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21047                    failedList.add(args);
21048                }
21049            }
21050        }
21051
21052        // reader
21053        synchronized (mPackages) {
21054            // We didn't update the settings after removing each package;
21055            // write them now for all packages.
21056            mSettings.writeLPr();
21057        }
21058
21059        // We have to absolutely send UPDATED_MEDIA_STATUS only
21060        // after confirming that all the receivers processed the ordered
21061        // broadcast when packages get disabled, force a gc to clean things up.
21062        // and unload all the containers.
21063        if (pkgList.size() > 0) {
21064            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21065                    new IIntentReceiver.Stub() {
21066                public void performReceive(Intent intent, int resultCode, String data,
21067                        Bundle extras, boolean ordered, boolean sticky,
21068                        int sendingUser) throws RemoteException {
21069                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21070                            reportStatus ? 1 : 0, 1, keys);
21071                    mHandler.sendMessage(msg);
21072                }
21073            });
21074        } else {
21075            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21076                    keys);
21077            mHandler.sendMessage(msg);
21078        }
21079    }
21080
21081    private void loadPrivatePackages(final VolumeInfo vol) {
21082        mHandler.post(new Runnable() {
21083            @Override
21084            public void run() {
21085                loadPrivatePackagesInner(vol);
21086            }
21087        });
21088    }
21089
21090    private void loadPrivatePackagesInner(VolumeInfo vol) {
21091        final String volumeUuid = vol.fsUuid;
21092        if (TextUtils.isEmpty(volumeUuid)) {
21093            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21094            return;
21095        }
21096
21097        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21098        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21099        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21100
21101        final VersionInfo ver;
21102        final List<PackageSetting> packages;
21103        synchronized (mPackages) {
21104            ver = mSettings.findOrCreateVersion(volumeUuid);
21105            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21106        }
21107
21108        for (PackageSetting ps : packages) {
21109            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21110            synchronized (mInstallLock) {
21111                final PackageParser.Package pkg;
21112                try {
21113                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21114                    loaded.add(pkg.applicationInfo);
21115
21116                } catch (PackageManagerException e) {
21117                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21118                }
21119
21120                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21121                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21122                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21123                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21124                }
21125            }
21126        }
21127
21128        // Reconcile app data for all started/unlocked users
21129        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21130        final UserManager um = mContext.getSystemService(UserManager.class);
21131        UserManagerInternal umInternal = getUserManagerInternal();
21132        for (UserInfo user : um.getUsers()) {
21133            final int flags;
21134            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21135                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21136            } else if (umInternal.isUserRunning(user.id)) {
21137                flags = StorageManager.FLAG_STORAGE_DE;
21138            } else {
21139                continue;
21140            }
21141
21142            try {
21143                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21144                synchronized (mInstallLock) {
21145                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21146                }
21147            } catch (IllegalStateException e) {
21148                // Device was probably ejected, and we'll process that event momentarily
21149                Slog.w(TAG, "Failed to prepare storage: " + e);
21150            }
21151        }
21152
21153        synchronized (mPackages) {
21154            int updateFlags = UPDATE_PERMISSIONS_ALL;
21155            if (ver.sdkVersion != mSdkVersion) {
21156                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21157                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21158                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21159            }
21160            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21161
21162            // Yay, everything is now upgraded
21163            ver.forceCurrent();
21164
21165            mSettings.writeLPr();
21166        }
21167
21168        for (PackageFreezer freezer : freezers) {
21169            freezer.close();
21170        }
21171
21172        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21173        sendResourcesChangedBroadcast(true, false, loaded, null);
21174    }
21175
21176    private void unloadPrivatePackages(final VolumeInfo vol) {
21177        mHandler.post(new Runnable() {
21178            @Override
21179            public void run() {
21180                unloadPrivatePackagesInner(vol);
21181            }
21182        });
21183    }
21184
21185    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21186        final String volumeUuid = vol.fsUuid;
21187        if (TextUtils.isEmpty(volumeUuid)) {
21188            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21189            return;
21190        }
21191
21192        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21193        synchronized (mInstallLock) {
21194        synchronized (mPackages) {
21195            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21196            for (PackageSetting ps : packages) {
21197                if (ps.pkg == null) continue;
21198
21199                final ApplicationInfo info = ps.pkg.applicationInfo;
21200                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21201                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21202
21203                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21204                        "unloadPrivatePackagesInner")) {
21205                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21206                            false, null)) {
21207                        unloaded.add(info);
21208                    } else {
21209                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21210                    }
21211                }
21212
21213                // Try very hard to release any references to this package
21214                // so we don't risk the system server being killed due to
21215                // open FDs
21216                AttributeCache.instance().removePackage(ps.name);
21217            }
21218
21219            mSettings.writeLPr();
21220        }
21221        }
21222
21223        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21224        sendResourcesChangedBroadcast(false, false, unloaded, null);
21225
21226        // Try very hard to release any references to this path so we don't risk
21227        // the system server being killed due to open FDs
21228        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21229
21230        for (int i = 0; i < 3; i++) {
21231            System.gc();
21232            System.runFinalization();
21233        }
21234    }
21235
21236    /**
21237     * Prepare storage areas for given user on all mounted devices.
21238     */
21239    void prepareUserData(int userId, int userSerial, int flags) {
21240        synchronized (mInstallLock) {
21241            final StorageManager storage = mContext.getSystemService(StorageManager.class);
21242            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21243                final String volumeUuid = vol.getFsUuid();
21244                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
21245            }
21246        }
21247    }
21248
21249    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
21250            boolean allowRecover) {
21251        // Prepare storage and verify that serial numbers are consistent; if
21252        // there's a mismatch we need to destroy to avoid leaking data
21253        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21254        try {
21255            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
21256
21257            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
21258                UserManagerService.enforceSerialNumber(
21259                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
21260                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21261                    UserManagerService.enforceSerialNumber(
21262                            Environment.getDataSystemDeDirectory(userId), userSerial);
21263                }
21264            }
21265            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
21266                UserManagerService.enforceSerialNumber(
21267                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
21268                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21269                    UserManagerService.enforceSerialNumber(
21270                            Environment.getDataSystemCeDirectory(userId), userSerial);
21271                }
21272            }
21273
21274            synchronized (mInstallLock) {
21275                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
21276            }
21277        } catch (Exception e) {
21278            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
21279                    + " because we failed to prepare: " + e);
21280            destroyUserDataLI(volumeUuid, userId,
21281                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21282
21283            if (allowRecover) {
21284                // Try one last time; if we fail again we're really in trouble
21285                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
21286            }
21287        }
21288    }
21289
21290    /**
21291     * Destroy storage areas for given user on all mounted devices.
21292     */
21293    void destroyUserData(int userId, int flags) {
21294        synchronized (mInstallLock) {
21295            final StorageManager storage = mContext.getSystemService(StorageManager.class);
21296            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21297                final String volumeUuid = vol.getFsUuid();
21298                destroyUserDataLI(volumeUuid, userId, flags);
21299            }
21300        }
21301    }
21302
21303    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
21304        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21305        try {
21306            // Clean up app data, profile data, and media data
21307            mInstaller.destroyUserData(volumeUuid, userId, flags);
21308
21309            // Clean up system data
21310            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
21311                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21312                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
21313                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
21314                }
21315                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21316                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
21317                }
21318            }
21319
21320            // Data with special labels is now gone, so finish the job
21321            storage.destroyUserStorage(volumeUuid, userId, flags);
21322
21323        } catch (Exception e) {
21324            logCriticalInfo(Log.WARN,
21325                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
21326        }
21327    }
21328
21329    /**
21330     * Examine all users present on given mounted volume, and destroy data
21331     * belonging to users that are no longer valid, or whose user ID has been
21332     * recycled.
21333     */
21334    private void reconcileUsers(String volumeUuid) {
21335        final List<File> files = new ArrayList<>();
21336        Collections.addAll(files, FileUtils
21337                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
21338        Collections.addAll(files, FileUtils
21339                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
21340        Collections.addAll(files, FileUtils
21341                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
21342        Collections.addAll(files, FileUtils
21343                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
21344        for (File file : files) {
21345            if (!file.isDirectory()) continue;
21346
21347            final int userId;
21348            final UserInfo info;
21349            try {
21350                userId = Integer.parseInt(file.getName());
21351                info = sUserManager.getUserInfo(userId);
21352            } catch (NumberFormatException e) {
21353                Slog.w(TAG, "Invalid user directory " + file);
21354                continue;
21355            }
21356
21357            boolean destroyUser = false;
21358            if (info == null) {
21359                logCriticalInfo(Log.WARN, "Destroying user directory " + file
21360                        + " because no matching user was found");
21361                destroyUser = true;
21362            } else if (!mOnlyCore) {
21363                try {
21364                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
21365                } catch (IOException e) {
21366                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
21367                            + " because we failed to enforce serial number: " + e);
21368                    destroyUser = true;
21369                }
21370            }
21371
21372            if (destroyUser) {
21373                synchronized (mInstallLock) {
21374                    destroyUserDataLI(volumeUuid, userId,
21375                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21376                }
21377            }
21378        }
21379    }
21380
21381    private void assertPackageKnown(String volumeUuid, String packageName)
21382            throws PackageManagerException {
21383        synchronized (mPackages) {
21384            // Normalize package name to handle renamed packages
21385            packageName = normalizePackageNameLPr(packageName);
21386
21387            final PackageSetting ps = mSettings.mPackages.get(packageName);
21388            if (ps == null) {
21389                throw new PackageManagerException("Package " + packageName + " is unknown");
21390            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21391                throw new PackageManagerException(
21392                        "Package " + packageName + " found on unknown volume " + volumeUuid
21393                                + "; expected volume " + ps.volumeUuid);
21394            }
21395        }
21396    }
21397
21398    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21399            throws PackageManagerException {
21400        synchronized (mPackages) {
21401            // Normalize package name to handle renamed packages
21402            packageName = normalizePackageNameLPr(packageName);
21403
21404            final PackageSetting ps = mSettings.mPackages.get(packageName);
21405            if (ps == null) {
21406                throw new PackageManagerException("Package " + packageName + " is unknown");
21407            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21408                throw new PackageManagerException(
21409                        "Package " + packageName + " found on unknown volume " + volumeUuid
21410                                + "; expected volume " + ps.volumeUuid);
21411            } else if (!ps.getInstalled(userId)) {
21412                throw new PackageManagerException(
21413                        "Package " + packageName + " not installed for user " + userId);
21414            }
21415        }
21416    }
21417
21418    private List<String> collectAbsoluteCodePaths() {
21419        synchronized (mPackages) {
21420            List<String> codePaths = new ArrayList<>();
21421            final int packageCount = mSettings.mPackages.size();
21422            for (int i = 0; i < packageCount; i++) {
21423                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21424                codePaths.add(ps.codePath.getAbsolutePath());
21425            }
21426            return codePaths;
21427        }
21428    }
21429
21430    /**
21431     * Examine all apps present on given mounted volume, and destroy apps that
21432     * aren't expected, either due to uninstallation or reinstallation on
21433     * another volume.
21434     */
21435    private void reconcileApps(String volumeUuid) {
21436        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21437        List<File> filesToDelete = null;
21438
21439        final File[] files = FileUtils.listFilesOrEmpty(
21440                Environment.getDataAppDirectory(volumeUuid));
21441        for (File file : files) {
21442            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21443                    && !PackageInstallerService.isStageName(file.getName());
21444            if (!isPackage) {
21445                // Ignore entries which are not packages
21446                continue;
21447            }
21448
21449            String absolutePath = file.getAbsolutePath();
21450
21451            boolean pathValid = false;
21452            final int absoluteCodePathCount = absoluteCodePaths.size();
21453            for (int i = 0; i < absoluteCodePathCount; i++) {
21454                String absoluteCodePath = absoluteCodePaths.get(i);
21455                if (absolutePath.startsWith(absoluteCodePath)) {
21456                    pathValid = true;
21457                    break;
21458                }
21459            }
21460
21461            if (!pathValid) {
21462                if (filesToDelete == null) {
21463                    filesToDelete = new ArrayList<>();
21464                }
21465                filesToDelete.add(file);
21466            }
21467        }
21468
21469        if (filesToDelete != null) {
21470            final int fileToDeleteCount = filesToDelete.size();
21471            for (int i = 0; i < fileToDeleteCount; i++) {
21472                File fileToDelete = filesToDelete.get(i);
21473                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21474                synchronized (mInstallLock) {
21475                    removeCodePathLI(fileToDelete);
21476                }
21477            }
21478        }
21479    }
21480
21481    /**
21482     * Reconcile all app data for the given user.
21483     * <p>
21484     * Verifies that directories exist and that ownership and labeling is
21485     * correct for all installed apps on all mounted volumes.
21486     */
21487    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21488        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21489        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21490            final String volumeUuid = vol.getFsUuid();
21491            synchronized (mInstallLock) {
21492                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21493            }
21494        }
21495    }
21496
21497    /**
21498     * Reconcile all app data on given mounted volume.
21499     * <p>
21500     * Destroys app data that isn't expected, either due to uninstallation or
21501     * reinstallation on another volume.
21502     * <p>
21503     * Verifies that directories exist and that ownership and labeling is
21504     * correct for all installed apps.
21505     */
21506    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21507            boolean migrateAppData) {
21508        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21509                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21510
21511        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21512        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21513
21514        // First look for stale data that doesn't belong, and check if things
21515        // have changed since we did our last restorecon
21516        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21517            if (StorageManager.isFileEncryptedNativeOrEmulated()
21518                    && !StorageManager.isUserKeyUnlocked(userId)) {
21519                throw new RuntimeException(
21520                        "Yikes, someone asked us to reconcile CE storage while " + userId
21521                                + " was still locked; this would have caused massive data loss!");
21522            }
21523
21524            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21525            for (File file : files) {
21526                final String packageName = file.getName();
21527                try {
21528                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21529                } catch (PackageManagerException e) {
21530                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21531                    try {
21532                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21533                                StorageManager.FLAG_STORAGE_CE, 0);
21534                    } catch (InstallerException e2) {
21535                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21536                    }
21537                }
21538            }
21539        }
21540        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21541            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21542            for (File file : files) {
21543                final String packageName = file.getName();
21544                try {
21545                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21546                } catch (PackageManagerException e) {
21547                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21548                    try {
21549                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21550                                StorageManager.FLAG_STORAGE_DE, 0);
21551                    } catch (InstallerException e2) {
21552                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21553                    }
21554                }
21555            }
21556        }
21557
21558        // Ensure that data directories are ready to roll for all packages
21559        // installed for this volume and user
21560        final List<PackageSetting> packages;
21561        synchronized (mPackages) {
21562            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21563        }
21564        int preparedCount = 0;
21565        for (PackageSetting ps : packages) {
21566            final String packageName = ps.name;
21567            if (ps.pkg == null) {
21568                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21569                // TODO: might be due to legacy ASEC apps; we should circle back
21570                // and reconcile again once they're scanned
21571                continue;
21572            }
21573
21574            if (ps.getInstalled(userId)) {
21575                prepareAppDataLIF(ps.pkg, userId, flags);
21576
21577                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21578                    // We may have just shuffled around app data directories, so
21579                    // prepare them one more time
21580                    prepareAppDataLIF(ps.pkg, userId, flags);
21581                }
21582
21583                preparedCount++;
21584            }
21585        }
21586
21587        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21588    }
21589
21590    /**
21591     * Prepare app data for the given app just after it was installed or
21592     * upgraded. This method carefully only touches users that it's installed
21593     * for, and it forces a restorecon to handle any seinfo changes.
21594     * <p>
21595     * Verifies that directories exist and that ownership and labeling is
21596     * correct for all installed apps. If there is an ownership mismatch, it
21597     * will try recovering system apps by wiping data; third-party app data is
21598     * left intact.
21599     * <p>
21600     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21601     */
21602    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21603        final PackageSetting ps;
21604        synchronized (mPackages) {
21605            ps = mSettings.mPackages.get(pkg.packageName);
21606            mSettings.writeKernelMappingLPr(ps);
21607        }
21608
21609        final UserManager um = mContext.getSystemService(UserManager.class);
21610        UserManagerInternal umInternal = getUserManagerInternal();
21611        for (UserInfo user : um.getUsers()) {
21612            final int flags;
21613            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21614                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21615            } else if (umInternal.isUserRunning(user.id)) {
21616                flags = StorageManager.FLAG_STORAGE_DE;
21617            } else {
21618                continue;
21619            }
21620
21621            if (ps.getInstalled(user.id)) {
21622                // TODO: when user data is locked, mark that we're still dirty
21623                prepareAppDataLIF(pkg, user.id, flags);
21624            }
21625        }
21626    }
21627
21628    /**
21629     * Prepare app data for the given app.
21630     * <p>
21631     * Verifies that directories exist and that ownership and labeling is
21632     * correct for all installed apps. If there is an ownership mismatch, this
21633     * will try recovering system apps by wiping data; third-party app data is
21634     * left intact.
21635     */
21636    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21637        if (pkg == null) {
21638            Slog.wtf(TAG, "Package was null!", new Throwable());
21639            return;
21640        }
21641        prepareAppDataLeafLIF(pkg, userId, flags);
21642        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21643        for (int i = 0; i < childCount; i++) {
21644            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21645        }
21646    }
21647
21648    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21649        if (DEBUG_APP_DATA) {
21650            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21651                    + Integer.toHexString(flags));
21652        }
21653
21654        final String volumeUuid = pkg.volumeUuid;
21655        final String packageName = pkg.packageName;
21656        final ApplicationInfo app = pkg.applicationInfo;
21657        final int appId = UserHandle.getAppId(app.uid);
21658
21659        Preconditions.checkNotNull(app.seinfo);
21660
21661        long ceDataInode = -1;
21662        try {
21663            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21664                    appId, app.seinfo, app.targetSdkVersion);
21665        } catch (InstallerException e) {
21666            if (app.isSystemApp()) {
21667                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21668                        + ", but trying to recover: " + e);
21669                destroyAppDataLeafLIF(pkg, userId, flags);
21670                try {
21671                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21672                            appId, app.seinfo, app.targetSdkVersion);
21673                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21674                } catch (InstallerException e2) {
21675                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21676                }
21677            } else {
21678                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21679            }
21680        }
21681
21682        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21683            // TODO: mark this structure as dirty so we persist it!
21684            synchronized (mPackages) {
21685                final PackageSetting ps = mSettings.mPackages.get(packageName);
21686                if (ps != null) {
21687                    ps.setCeDataInode(ceDataInode, userId);
21688                }
21689            }
21690        }
21691
21692        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21693    }
21694
21695    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21696        if (pkg == null) {
21697            Slog.wtf(TAG, "Package was null!", new Throwable());
21698            return;
21699        }
21700        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21702        for (int i = 0; i < childCount; i++) {
21703            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21704        }
21705    }
21706
21707    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21708        final String volumeUuid = pkg.volumeUuid;
21709        final String packageName = pkg.packageName;
21710        final ApplicationInfo app = pkg.applicationInfo;
21711
21712        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21713            // Create a native library symlink only if we have native libraries
21714            // and if the native libraries are 32 bit libraries. We do not provide
21715            // this symlink for 64 bit libraries.
21716            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21717                final String nativeLibPath = app.nativeLibraryDir;
21718                try {
21719                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21720                            nativeLibPath, userId);
21721                } catch (InstallerException e) {
21722                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21723                }
21724            }
21725        }
21726    }
21727
21728    /**
21729     * For system apps on non-FBE devices, this method migrates any existing
21730     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21731     * requested by the app.
21732     */
21733    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21734        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21735                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21736            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21737                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21738            try {
21739                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21740                        storageTarget);
21741            } catch (InstallerException e) {
21742                logCriticalInfo(Log.WARN,
21743                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21744            }
21745            return true;
21746        } else {
21747            return false;
21748        }
21749    }
21750
21751    public PackageFreezer freezePackage(String packageName, String killReason) {
21752        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21753    }
21754
21755    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21756        return new PackageFreezer(packageName, userId, killReason);
21757    }
21758
21759    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21760            String killReason) {
21761        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21762    }
21763
21764    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21765            String killReason) {
21766        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21767            return new PackageFreezer();
21768        } else {
21769            return freezePackage(packageName, userId, killReason);
21770        }
21771    }
21772
21773    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21774            String killReason) {
21775        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21776    }
21777
21778    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21779            String killReason) {
21780        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21781            return new PackageFreezer();
21782        } else {
21783            return freezePackage(packageName, userId, killReason);
21784        }
21785    }
21786
21787    /**
21788     * Class that freezes and kills the given package upon creation, and
21789     * unfreezes it upon closing. This is typically used when doing surgery on
21790     * app code/data to prevent the app from running while you're working.
21791     */
21792    private class PackageFreezer implements AutoCloseable {
21793        private final String mPackageName;
21794        private final PackageFreezer[] mChildren;
21795
21796        private final boolean mWeFroze;
21797
21798        private final AtomicBoolean mClosed = new AtomicBoolean();
21799        private final CloseGuard mCloseGuard = CloseGuard.get();
21800
21801        /**
21802         * Create and return a stub freezer that doesn't actually do anything,
21803         * typically used when someone requested
21804         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21805         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21806         */
21807        public PackageFreezer() {
21808            mPackageName = null;
21809            mChildren = null;
21810            mWeFroze = false;
21811            mCloseGuard.open("close");
21812        }
21813
21814        public PackageFreezer(String packageName, int userId, String killReason) {
21815            synchronized (mPackages) {
21816                mPackageName = packageName;
21817                mWeFroze = mFrozenPackages.add(mPackageName);
21818
21819                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21820                if (ps != null) {
21821                    killApplication(ps.name, ps.appId, userId, killReason);
21822                }
21823
21824                final PackageParser.Package p = mPackages.get(packageName);
21825                if (p != null && p.childPackages != null) {
21826                    final int N = p.childPackages.size();
21827                    mChildren = new PackageFreezer[N];
21828                    for (int i = 0; i < N; i++) {
21829                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21830                                userId, killReason);
21831                    }
21832                } else {
21833                    mChildren = null;
21834                }
21835            }
21836            mCloseGuard.open("close");
21837        }
21838
21839        @Override
21840        protected void finalize() throws Throwable {
21841            try {
21842                mCloseGuard.warnIfOpen();
21843                close();
21844            } finally {
21845                super.finalize();
21846            }
21847        }
21848
21849        @Override
21850        public void close() {
21851            mCloseGuard.close();
21852            if (mClosed.compareAndSet(false, true)) {
21853                synchronized (mPackages) {
21854                    if (mWeFroze) {
21855                        mFrozenPackages.remove(mPackageName);
21856                    }
21857
21858                    if (mChildren != null) {
21859                        for (PackageFreezer freezer : mChildren) {
21860                            freezer.close();
21861                        }
21862                    }
21863                }
21864            }
21865        }
21866    }
21867
21868    /**
21869     * Verify that given package is currently frozen.
21870     */
21871    private void checkPackageFrozen(String packageName) {
21872        synchronized (mPackages) {
21873            if (!mFrozenPackages.contains(packageName)) {
21874                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21875            }
21876        }
21877    }
21878
21879    @Override
21880    public int movePackage(final String packageName, final String volumeUuid) {
21881        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21882
21883        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21884        final int moveId = mNextMoveId.getAndIncrement();
21885        mHandler.post(new Runnable() {
21886            @Override
21887            public void run() {
21888                try {
21889                    movePackageInternal(packageName, volumeUuid, moveId, user);
21890                } catch (PackageManagerException e) {
21891                    Slog.w(TAG, "Failed to move " + packageName, e);
21892                    mMoveCallbacks.notifyStatusChanged(moveId,
21893                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21894                }
21895            }
21896        });
21897        return moveId;
21898    }
21899
21900    private void movePackageInternal(final String packageName, final String volumeUuid,
21901            final int moveId, UserHandle user) throws PackageManagerException {
21902        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21903        final PackageManager pm = mContext.getPackageManager();
21904
21905        final boolean currentAsec;
21906        final String currentVolumeUuid;
21907        final File codeFile;
21908        final String installerPackageName;
21909        final String packageAbiOverride;
21910        final int appId;
21911        final String seinfo;
21912        final String label;
21913        final int targetSdkVersion;
21914        final PackageFreezer freezer;
21915        final int[] installedUserIds;
21916
21917        // reader
21918        synchronized (mPackages) {
21919            final PackageParser.Package pkg = mPackages.get(packageName);
21920            final PackageSetting ps = mSettings.mPackages.get(packageName);
21921            if (pkg == null || ps == null) {
21922                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21923            }
21924
21925            if (pkg.applicationInfo.isSystemApp()) {
21926                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21927                        "Cannot move system application");
21928            }
21929
21930            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21931            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21932                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21933            if (isInternalStorage && !allow3rdPartyOnInternal) {
21934                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21935                        "3rd party apps are not allowed on internal storage");
21936            }
21937
21938            if (pkg.applicationInfo.isExternalAsec()) {
21939                currentAsec = true;
21940                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21941            } else if (pkg.applicationInfo.isForwardLocked()) {
21942                currentAsec = true;
21943                currentVolumeUuid = "forward_locked";
21944            } else {
21945                currentAsec = false;
21946                currentVolumeUuid = ps.volumeUuid;
21947
21948                final File probe = new File(pkg.codePath);
21949                final File probeOat = new File(probe, "oat");
21950                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21951                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21952                            "Move only supported for modern cluster style installs");
21953                }
21954            }
21955
21956            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21957                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21958                        "Package already moved to " + volumeUuid);
21959            }
21960            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21961                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21962                        "Device admin cannot be moved");
21963            }
21964
21965            if (mFrozenPackages.contains(packageName)) {
21966                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21967                        "Failed to move already frozen package");
21968            }
21969
21970            codeFile = new File(pkg.codePath);
21971            installerPackageName = ps.installerPackageName;
21972            packageAbiOverride = ps.cpuAbiOverrideString;
21973            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21974            seinfo = pkg.applicationInfo.seinfo;
21975            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21976            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21977            freezer = freezePackage(packageName, "movePackageInternal");
21978            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21979        }
21980
21981        final Bundle extras = new Bundle();
21982        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21983        extras.putString(Intent.EXTRA_TITLE, label);
21984        mMoveCallbacks.notifyCreated(moveId, extras);
21985
21986        int installFlags;
21987        final boolean moveCompleteApp;
21988        final File measurePath;
21989
21990        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21991            installFlags = INSTALL_INTERNAL;
21992            moveCompleteApp = !currentAsec;
21993            measurePath = Environment.getDataAppDirectory(volumeUuid);
21994        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21995            installFlags = INSTALL_EXTERNAL;
21996            moveCompleteApp = false;
21997            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21998        } else {
21999            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22000            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22001                    || !volume.isMountedWritable()) {
22002                freezer.close();
22003                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22004                        "Move location not mounted private volume");
22005            }
22006
22007            Preconditions.checkState(!currentAsec);
22008
22009            installFlags = INSTALL_INTERNAL;
22010            moveCompleteApp = true;
22011            measurePath = Environment.getDataAppDirectory(volumeUuid);
22012        }
22013
22014        final PackageStats stats = new PackageStats(null, -1);
22015        synchronized (mInstaller) {
22016            for (int userId : installedUserIds) {
22017                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22018                    freezer.close();
22019                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22020                            "Failed to measure package size");
22021                }
22022            }
22023        }
22024
22025        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22026                + stats.dataSize);
22027
22028        final long startFreeBytes = measurePath.getFreeSpace();
22029        final long sizeBytes;
22030        if (moveCompleteApp) {
22031            sizeBytes = stats.codeSize + stats.dataSize;
22032        } else {
22033            sizeBytes = stats.codeSize;
22034        }
22035
22036        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22037            freezer.close();
22038            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22039                    "Not enough free space to move");
22040        }
22041
22042        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22043
22044        final CountDownLatch installedLatch = new CountDownLatch(1);
22045        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22046            @Override
22047            public void onUserActionRequired(Intent intent) throws RemoteException {
22048                throw new IllegalStateException();
22049            }
22050
22051            @Override
22052            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22053                    Bundle extras) throws RemoteException {
22054                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22055                        + PackageManager.installStatusToString(returnCode, msg));
22056
22057                installedLatch.countDown();
22058                freezer.close();
22059
22060                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22061                switch (status) {
22062                    case PackageInstaller.STATUS_SUCCESS:
22063                        mMoveCallbacks.notifyStatusChanged(moveId,
22064                                PackageManager.MOVE_SUCCEEDED);
22065                        break;
22066                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22067                        mMoveCallbacks.notifyStatusChanged(moveId,
22068                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22069                        break;
22070                    default:
22071                        mMoveCallbacks.notifyStatusChanged(moveId,
22072                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22073                        break;
22074                }
22075            }
22076        };
22077
22078        final MoveInfo move;
22079        if (moveCompleteApp) {
22080            // Kick off a thread to report progress estimates
22081            new Thread() {
22082                @Override
22083                public void run() {
22084                    while (true) {
22085                        try {
22086                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22087                                break;
22088                            }
22089                        } catch (InterruptedException ignored) {
22090                        }
22091
22092                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22093                        final int progress = 10 + (int) MathUtils.constrain(
22094                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22095                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22096                    }
22097                }
22098            }.start();
22099
22100            final String dataAppName = codeFile.getName();
22101            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22102                    dataAppName, appId, seinfo, targetSdkVersion);
22103        } else {
22104            move = null;
22105        }
22106
22107        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22108
22109        final Message msg = mHandler.obtainMessage(INIT_COPY);
22110        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22111        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22112                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22113                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22114                PackageManager.INSTALL_REASON_UNKNOWN);
22115        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22116        msg.obj = params;
22117
22118        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22119                System.identityHashCode(msg.obj));
22120        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22121                System.identityHashCode(msg.obj));
22122
22123        mHandler.sendMessage(msg);
22124    }
22125
22126    @Override
22127    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22129
22130        final int realMoveId = mNextMoveId.getAndIncrement();
22131        final Bundle extras = new Bundle();
22132        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22133        mMoveCallbacks.notifyCreated(realMoveId, extras);
22134
22135        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22136            @Override
22137            public void onCreated(int moveId, Bundle extras) {
22138                // Ignored
22139            }
22140
22141            @Override
22142            public void onStatusChanged(int moveId, int status, long estMillis) {
22143                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22144            }
22145        };
22146
22147        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22148        storage.setPrimaryStorageUuid(volumeUuid, callback);
22149        return realMoveId;
22150    }
22151
22152    @Override
22153    public int getMoveStatus(int moveId) {
22154        mContext.enforceCallingOrSelfPermission(
22155                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22156        return mMoveCallbacks.mLastStatus.get(moveId);
22157    }
22158
22159    @Override
22160    public void registerMoveCallback(IPackageMoveObserver callback) {
22161        mContext.enforceCallingOrSelfPermission(
22162                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22163        mMoveCallbacks.register(callback);
22164    }
22165
22166    @Override
22167    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22168        mContext.enforceCallingOrSelfPermission(
22169                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22170        mMoveCallbacks.unregister(callback);
22171    }
22172
22173    @Override
22174    public boolean setInstallLocation(int loc) {
22175        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22176                null);
22177        if (getInstallLocation() == loc) {
22178            return true;
22179        }
22180        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22181                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22182            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22183                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22184            return true;
22185        }
22186        return false;
22187   }
22188
22189    @Override
22190    public int getInstallLocation() {
22191        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22192                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22193                PackageHelper.APP_INSTALL_AUTO);
22194    }
22195
22196    /** Called by UserManagerService */
22197    void cleanUpUser(UserManagerService userManager, int userHandle) {
22198        synchronized (mPackages) {
22199            mDirtyUsers.remove(userHandle);
22200            mUserNeedsBadging.delete(userHandle);
22201            mSettings.removeUserLPw(userHandle);
22202            mPendingBroadcasts.remove(userHandle);
22203            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
22204            removeUnusedPackagesLPw(userManager, userHandle);
22205        }
22206    }
22207
22208    /**
22209     * We're removing userHandle and would like to remove any downloaded packages
22210     * that are no longer in use by any other user.
22211     * @param userHandle the user being removed
22212     */
22213    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22214        final boolean DEBUG_CLEAN_APKS = false;
22215        int [] users = userManager.getUserIds();
22216        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22217        while (psit.hasNext()) {
22218            PackageSetting ps = psit.next();
22219            if (ps.pkg == null) {
22220                continue;
22221            }
22222            final String packageName = ps.pkg.packageName;
22223            // Skip over if system app
22224            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22225                continue;
22226            }
22227            if (DEBUG_CLEAN_APKS) {
22228                Slog.i(TAG, "Checking package " + packageName);
22229            }
22230            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22231            if (keep) {
22232                if (DEBUG_CLEAN_APKS) {
22233                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22234                }
22235            } else {
22236                for (int i = 0; i < users.length; i++) {
22237                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22238                        keep = true;
22239                        if (DEBUG_CLEAN_APKS) {
22240                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22241                                    + users[i]);
22242                        }
22243                        break;
22244                    }
22245                }
22246            }
22247            if (!keep) {
22248                if (DEBUG_CLEAN_APKS) {
22249                    Slog.i(TAG, "  Removing package " + packageName);
22250                }
22251                mHandler.post(new Runnable() {
22252                    public void run() {
22253                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22254                                userHandle, 0);
22255                    } //end run
22256                });
22257            }
22258        }
22259    }
22260
22261    /** Called by UserManagerService */
22262    void createNewUser(int userId, String[] disallowedPackages) {
22263        synchronized (mInstallLock) {
22264            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22265        }
22266        synchronized (mPackages) {
22267            scheduleWritePackageRestrictionsLocked(userId);
22268            scheduleWritePackageListLocked(userId);
22269            applyFactoryDefaultBrowserLPw(userId);
22270            primeDomainVerificationsLPw(userId);
22271        }
22272    }
22273
22274    void onNewUserCreated(final int userId) {
22275        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22276        // If permission review for legacy apps is required, we represent
22277        // dagerous permissions for such apps as always granted runtime
22278        // permissions to keep per user flag state whether review is needed.
22279        // Hence, if a new user is added we have to propagate dangerous
22280        // permission grants for these legacy apps.
22281        if (mPermissionReviewRequired) {
22282            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22283                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22284        }
22285    }
22286
22287    @Override
22288    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22289        mContext.enforceCallingOrSelfPermission(
22290                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22291                "Only package verification agents can read the verifier device identity");
22292
22293        synchronized (mPackages) {
22294            return mSettings.getVerifierDeviceIdentityLPw();
22295        }
22296    }
22297
22298    @Override
22299    public void setPermissionEnforced(String permission, boolean enforced) {
22300        // TODO: Now that we no longer change GID for storage, this should to away.
22301        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22302                "setPermissionEnforced");
22303        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22304            synchronized (mPackages) {
22305                if (mSettings.mReadExternalStorageEnforced == null
22306                        || mSettings.mReadExternalStorageEnforced != enforced) {
22307                    mSettings.mReadExternalStorageEnforced = enforced;
22308                    mSettings.writeLPr();
22309                }
22310            }
22311            // kill any non-foreground processes so we restart them and
22312            // grant/revoke the GID.
22313            final IActivityManager am = ActivityManager.getService();
22314            if (am != null) {
22315                final long token = Binder.clearCallingIdentity();
22316                try {
22317                    am.killProcessesBelowForeground("setPermissionEnforcement");
22318                } catch (RemoteException e) {
22319                } finally {
22320                    Binder.restoreCallingIdentity(token);
22321                }
22322            }
22323        } else {
22324            throw new IllegalArgumentException("No selective enforcement for " + permission);
22325        }
22326    }
22327
22328    @Override
22329    @Deprecated
22330    public boolean isPermissionEnforced(String permission) {
22331        return true;
22332    }
22333
22334    @Override
22335    public boolean isStorageLow() {
22336        final long token = Binder.clearCallingIdentity();
22337        try {
22338            final DeviceStorageMonitorInternal
22339                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22340            if (dsm != null) {
22341                return dsm.isMemoryLow();
22342            } else {
22343                return false;
22344            }
22345        } finally {
22346            Binder.restoreCallingIdentity(token);
22347        }
22348    }
22349
22350    @Override
22351    public IPackageInstaller getPackageInstaller() {
22352        return mInstallerService;
22353    }
22354
22355    private boolean userNeedsBadging(int userId) {
22356        int index = mUserNeedsBadging.indexOfKey(userId);
22357        if (index < 0) {
22358            final UserInfo userInfo;
22359            final long token = Binder.clearCallingIdentity();
22360            try {
22361                userInfo = sUserManager.getUserInfo(userId);
22362            } finally {
22363                Binder.restoreCallingIdentity(token);
22364            }
22365            final boolean b;
22366            if (userInfo != null && userInfo.isManagedProfile()) {
22367                b = true;
22368            } else {
22369                b = false;
22370            }
22371            mUserNeedsBadging.put(userId, b);
22372            return b;
22373        }
22374        return mUserNeedsBadging.valueAt(index);
22375    }
22376
22377    @Override
22378    public KeySet getKeySetByAlias(String packageName, String alias) {
22379        if (packageName == null || alias == null) {
22380            return null;
22381        }
22382        synchronized(mPackages) {
22383            final PackageParser.Package pkg = mPackages.get(packageName);
22384            if (pkg == null) {
22385                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22386                throw new IllegalArgumentException("Unknown package: " + packageName);
22387            }
22388            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22389            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22390        }
22391    }
22392
22393    @Override
22394    public KeySet getSigningKeySet(String packageName) {
22395        if (packageName == null) {
22396            return null;
22397        }
22398        synchronized(mPackages) {
22399            final PackageParser.Package pkg = mPackages.get(packageName);
22400            if (pkg == null) {
22401                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22402                throw new IllegalArgumentException("Unknown package: " + packageName);
22403            }
22404            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22405                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22406                throw new SecurityException("May not access signing KeySet of other apps.");
22407            }
22408            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22409            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22410        }
22411    }
22412
22413    @Override
22414    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22415        if (packageName == null || ks == null) {
22416            return false;
22417        }
22418        synchronized(mPackages) {
22419            final PackageParser.Package pkg = mPackages.get(packageName);
22420            if (pkg == null) {
22421                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22422                throw new IllegalArgumentException("Unknown package: " + packageName);
22423            }
22424            IBinder ksh = ks.getToken();
22425            if (ksh instanceof KeySetHandle) {
22426                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22427                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22428            }
22429            return false;
22430        }
22431    }
22432
22433    @Override
22434    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22435        if (packageName == null || ks == null) {
22436            return false;
22437        }
22438        synchronized(mPackages) {
22439            final PackageParser.Package pkg = mPackages.get(packageName);
22440            if (pkg == null) {
22441                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22442                throw new IllegalArgumentException("Unknown package: " + packageName);
22443            }
22444            IBinder ksh = ks.getToken();
22445            if (ksh instanceof KeySetHandle) {
22446                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22447                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22448            }
22449            return false;
22450        }
22451    }
22452
22453    private void deletePackageIfUnusedLPr(final String packageName) {
22454        PackageSetting ps = mSettings.mPackages.get(packageName);
22455        if (ps == null) {
22456            return;
22457        }
22458        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22459            // TODO Implement atomic delete if package is unused
22460            // It is currently possible that the package will be deleted even if it is installed
22461            // after this method returns.
22462            mHandler.post(new Runnable() {
22463                public void run() {
22464                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22465                            0, PackageManager.DELETE_ALL_USERS);
22466                }
22467            });
22468        }
22469    }
22470
22471    /**
22472     * Check and throw if the given before/after packages would be considered a
22473     * downgrade.
22474     */
22475    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22476            throws PackageManagerException {
22477        if (after.versionCode < before.mVersionCode) {
22478            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22479                    "Update version code " + after.versionCode + " is older than current "
22480                    + before.mVersionCode);
22481        } else if (after.versionCode == before.mVersionCode) {
22482            if (after.baseRevisionCode < before.baseRevisionCode) {
22483                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22484                        "Update base revision code " + after.baseRevisionCode
22485                        + " is older than current " + before.baseRevisionCode);
22486            }
22487
22488            if (!ArrayUtils.isEmpty(after.splitNames)) {
22489                for (int i = 0; i < after.splitNames.length; i++) {
22490                    final String splitName = after.splitNames[i];
22491                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22492                    if (j != -1) {
22493                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22494                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22495                                    "Update split " + splitName + " revision code "
22496                                    + after.splitRevisionCodes[i] + " is older than current "
22497                                    + before.splitRevisionCodes[j]);
22498                        }
22499                    }
22500                }
22501            }
22502        }
22503    }
22504
22505    private static class MoveCallbacks extends Handler {
22506        private static final int MSG_CREATED = 1;
22507        private static final int MSG_STATUS_CHANGED = 2;
22508
22509        private final RemoteCallbackList<IPackageMoveObserver>
22510                mCallbacks = new RemoteCallbackList<>();
22511
22512        private final SparseIntArray mLastStatus = new SparseIntArray();
22513
22514        public MoveCallbacks(Looper looper) {
22515            super(looper);
22516        }
22517
22518        public void register(IPackageMoveObserver callback) {
22519            mCallbacks.register(callback);
22520        }
22521
22522        public void unregister(IPackageMoveObserver callback) {
22523            mCallbacks.unregister(callback);
22524        }
22525
22526        @Override
22527        public void handleMessage(Message msg) {
22528            final SomeArgs args = (SomeArgs) msg.obj;
22529            final int n = mCallbacks.beginBroadcast();
22530            for (int i = 0; i < n; i++) {
22531                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22532                try {
22533                    invokeCallback(callback, msg.what, args);
22534                } catch (RemoteException ignored) {
22535                }
22536            }
22537            mCallbacks.finishBroadcast();
22538            args.recycle();
22539        }
22540
22541        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22542                throws RemoteException {
22543            switch (what) {
22544                case MSG_CREATED: {
22545                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22546                    break;
22547                }
22548                case MSG_STATUS_CHANGED: {
22549                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22550                    break;
22551                }
22552            }
22553        }
22554
22555        private void notifyCreated(int moveId, Bundle extras) {
22556            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22557
22558            final SomeArgs args = SomeArgs.obtain();
22559            args.argi1 = moveId;
22560            args.arg2 = extras;
22561            obtainMessage(MSG_CREATED, args).sendToTarget();
22562        }
22563
22564        private void notifyStatusChanged(int moveId, int status) {
22565            notifyStatusChanged(moveId, status, -1);
22566        }
22567
22568        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22569            Slog.v(TAG, "Move " + moveId + " status " + status);
22570
22571            final SomeArgs args = SomeArgs.obtain();
22572            args.argi1 = moveId;
22573            args.argi2 = status;
22574            args.arg3 = estMillis;
22575            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22576
22577            synchronized (mLastStatus) {
22578                mLastStatus.put(moveId, status);
22579            }
22580        }
22581    }
22582
22583    private final static class OnPermissionChangeListeners extends Handler {
22584        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22585
22586        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22587                new RemoteCallbackList<>();
22588
22589        public OnPermissionChangeListeners(Looper looper) {
22590            super(looper);
22591        }
22592
22593        @Override
22594        public void handleMessage(Message msg) {
22595            switch (msg.what) {
22596                case MSG_ON_PERMISSIONS_CHANGED: {
22597                    final int uid = msg.arg1;
22598                    handleOnPermissionsChanged(uid);
22599                } break;
22600            }
22601        }
22602
22603        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22604            mPermissionListeners.register(listener);
22605
22606        }
22607
22608        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22609            mPermissionListeners.unregister(listener);
22610        }
22611
22612        public void onPermissionsChanged(int uid) {
22613            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22614                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22615            }
22616        }
22617
22618        private void handleOnPermissionsChanged(int uid) {
22619            final int count = mPermissionListeners.beginBroadcast();
22620            try {
22621                for (int i = 0; i < count; i++) {
22622                    IOnPermissionsChangeListener callback = mPermissionListeners
22623                            .getBroadcastItem(i);
22624                    try {
22625                        callback.onPermissionsChanged(uid);
22626                    } catch (RemoteException e) {
22627                        Log.e(TAG, "Permission listener is dead", e);
22628                    }
22629                }
22630            } finally {
22631                mPermissionListeners.finishBroadcast();
22632            }
22633        }
22634    }
22635
22636    private class PackageManagerInternalImpl extends PackageManagerInternal {
22637        @Override
22638        public void setLocationPackagesProvider(PackagesProvider provider) {
22639            synchronized (mPackages) {
22640                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22641            }
22642        }
22643
22644        @Override
22645        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22646            synchronized (mPackages) {
22647                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22648            }
22649        }
22650
22651        @Override
22652        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22653            synchronized (mPackages) {
22654                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22655            }
22656        }
22657
22658        @Override
22659        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22660            synchronized (mPackages) {
22661                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22662            }
22663        }
22664
22665        @Override
22666        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22667            synchronized (mPackages) {
22668                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22669            }
22670        }
22671
22672        @Override
22673        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22674            synchronized (mPackages) {
22675                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22676            }
22677        }
22678
22679        @Override
22680        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22681            synchronized (mPackages) {
22682                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22683                        packageName, userId);
22684            }
22685        }
22686
22687        @Override
22688        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22689            synchronized (mPackages) {
22690                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22691                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22692                        packageName, userId);
22693            }
22694        }
22695
22696        @Override
22697        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22698            synchronized (mPackages) {
22699                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22700                        packageName, userId);
22701            }
22702        }
22703
22704        @Override
22705        public void setKeepUninstalledPackages(final List<String> packageList) {
22706            Preconditions.checkNotNull(packageList);
22707            List<String> removedFromList = null;
22708            synchronized (mPackages) {
22709                if (mKeepUninstalledPackages != null) {
22710                    final int packagesCount = mKeepUninstalledPackages.size();
22711                    for (int i = 0; i < packagesCount; i++) {
22712                        String oldPackage = mKeepUninstalledPackages.get(i);
22713                        if (packageList != null && packageList.contains(oldPackage)) {
22714                            continue;
22715                        }
22716                        if (removedFromList == null) {
22717                            removedFromList = new ArrayList<>();
22718                        }
22719                        removedFromList.add(oldPackage);
22720                    }
22721                }
22722                mKeepUninstalledPackages = new ArrayList<>(packageList);
22723                if (removedFromList != null) {
22724                    final int removedCount = removedFromList.size();
22725                    for (int i = 0; i < removedCount; i++) {
22726                        deletePackageIfUnusedLPr(removedFromList.get(i));
22727                    }
22728                }
22729            }
22730        }
22731
22732        @Override
22733        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22734            synchronized (mPackages) {
22735                // If we do not support permission review, done.
22736                if (!mPermissionReviewRequired) {
22737                    return false;
22738                }
22739
22740                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22741                if (packageSetting == null) {
22742                    return false;
22743                }
22744
22745                // Permission review applies only to apps not supporting the new permission model.
22746                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22747                    return false;
22748                }
22749
22750                // Legacy apps have the permission and get user consent on launch.
22751                PermissionsState permissionsState = packageSetting.getPermissionsState();
22752                return permissionsState.isPermissionReviewRequired(userId);
22753            }
22754        }
22755
22756        @Override
22757        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22758            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22759        }
22760
22761        @Override
22762        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22763                int userId) {
22764            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22765        }
22766
22767        @Override
22768        public void setDeviceAndProfileOwnerPackages(
22769                int deviceOwnerUserId, String deviceOwnerPackage,
22770                SparseArray<String> profileOwnerPackages) {
22771            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22772                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22773        }
22774
22775        @Override
22776        public boolean isPackageDataProtected(int userId, String packageName) {
22777            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22778        }
22779
22780        @Override
22781        public boolean isPackageEphemeral(int userId, String packageName) {
22782            synchronized (mPackages) {
22783                PackageParser.Package p = mPackages.get(packageName);
22784                return p != null ? p.applicationInfo.isEphemeralApp() : false;
22785            }
22786        }
22787
22788        @Override
22789        public boolean wasPackageEverLaunched(String packageName, int userId) {
22790            synchronized (mPackages) {
22791                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22792            }
22793        }
22794
22795        @Override
22796        public void grantRuntimePermission(String packageName, String name, int userId,
22797                boolean overridePolicy) {
22798            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22799                    overridePolicy);
22800        }
22801
22802        @Override
22803        public void revokeRuntimePermission(String packageName, String name, int userId,
22804                boolean overridePolicy) {
22805            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22806                    overridePolicy);
22807        }
22808
22809        @Override
22810        public String getNameForUid(int uid) {
22811            return PackageManagerService.this.getNameForUid(uid);
22812        }
22813
22814        @Override
22815        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22816                Intent origIntent, String resolvedType, Intent launchIntent,
22817                String callingPackage, int userId) {
22818            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22819                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22820        }
22821
22822        @Override
22823        public void grantEphemeralAccess(int userId, Intent intent,
22824                int targetAppId, int ephemeralAppId) {
22825            synchronized (mPackages) {
22826                mEphemeralApplicationRegistry.grantEphemeralAccessLPw(userId, intent,
22827                        targetAppId, ephemeralAppId);
22828            }
22829        }
22830
22831        public String getSetupWizardPackageName() {
22832            return mSetupWizardPackage;
22833        }
22834    }
22835
22836    @Override
22837    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22838        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22839        synchronized (mPackages) {
22840            final long identity = Binder.clearCallingIdentity();
22841            try {
22842                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22843                        packageNames, userId);
22844            } finally {
22845                Binder.restoreCallingIdentity(identity);
22846            }
22847        }
22848    }
22849
22850    private static void enforceSystemOrPhoneCaller(String tag) {
22851        int callingUid = Binder.getCallingUid();
22852        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22853            throw new SecurityException(
22854                    "Cannot call " + tag + " from UID " + callingUid);
22855        }
22856    }
22857
22858    boolean isHistoricalPackageUsageAvailable() {
22859        return mPackageUsage.isHistoricalPackageUsageAvailable();
22860    }
22861
22862    /**
22863     * Return a <b>copy</b> of the collection of packages known to the package manager.
22864     * @return A copy of the values of mPackages.
22865     */
22866    Collection<PackageParser.Package> getPackages() {
22867        synchronized (mPackages) {
22868            return new ArrayList<>(mPackages.values());
22869        }
22870    }
22871
22872    /**
22873     * Logs process start information (including base APK hash) to the security log.
22874     * @hide
22875     */
22876    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22877            String apkFile, int pid) {
22878        if (!SecurityLog.isLoggingEnabled()) {
22879            return;
22880        }
22881        Bundle data = new Bundle();
22882        data.putLong("startTimestamp", System.currentTimeMillis());
22883        data.putString("processName", processName);
22884        data.putInt("uid", uid);
22885        data.putString("seinfo", seinfo);
22886        data.putString("apkFile", apkFile);
22887        data.putInt("pid", pid);
22888        Message msg = mProcessLoggingHandler.obtainMessage(
22889                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22890        msg.setData(data);
22891        mProcessLoggingHandler.sendMessage(msg);
22892    }
22893
22894    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22895        return mCompilerStats.getPackageStats(pkgName);
22896    }
22897
22898    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22899        return getOrCreateCompilerPackageStats(pkg.packageName);
22900    }
22901
22902    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22903        return mCompilerStats.getOrCreatePackageStats(pkgName);
22904    }
22905
22906    public void deleteCompilerPackageStats(String pkgName) {
22907        mCompilerStats.deletePackageStats(pkgName);
22908    }
22909
22910    @Override
22911    public int getInstallReason(String packageName, int userId) {
22912        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22913                true /* requireFullPermission */, false /* checkShell */,
22914                "get install reason");
22915        synchronized (mPackages) {
22916            final PackageSetting ps = mSettings.mPackages.get(packageName);
22917            if (ps != null) {
22918                return ps.getInstallReason(userId);
22919            }
22920        }
22921        return PackageManager.INSTALL_REASON_UNKNOWN;
22922    }
22923}
22924