PackageManagerService.java revision be0b8896d1bc385d4c8fb54c21929745935dcbea
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_INSTANT_APP_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.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppInfo;
132import android.content.pm.EphemeralRequest;
133import android.content.pm.EphemeralResolveInfo;
134import android.content.pm.EphemeralResponse;
135import android.content.pm.FallbackCategoryProvider;
136import android.content.pm.FeatureInfo;
137import android.content.pm.IOnPermissionsChangeListener;
138import android.content.pm.IPackageDataObserver;
139import android.content.pm.IPackageDeleteObserver;
140import android.content.pm.IPackageDeleteObserver2;
141import android.content.pm.IPackageInstallObserver2;
142import android.content.pm.IPackageInstaller;
143import android.content.pm.IPackageManager;
144import android.content.pm.IPackageMoveObserver;
145import android.content.pm.IPackageStatsObserver;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManagerInternal;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.view.Display;
239
240import com.android.internal.R;
241import com.android.internal.annotations.GuardedBy;
242import com.android.internal.app.IMediaContainerService;
243import com.android.internal.app.ResolverActivity;
244import com.android.internal.content.NativeLibraryHelper;
245import com.android.internal.content.PackageHelper;
246import com.android.internal.logging.MetricsLogger;
247import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
248import com.android.internal.os.IParcelFileDescriptorFactory;
249import com.android.internal.os.RoSystemProperties;
250import com.android.internal.os.SomeArgs;
251import com.android.internal.os.Zygote;
252import com.android.internal.telephony.CarrierAppUtils;
253import com.android.internal.util.ArrayUtils;
254import com.android.internal.util.FastPrintWriter;
255import com.android.internal.util.FastXmlSerializer;
256import com.android.internal.util.IndentingPrintWriter;
257import com.android.internal.util.Preconditions;
258import com.android.internal.util.XmlUtils;
259import com.android.server.AttributeCache;
260import com.android.server.BackgroundDexOptJobService;
261import com.android.server.EventLogTags;
262import com.android.server.FgThread;
263import com.android.server.IntentResolver;
264import com.android.server.LocalServices;
265import com.android.server.ServiceThread;
266import com.android.server.SystemConfig;
267import com.android.server.Watchdog;
268import com.android.server.net.NetworkPolicyManagerInternal;
269import com.android.server.pm.Installer.InstallerException;
270import com.android.server.pm.PermissionsState.PermissionState;
271import com.android.server.pm.Settings.DatabaseVersion;
272import com.android.server.pm.Settings.VersionInfo;
273import com.android.server.pm.dex.DexManager;
274import com.android.server.storage.DeviceStorageMonitorInternal;
275
276import dalvik.system.CloseGuard;
277import dalvik.system.DexFile;
278import dalvik.system.VMRuntime;
279
280import libcore.io.IoUtils;
281import libcore.util.EmptyArray;
282
283import org.xmlpull.v1.XmlPullParser;
284import org.xmlpull.v1.XmlPullParserException;
285import org.xmlpull.v1.XmlSerializer;
286
287import java.io.BufferedOutputStream;
288import java.io.BufferedReader;
289import java.io.ByteArrayInputStream;
290import java.io.ByteArrayOutputStream;
291import java.io.File;
292import java.io.FileDescriptor;
293import java.io.FileInputStream;
294import java.io.FileNotFoundException;
295import java.io.FileOutputStream;
296import java.io.FileReader;
297import java.io.FilenameFilter;
298import java.io.IOException;
299import java.io.PrintWriter;
300import java.nio.charset.StandardCharsets;
301import java.security.DigestInputStream;
302import java.security.MessageDigest;
303import java.security.NoSuchAlgorithmException;
304import java.security.PublicKey;
305import java.security.SecureRandom;
306import java.security.cert.Certificate;
307import java.security.cert.CertificateEncodingException;
308import java.security.cert.CertificateException;
309import java.text.SimpleDateFormat;
310import java.util.ArrayList;
311import java.util.Arrays;
312import java.util.Collection;
313import java.util.Collections;
314import java.util.Comparator;
315import java.util.Date;
316import java.util.HashSet;
317import java.util.HashMap;
318import java.util.Iterator;
319import java.util.List;
320import java.util.Map;
321import java.util.Objects;
322import java.util.Set;
323import java.util.concurrent.CountDownLatch;
324import java.util.concurrent.TimeUnit;
325import java.util.concurrent.atomic.AtomicBoolean;
326import java.util.concurrent.atomic.AtomicInteger;
327
328/**
329 * Keep track of all those APKs everywhere.
330 * <p>
331 * Internally there are two important locks:
332 * <ul>
333 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
334 * and other related state. It is a fine-grained lock that should only be held
335 * momentarily, as it's one of the most contended locks in the system.
336 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
337 * operations typically involve heavy lifting of application data on disk. Since
338 * {@code installd} is single-threaded, and it's operations can often be slow,
339 * this lock should never be acquired while already holding {@link #mPackages}.
340 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
341 * holding {@link #mInstallLock}.
342 * </ul>
343 * Many internal methods rely on the caller to hold the appropriate locks, and
344 * this contract is expressed through method name suffixes:
345 * <ul>
346 * <li>fooLI(): the caller must hold {@link #mInstallLock}
347 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
348 * being modified must be frozen
349 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
350 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
351 * </ul>
352 * <p>
353 * Because this class is very central to the platform's security; please run all
354 * CTS and unit tests whenever making modifications:
355 *
356 * <pre>
357 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
358 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
359 * </pre>
360 */
361public class PackageManagerService extends IPackageManager.Stub {
362    static final String TAG = "PackageManager";
363    static final boolean DEBUG_SETTINGS = false;
364    static final boolean DEBUG_PREFERRED = false;
365    static final boolean DEBUG_UPGRADE = false;
366    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
367    private static final boolean DEBUG_BACKUP = false;
368    private static final boolean DEBUG_INSTALL = false;
369    private static final boolean DEBUG_REMOVE = false;
370    private static final boolean DEBUG_BROADCASTS = false;
371    private static final boolean DEBUG_SHOW_INFO = false;
372    private static final boolean DEBUG_PACKAGE_INFO = false;
373    private static final boolean DEBUG_INTENT_MATCHING = false;
374    private static final boolean DEBUG_PACKAGE_SCANNING = false;
375    private static final boolean DEBUG_VERIFY = false;
376    private static final boolean DEBUG_FILTERS = false;
377
378    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
379    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
380    // user, but by default initialize to this.
381    public static final boolean DEBUG_DEXOPT = false;
382
383    private static final boolean DEBUG_ABI_SELECTION = false;
384    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
385    private static final boolean DEBUG_TRIAGED_MISSING = false;
386    private static final boolean DEBUG_APP_DATA = false;
387
388    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
389    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
390
391    private static final boolean DISABLE_EPHEMERAL_APPS = false;
392    private static final boolean HIDE_EPHEMERAL_APIS = false;
393
394    private static final boolean ENABLE_QUOTA =
395            SystemProperties.getBoolean("persist.fw.quota", false);
396
397    private static final int RADIO_UID = Process.PHONE_UID;
398    private static final int LOG_UID = Process.LOG_UID;
399    private static final int NFC_UID = Process.NFC_UID;
400    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
401    private static final int SHELL_UID = Process.SHELL_UID;
402
403    // Cap the size of permission trees that 3rd party apps can define
404    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
405
406    // Suffix used during package installation when copying/moving
407    // package apks to install directory.
408    private static final String INSTALL_PACKAGE_SUFFIX = "-";
409
410    static final int SCAN_NO_DEX = 1<<1;
411    static final int SCAN_FORCE_DEX = 1<<2;
412    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
413    static final int SCAN_NEW_INSTALL = 1<<4;
414    static final int SCAN_UPDATE_TIME = 1<<5;
415    static final int SCAN_BOOTING = 1<<6;
416    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
417    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
418    static final int SCAN_REPLACING = 1<<9;
419    static final int SCAN_REQUIRE_KNOWN = 1<<10;
420    static final int SCAN_MOVE = 1<<11;
421    static final int SCAN_INITIAL = 1<<12;
422    static final int SCAN_CHECK_ONLY = 1<<13;
423    static final int SCAN_DONT_KILL_APP = 1<<14;
424    static final int SCAN_IGNORE_FROZEN = 1<<15;
425    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
426    static final int SCAN_AS_INSTANT_APP = 1<<17;
427    static final int SCAN_AS_FULL_APP = 1<<18;
428    /** Should not be with the scan flags */
429    static final int FLAGS_REMOVE_CHATTY = 1<<31;
430
431    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
432
433    private static final int[] EMPTY_INT_ARRAY = new int[0];
434
435    /**
436     * Timeout (in milliseconds) after which the watchdog should declare that
437     * our handler thread is wedged.  The usual default for such things is one
438     * minute but we sometimes do very lengthy I/O operations on this thread,
439     * such as installing multi-gigabyte applications, so ours needs to be longer.
440     */
441    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
442
443    /**
444     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
445     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
446     * settings entry if available, otherwise we use the hardcoded default.  If it's been
447     * more than this long since the last fstrim, we force one during the boot sequence.
448     *
449     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
450     * one gets run at the next available charging+idle time.  This final mandatory
451     * no-fstrim check kicks in only of the other scheduling criteria is never met.
452     */
453    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
454
455    /**
456     * Whether verification is enabled by default.
457     */
458    private static final boolean DEFAULT_VERIFY_ENABLE = true;
459
460    /**
461     * The default maximum time to wait for the verification agent to return in
462     * milliseconds.
463     */
464    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
465
466    /**
467     * The default response for package verification timeout.
468     *
469     * This can be either PackageManager.VERIFICATION_ALLOW or
470     * PackageManager.VERIFICATION_REJECT.
471     */
472    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
473
474    static final String PLATFORM_PACKAGE_NAME = "android";
475
476    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
477
478    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
479            DEFAULT_CONTAINER_PACKAGE,
480            "com.android.defcontainer.DefaultContainerService");
481
482    private static final String KILL_APP_REASON_GIDS_CHANGED =
483            "permission grant or revoke changed gids";
484
485    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
486            "permissions revoked";
487
488    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
489
490    private static final String PACKAGE_SCHEME = "package";
491
492    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
493    /**
494     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
495     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
496     * VENDOR_OVERLAY_DIR.
497     */
498    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
499    /**
500     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
501     * is in VENDOR_OVERLAY_THEME_PROPERTY.
502     */
503    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
504            = "persist.vendor.overlay.theme";
505
506    /** Permission grant: not grant the permission. */
507    private static final int GRANT_DENIED = 1;
508
509    /** Permission grant: grant the permission as an install permission. */
510    private static final int GRANT_INSTALL = 2;
511
512    /** Permission grant: grant the permission as a runtime one. */
513    private static final int GRANT_RUNTIME = 3;
514
515    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
516    private static final int GRANT_UPGRADE = 4;
517
518    /** Canonical intent used to identify what counts as a "web browser" app */
519    private static final Intent sBrowserIntent;
520    static {
521        sBrowserIntent = new Intent();
522        sBrowserIntent.setAction(Intent.ACTION_VIEW);
523        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
524        sBrowserIntent.setData(Uri.parse("http:"));
525    }
526
527    /**
528     * The set of all protected actions [i.e. those actions for which a high priority
529     * intent filter is disallowed].
530     */
531    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
532    static {
533        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
534        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
535        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
536        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
537    }
538
539    // Compilation reasons.
540    public static final int REASON_FIRST_BOOT = 0;
541    public static final int REASON_BOOT = 1;
542    public static final int REASON_INSTALL = 2;
543    public static final int REASON_BACKGROUND_DEXOPT = 3;
544    public static final int REASON_AB_OTA = 4;
545    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
546    public static final int REASON_SHARED_APK = 6;
547    public static final int REASON_FORCED_DEXOPT = 7;
548    public static final int REASON_CORE_APP = 8;
549
550    public static final int REASON_LAST = REASON_CORE_APP;
551
552    /** All dangerous permission names in the same order as the events in MetricsEvent */
553    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
554            Manifest.permission.READ_CALENDAR,
555            Manifest.permission.WRITE_CALENDAR,
556            Manifest.permission.CAMERA,
557            Manifest.permission.READ_CONTACTS,
558            Manifest.permission.WRITE_CONTACTS,
559            Manifest.permission.GET_ACCOUNTS,
560            Manifest.permission.ACCESS_FINE_LOCATION,
561            Manifest.permission.ACCESS_COARSE_LOCATION,
562            Manifest.permission.RECORD_AUDIO,
563            Manifest.permission.READ_PHONE_STATE,
564            Manifest.permission.CALL_PHONE,
565            Manifest.permission.READ_CALL_LOG,
566            Manifest.permission.WRITE_CALL_LOG,
567            Manifest.permission.ADD_VOICEMAIL,
568            Manifest.permission.USE_SIP,
569            Manifest.permission.PROCESS_OUTGOING_CALLS,
570            Manifest.permission.READ_CELL_BROADCASTS,
571            Manifest.permission.BODY_SENSORS,
572            Manifest.permission.SEND_SMS,
573            Manifest.permission.RECEIVE_SMS,
574            Manifest.permission.READ_SMS,
575            Manifest.permission.RECEIVE_WAP_PUSH,
576            Manifest.permission.RECEIVE_MMS,
577            Manifest.permission.READ_EXTERNAL_STORAGE,
578            Manifest.permission.WRITE_EXTERNAL_STORAGE,
579            Manifest.permission.READ_PHONE_NUMBER);
580
581
582    /**
583     * Version number for the package parser cache. Increment this whenever the format or
584     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
585     */
586    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
587
588    /**
589     * Whether the package parser cache is enabled.
590     */
591    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
592
593    final ServiceThread mHandlerThread;
594
595    final PackageHandler mHandler;
596
597    private final ProcessLoggingHandler mProcessLoggingHandler;
598
599    /**
600     * Messages for {@link #mHandler} that need to wait for system ready before
601     * being dispatched.
602     */
603    private ArrayList<Message> mPostSystemReadyMessages;
604
605    final int mSdkVersion = Build.VERSION.SDK_INT;
606
607    final Context mContext;
608    final boolean mFactoryTest;
609    final boolean mOnlyCore;
610    final DisplayMetrics mMetrics;
611    final int mDefParseFlags;
612    final String[] mSeparateProcesses;
613    final boolean mIsUpgrade;
614    final boolean mIsPreNUpgrade;
615    final boolean mIsPreNMR1Upgrade;
616
617    @GuardedBy("mPackages")
618    private boolean mDexOptDialogShown;
619
620    /** The location for ASEC container files on internal storage. */
621    final String mAsecInternalPath;
622
623    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
624    // LOCK HELD.  Can be called with mInstallLock held.
625    @GuardedBy("mInstallLock")
626    final Installer mInstaller;
627
628    /** Directory where installed third-party apps stored */
629    final File mAppInstallDir;
630    final File mEphemeralInstallDir;
631
632    /**
633     * Directory to which applications installed internally have their
634     * 32 bit native libraries copied.
635     */
636    private File mAppLib32InstallDir;
637
638    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
639    // apps.
640    final File mDrmAppPrivateInstallDir;
641
642    // ----------------------------------------------------------------
643
644    // Lock for state used when installing and doing other long running
645    // operations.  Methods that must be called with this lock held have
646    // the suffix "LI".
647    final Object mInstallLock = new Object();
648
649    // ----------------------------------------------------------------
650
651    // Keys are String (package name), values are Package.  This also serves
652    // as the lock for the global state.  Methods that must be called with
653    // this lock held have the prefix "LP".
654    @GuardedBy("mPackages")
655    final ArrayMap<String, PackageParser.Package> mPackages =
656            new ArrayMap<String, PackageParser.Package>();
657
658    final ArrayMap<String, Set<String>> mKnownCodebase =
659            new ArrayMap<String, Set<String>>();
660
661    // Tracks available target package names -> overlay package paths.
662    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
663        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
664
665    /**
666     * Tracks new system packages [received in an OTA] that we expect to
667     * find updated user-installed versions. Keys are package name, values
668     * are package location.
669     */
670    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
671    /**
672     * Tracks high priority intent filters for protected actions. During boot, certain
673     * filter actions are protected and should never be allowed to have a high priority
674     * intent filter for them. However, there is one, and only one exception -- the
675     * setup wizard. It must be able to define a high priority intent filter for these
676     * actions to ensure there are no escapes from the wizard. We need to delay processing
677     * of these during boot as we need to look at all of the system packages in order
678     * to know which component is the setup wizard.
679     */
680    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
681    /**
682     * Whether or not processing protected filters should be deferred.
683     */
684    private boolean mDeferProtectedFilters = true;
685
686    /**
687     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
688     */
689    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
690    /**
691     * Whether or not system app permissions should be promoted from install to runtime.
692     */
693    boolean mPromoteSystemApps;
694
695    @GuardedBy("mPackages")
696    final Settings mSettings;
697
698    /**
699     * Set of package names that are currently "frozen", which means active
700     * surgery is being done on the code/data for that package. The platform
701     * will refuse to launch frozen packages to avoid race conditions.
702     *
703     * @see PackageFreezer
704     */
705    @GuardedBy("mPackages")
706    final ArraySet<String> mFrozenPackages = new ArraySet<>();
707
708    final ProtectedPackages mProtectedPackages;
709
710    boolean mFirstBoot;
711
712    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
713
714    // System configuration read by SystemConfig.
715    final int[] mGlobalGids;
716    final SparseArray<ArraySet<String>> mSystemPermissions;
717    @GuardedBy("mAvailableFeatures")
718    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
719
720    // If mac_permissions.xml was found for seinfo labeling.
721    boolean mFoundPolicyFile;
722
723    private final InstantAppRegistry mInstantAppRegistry;
724
725    @GuardedBy("mPackages")
726    int mChangedPackagesSequenceNumber;
727    /**
728     * List of changed [installed, removed or updated] packages.
729     * mapping from user id -> sequence number -> package name
730     */
731    @GuardedBy("mPackages")
732    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
733    /**
734     * The sequence number of the last change to a package.
735     * mapping from user id -> package name -> sequence number
736     */
737    @GuardedBy("mPackages")
738    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
739
740    public static final class SharedLibraryEntry {
741        public final String path;
742        public final String apk;
743        public final SharedLibraryInfo info;
744
745        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
746                String declaringPackageName, int declaringPackageVersionCode) {
747            path = _path;
748            apk = _apk;
749            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
750                    declaringPackageName, declaringPackageVersionCode), null);
751        }
752    }
753
754    // Currently known shared libraries.
755    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
756    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
757            new ArrayMap<>();
758
759    // All available activities, for your resolving pleasure.
760    final ActivityIntentResolver mActivities =
761            new ActivityIntentResolver();
762
763    // All available receivers, for your resolving pleasure.
764    final ActivityIntentResolver mReceivers =
765            new ActivityIntentResolver();
766
767    // All available services, for your resolving pleasure.
768    final ServiceIntentResolver mServices = new ServiceIntentResolver();
769
770    // All available providers, for your resolving pleasure.
771    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
772
773    // Mapping from provider base names (first directory in content URI codePath)
774    // to the provider information.
775    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
776            new ArrayMap<String, PackageParser.Provider>();
777
778    // Mapping from instrumentation class names to info about them.
779    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
780            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
781
782    // Mapping from permission names to info about them.
783    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
784            new ArrayMap<String, PackageParser.PermissionGroup>();
785
786    // Packages whose data we have transfered into another package, thus
787    // should no longer exist.
788    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
789
790    // Broadcast actions that are only available to the system.
791    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
792
793    /** List of packages waiting for verification. */
794    final SparseArray<PackageVerificationState> mPendingVerification
795            = new SparseArray<PackageVerificationState>();
796
797    /** Set of packages associated with each app op permission. */
798    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
799
800    final PackageInstallerService mInstallerService;
801
802    private final PackageDexOptimizer mPackageDexOptimizer;
803    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
804    // is used by other apps).
805    private final DexManager mDexManager;
806
807    private AtomicInteger mNextMoveId = new AtomicInteger();
808    private final MoveCallbacks mMoveCallbacks;
809
810    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
811
812    // Cache of users who need badging.
813    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
814
815    /** Token for keys in mPendingVerification. */
816    private int mPendingVerificationToken = 0;
817
818    volatile boolean mSystemReady;
819    volatile boolean mSafeMode;
820    volatile boolean mHasSystemUidErrors;
821
822    ApplicationInfo mAndroidApplication;
823    final ActivityInfo mResolveActivity = new ActivityInfo();
824    final ResolveInfo mResolveInfo = new ResolveInfo();
825    ComponentName mResolveComponentName;
826    PackageParser.Package mPlatformPackage;
827    ComponentName mCustomResolverComponentName;
828
829    boolean mResolverReplaced = false;
830
831    private final @Nullable ComponentName mIntentFilterVerifierComponent;
832    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
833
834    private int mIntentFilterVerificationToken = 0;
835
836    /** The service connection to the ephemeral resolver */
837    final EphemeralResolverConnection mEphemeralResolverConnection;
838
839    /** Component used to install ephemeral applications */
840    ComponentName mEphemeralInstallerComponent;
841    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
842    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
843
844    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
845            = new SparseArray<IntentFilterVerificationState>();
846
847    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
848
849    // List of packages names to keep cached, even if they are uninstalled for all users
850    private List<String> mKeepUninstalledPackages;
851
852    private UserManagerInternal mUserManagerInternal;
853
854    private File mCacheDir;
855
856    private ArraySet<String> mPrivappPermissionsViolations;
857
858    private static class IFVerificationParams {
859        PackageParser.Package pkg;
860        boolean replacing;
861        int userId;
862        int verifierUid;
863
864        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
865                int _userId, int _verifierUid) {
866            pkg = _pkg;
867            replacing = _replacing;
868            userId = _userId;
869            replacing = _replacing;
870            verifierUid = _verifierUid;
871        }
872    }
873
874    private interface IntentFilterVerifier<T extends IntentFilter> {
875        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
876                                               T filter, String packageName);
877        void startVerifications(int userId);
878        void receiveVerificationResponse(int verificationId);
879    }
880
881    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
882        private Context mContext;
883        private ComponentName mIntentFilterVerifierComponent;
884        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
885
886        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
887            mContext = context;
888            mIntentFilterVerifierComponent = verifierComponent;
889        }
890
891        private String getDefaultScheme() {
892            return IntentFilter.SCHEME_HTTPS;
893        }
894
895        @Override
896        public void startVerifications(int userId) {
897            // Launch verifications requests
898            int count = mCurrentIntentFilterVerifications.size();
899            for (int n=0; n<count; n++) {
900                int verificationId = mCurrentIntentFilterVerifications.get(n);
901                final IntentFilterVerificationState ivs =
902                        mIntentFilterVerificationStates.get(verificationId);
903
904                String packageName = ivs.getPackageName();
905
906                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
907                final int filterCount = filters.size();
908                ArraySet<String> domainsSet = new ArraySet<>();
909                for (int m=0; m<filterCount; m++) {
910                    PackageParser.ActivityIntentInfo filter = filters.get(m);
911                    domainsSet.addAll(filter.getHostsList());
912                }
913                synchronized (mPackages) {
914                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
915                            packageName, domainsSet) != null) {
916                        scheduleWriteSettingsLocked();
917                    }
918                }
919                sendVerificationRequest(userId, verificationId, ivs);
920            }
921            mCurrentIntentFilterVerifications.clear();
922        }
923
924        private void sendVerificationRequest(int userId, int verificationId,
925                IntentFilterVerificationState ivs) {
926
927            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
928            verificationIntent.putExtra(
929                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
930                    verificationId);
931            verificationIntent.putExtra(
932                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
933                    getDefaultScheme());
934            verificationIntent.putExtra(
935                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
936                    ivs.getHostsString());
937            verificationIntent.putExtra(
938                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
939                    ivs.getPackageName());
940            verificationIntent.setComponent(mIntentFilterVerifierComponent);
941            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
942
943            UserHandle user = new UserHandle(userId);
944            mContext.sendBroadcastAsUser(verificationIntent, user);
945            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
946                    "Sending IntentFilter verification broadcast");
947        }
948
949        public void receiveVerificationResponse(int verificationId) {
950            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
951
952            final boolean verified = ivs.isVerified();
953
954            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
955            final int count = filters.size();
956            if (DEBUG_DOMAIN_VERIFICATION) {
957                Slog.i(TAG, "Received verification response " + verificationId
958                        + " for " + count + " filters, verified=" + verified);
959            }
960            for (int n=0; n<count; n++) {
961                PackageParser.ActivityIntentInfo filter = filters.get(n);
962                filter.setVerified(verified);
963
964                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
965                        + " verified with result:" + verified + " and hosts:"
966                        + ivs.getHostsString());
967            }
968
969            mIntentFilterVerificationStates.remove(verificationId);
970
971            final String packageName = ivs.getPackageName();
972            IntentFilterVerificationInfo ivi = null;
973
974            synchronized (mPackages) {
975                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
976            }
977            if (ivi == null) {
978                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
979                        + verificationId + " packageName:" + packageName);
980                return;
981            }
982            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
983                    "Updating IntentFilterVerificationInfo for package " + packageName
984                            +" verificationId:" + verificationId);
985
986            synchronized (mPackages) {
987                if (verified) {
988                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
989                } else {
990                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
991                }
992                scheduleWriteSettingsLocked();
993
994                final int userId = ivs.getUserId();
995                if (userId != UserHandle.USER_ALL) {
996                    final int userStatus =
997                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
998
999                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1000                    boolean needUpdate = false;
1001
1002                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1003                    // already been set by the User thru the Disambiguation dialog
1004                    switch (userStatus) {
1005                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1006                            if (verified) {
1007                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1008                            } else {
1009                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1010                            }
1011                            needUpdate = true;
1012                            break;
1013
1014                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1015                            if (verified) {
1016                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1017                                needUpdate = true;
1018                            }
1019                            break;
1020
1021                        default:
1022                            // Nothing to do
1023                    }
1024
1025                    if (needUpdate) {
1026                        mSettings.updateIntentFilterVerificationStatusLPw(
1027                                packageName, updatedStatus, userId);
1028                        scheduleWritePackageRestrictionsLocked(userId);
1029                    }
1030                }
1031            }
1032        }
1033
1034        @Override
1035        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1036                    ActivityIntentInfo filter, String packageName) {
1037            if (!hasValidDomains(filter)) {
1038                return false;
1039            }
1040            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1041            if (ivs == null) {
1042                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1043                        packageName);
1044            }
1045            if (DEBUG_DOMAIN_VERIFICATION) {
1046                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1047            }
1048            ivs.addFilter(filter);
1049            return true;
1050        }
1051
1052        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1053                int userId, int verificationId, String packageName) {
1054            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1055                    verifierUid, userId, packageName);
1056            ivs.setPendingState();
1057            synchronized (mPackages) {
1058                mIntentFilterVerificationStates.append(verificationId, ivs);
1059                mCurrentIntentFilterVerifications.add(verificationId);
1060            }
1061            return ivs;
1062        }
1063    }
1064
1065    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1066        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1067                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1068                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1069    }
1070
1071    // Set of pending broadcasts for aggregating enable/disable of components.
1072    static class PendingPackageBroadcasts {
1073        // for each user id, a map of <package name -> components within that package>
1074        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1075
1076        public PendingPackageBroadcasts() {
1077            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1078        }
1079
1080        public ArrayList<String> get(int userId, String packageName) {
1081            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1082            return packages.get(packageName);
1083        }
1084
1085        public void put(int userId, String packageName, ArrayList<String> components) {
1086            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1087            packages.put(packageName, components);
1088        }
1089
1090        public void remove(int userId, String packageName) {
1091            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1092            if (packages != null) {
1093                packages.remove(packageName);
1094            }
1095        }
1096
1097        public void remove(int userId) {
1098            mUidMap.remove(userId);
1099        }
1100
1101        public int userIdCount() {
1102            return mUidMap.size();
1103        }
1104
1105        public int userIdAt(int n) {
1106            return mUidMap.keyAt(n);
1107        }
1108
1109        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1110            return mUidMap.get(userId);
1111        }
1112
1113        public int size() {
1114            // total number of pending broadcast entries across all userIds
1115            int num = 0;
1116            for (int i = 0; i< mUidMap.size(); i++) {
1117                num += mUidMap.valueAt(i).size();
1118            }
1119            return num;
1120        }
1121
1122        public void clear() {
1123            mUidMap.clear();
1124        }
1125
1126        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1127            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1128            if (map == null) {
1129                map = new ArrayMap<String, ArrayList<String>>();
1130                mUidMap.put(userId, map);
1131            }
1132            return map;
1133        }
1134    }
1135    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1136
1137    // Service Connection to remote media container service to copy
1138    // package uri's from external media onto secure containers
1139    // or internal storage.
1140    private IMediaContainerService mContainerService = null;
1141
1142    static final int SEND_PENDING_BROADCAST = 1;
1143    static final int MCS_BOUND = 3;
1144    static final int END_COPY = 4;
1145    static final int INIT_COPY = 5;
1146    static final int MCS_UNBIND = 6;
1147    static final int START_CLEANING_PACKAGE = 7;
1148    static final int FIND_INSTALL_LOC = 8;
1149    static final int POST_INSTALL = 9;
1150    static final int MCS_RECONNECT = 10;
1151    static final int MCS_GIVE_UP = 11;
1152    static final int UPDATED_MEDIA_STATUS = 12;
1153    static final int WRITE_SETTINGS = 13;
1154    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1155    static final int PACKAGE_VERIFIED = 15;
1156    static final int CHECK_PENDING_VERIFICATION = 16;
1157    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1158    static final int INTENT_FILTER_VERIFIED = 18;
1159    static final int WRITE_PACKAGE_LIST = 19;
1160    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1161
1162    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1163
1164    // Delay time in millisecs
1165    static final int BROADCAST_DELAY = 10 * 1000;
1166
1167    static UserManagerService sUserManager;
1168
1169    // Stores a list of users whose package restrictions file needs to be updated
1170    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1171
1172    final private DefaultContainerConnection mDefContainerConn =
1173            new DefaultContainerConnection();
1174    class DefaultContainerConnection implements ServiceConnection {
1175        public void onServiceConnected(ComponentName name, IBinder service) {
1176            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1177            final IMediaContainerService imcs = IMediaContainerService.Stub
1178                    .asInterface(Binder.allowBlocking(service));
1179            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1180        }
1181
1182        public void onServiceDisconnected(ComponentName name) {
1183            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1184        }
1185    }
1186
1187    // Recordkeeping of restore-after-install operations that are currently in flight
1188    // between the Package Manager and the Backup Manager
1189    static class PostInstallData {
1190        public InstallArgs args;
1191        public PackageInstalledInfo res;
1192
1193        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1194            args = _a;
1195            res = _r;
1196        }
1197    }
1198
1199    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1200    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1201
1202    // XML tags for backup/restore of various bits of state
1203    private static final String TAG_PREFERRED_BACKUP = "pa";
1204    private static final String TAG_DEFAULT_APPS = "da";
1205    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1206
1207    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1208    private static final String TAG_ALL_GRANTS = "rt-grants";
1209    private static final String TAG_GRANT = "grant";
1210    private static final String ATTR_PACKAGE_NAME = "pkg";
1211
1212    private static final String TAG_PERMISSION = "perm";
1213    private static final String ATTR_PERMISSION_NAME = "name";
1214    private static final String ATTR_IS_GRANTED = "g";
1215    private static final String ATTR_USER_SET = "set";
1216    private static final String ATTR_USER_FIXED = "fixed";
1217    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1218
1219    // System/policy permission grants are not backed up
1220    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1221            FLAG_PERMISSION_POLICY_FIXED
1222            | FLAG_PERMISSION_SYSTEM_FIXED
1223            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1224
1225    // And we back up these user-adjusted states
1226    private static final int USER_RUNTIME_GRANT_MASK =
1227            FLAG_PERMISSION_USER_SET
1228            | FLAG_PERMISSION_USER_FIXED
1229            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1230
1231    final @Nullable String mRequiredVerifierPackage;
1232    final @NonNull String mRequiredInstallerPackage;
1233    final @NonNull String mRequiredUninstallerPackage;
1234    final @Nullable String mSetupWizardPackage;
1235    final @Nullable String mStorageManagerPackage;
1236    final @NonNull String mServicesSystemSharedLibraryPackageName;
1237    final @NonNull String mSharedSystemSharedLibraryPackageName;
1238
1239    final boolean mPermissionReviewRequired;
1240
1241    private final PackageUsage mPackageUsage = new PackageUsage();
1242    private final CompilerStats mCompilerStats = new CompilerStats();
1243
1244    class PackageHandler extends Handler {
1245        private boolean mBound = false;
1246        final ArrayList<HandlerParams> mPendingInstalls =
1247            new ArrayList<HandlerParams>();
1248
1249        private boolean connectToService() {
1250            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1251                    " DefaultContainerService");
1252            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1253            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1254            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1255                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1256                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1257                mBound = true;
1258                return true;
1259            }
1260            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1261            return false;
1262        }
1263
1264        private void disconnectService() {
1265            mContainerService = null;
1266            mBound = false;
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1268            mContext.unbindService(mDefContainerConn);
1269            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1270        }
1271
1272        PackageHandler(Looper looper) {
1273            super(looper);
1274        }
1275
1276        public void handleMessage(Message msg) {
1277            try {
1278                doHandleMessage(msg);
1279            } finally {
1280                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1281            }
1282        }
1283
1284        void doHandleMessage(Message msg) {
1285            switch (msg.what) {
1286                case INIT_COPY: {
1287                    HandlerParams params = (HandlerParams) msg.obj;
1288                    int idx = mPendingInstalls.size();
1289                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1290                    // If a bind was already initiated we dont really
1291                    // need to do anything. The pending install
1292                    // will be processed later on.
1293                    if (!mBound) {
1294                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1295                                System.identityHashCode(mHandler));
1296                        // If this is the only one pending we might
1297                        // have to bind to the service again.
1298                        if (!connectToService()) {
1299                            Slog.e(TAG, "Failed to bind to media container service");
1300                            params.serviceError();
1301                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1302                                    System.identityHashCode(mHandler));
1303                            if (params.traceMethod != null) {
1304                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1305                                        params.traceCookie);
1306                            }
1307                            return;
1308                        } else {
1309                            // Once we bind to the service, the first
1310                            // pending request will be processed.
1311                            mPendingInstalls.add(idx, params);
1312                        }
1313                    } else {
1314                        mPendingInstalls.add(idx, params);
1315                        // Already bound to the service. Just make
1316                        // sure we trigger off processing the first request.
1317                        if (idx == 0) {
1318                            mHandler.sendEmptyMessage(MCS_BOUND);
1319                        }
1320                    }
1321                    break;
1322                }
1323                case MCS_BOUND: {
1324                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1325                    if (msg.obj != null) {
1326                        mContainerService = (IMediaContainerService) msg.obj;
1327                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1328                                System.identityHashCode(mHandler));
1329                    }
1330                    if (mContainerService == null) {
1331                        if (!mBound) {
1332                            // Something seriously wrong since we are not bound and we are not
1333                            // waiting for connection. Bail out.
1334                            Slog.e(TAG, "Cannot bind to media container service");
1335                            for (HandlerParams params : mPendingInstalls) {
1336                                // Indicate service bind error
1337                                params.serviceError();
1338                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339                                        System.identityHashCode(params));
1340                                if (params.traceMethod != null) {
1341                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1342                                            params.traceMethod, params.traceCookie);
1343                                }
1344                                return;
1345                            }
1346                            mPendingInstalls.clear();
1347                        } else {
1348                            Slog.w(TAG, "Waiting to connect to media container service");
1349                        }
1350                    } else if (mPendingInstalls.size() > 0) {
1351                        HandlerParams params = mPendingInstalls.get(0);
1352                        if (params != null) {
1353                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1354                                    System.identityHashCode(params));
1355                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1356                            if (params.startCopy()) {
1357                                // We are done...  look for more work or to
1358                                // go idle.
1359                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1360                                        "Checking for more work or unbind...");
1361                                // Delete pending install
1362                                if (mPendingInstalls.size() > 0) {
1363                                    mPendingInstalls.remove(0);
1364                                }
1365                                if (mPendingInstalls.size() == 0) {
1366                                    if (mBound) {
1367                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1368                                                "Posting delayed MCS_UNBIND");
1369                                        removeMessages(MCS_UNBIND);
1370                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1371                                        // Unbind after a little delay, to avoid
1372                                        // continual thrashing.
1373                                        sendMessageDelayed(ubmsg, 10000);
1374                                    }
1375                                } else {
1376                                    // There are more pending requests in queue.
1377                                    // Just post MCS_BOUND message to trigger processing
1378                                    // of next pending install.
1379                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1380                                            "Posting MCS_BOUND for next work");
1381                                    mHandler.sendEmptyMessage(MCS_BOUND);
1382                                }
1383                            }
1384                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1385                        }
1386                    } else {
1387                        // Should never happen ideally.
1388                        Slog.w(TAG, "Empty queue");
1389                    }
1390                    break;
1391                }
1392                case MCS_RECONNECT: {
1393                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1394                    if (mPendingInstalls.size() > 0) {
1395                        if (mBound) {
1396                            disconnectService();
1397                        }
1398                        if (!connectToService()) {
1399                            Slog.e(TAG, "Failed to bind to media container service");
1400                            for (HandlerParams params : mPendingInstalls) {
1401                                // Indicate service bind error
1402                                params.serviceError();
1403                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1404                                        System.identityHashCode(params));
1405                            }
1406                            mPendingInstalls.clear();
1407                        }
1408                    }
1409                    break;
1410                }
1411                case MCS_UNBIND: {
1412                    // If there is no actual work left, then time to unbind.
1413                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1414
1415                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1416                        if (mBound) {
1417                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1418
1419                            disconnectService();
1420                        }
1421                    } else if (mPendingInstalls.size() > 0) {
1422                        // There are more pending requests in queue.
1423                        // Just post MCS_BOUND message to trigger processing
1424                        // of next pending install.
1425                        mHandler.sendEmptyMessage(MCS_BOUND);
1426                    }
1427
1428                    break;
1429                }
1430                case MCS_GIVE_UP: {
1431                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1432                    HandlerParams params = mPendingInstalls.remove(0);
1433                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1434                            System.identityHashCode(params));
1435                    break;
1436                }
1437                case SEND_PENDING_BROADCAST: {
1438                    String packages[];
1439                    ArrayList<String> components[];
1440                    int size = 0;
1441                    int uids[];
1442                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1443                    synchronized (mPackages) {
1444                        if (mPendingBroadcasts == null) {
1445                            return;
1446                        }
1447                        size = mPendingBroadcasts.size();
1448                        if (size <= 0) {
1449                            // Nothing to be done. Just return
1450                            return;
1451                        }
1452                        packages = new String[size];
1453                        components = new ArrayList[size];
1454                        uids = new int[size];
1455                        int i = 0;  // filling out the above arrays
1456
1457                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1458                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1459                            Iterator<Map.Entry<String, ArrayList<String>>> it
1460                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1461                                            .entrySet().iterator();
1462                            while (it.hasNext() && i < size) {
1463                                Map.Entry<String, ArrayList<String>> ent = it.next();
1464                                packages[i] = ent.getKey();
1465                                components[i] = ent.getValue();
1466                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1467                                uids[i] = (ps != null)
1468                                        ? UserHandle.getUid(packageUserId, ps.appId)
1469                                        : -1;
1470                                i++;
1471                            }
1472                        }
1473                        size = i;
1474                        mPendingBroadcasts.clear();
1475                    }
1476                    // Send broadcasts
1477                    for (int i = 0; i < size; i++) {
1478                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1479                    }
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1481                    break;
1482                }
1483                case START_CLEANING_PACKAGE: {
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1485                    final String packageName = (String)msg.obj;
1486                    final int userId = msg.arg1;
1487                    final boolean andCode = msg.arg2 != 0;
1488                    synchronized (mPackages) {
1489                        if (userId == UserHandle.USER_ALL) {
1490                            int[] users = sUserManager.getUserIds();
1491                            for (int user : users) {
1492                                mSettings.addPackageToCleanLPw(
1493                                        new PackageCleanItem(user, packageName, andCode));
1494                            }
1495                        } else {
1496                            mSettings.addPackageToCleanLPw(
1497                                    new PackageCleanItem(userId, packageName, andCode));
1498                        }
1499                    }
1500                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1501                    startCleaningPackages();
1502                } break;
1503                case POST_INSTALL: {
1504                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1505
1506                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1507                    final boolean didRestore = (msg.arg2 != 0);
1508                    mRunningInstalls.delete(msg.arg1);
1509
1510                    if (data != null) {
1511                        InstallArgs args = data.args;
1512                        PackageInstalledInfo parentRes = data.res;
1513
1514                        final boolean grantPermissions = (args.installFlags
1515                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1516                        final boolean killApp = (args.installFlags
1517                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1518                        final String[] grantedPermissions = args.installGrantPermissions;
1519
1520                        // Handle the parent package
1521                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1522                                grantedPermissions, didRestore, args.installerPackageName,
1523                                args.observer);
1524
1525                        // Handle the child packages
1526                        final int childCount = (parentRes.addedChildPackages != null)
1527                                ? parentRes.addedChildPackages.size() : 0;
1528                        for (int i = 0; i < childCount; i++) {
1529                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1530                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1531                                    grantedPermissions, false, args.installerPackageName,
1532                                    args.observer);
1533                        }
1534
1535                        // Log tracing if needed
1536                        if (args.traceMethod != null) {
1537                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1538                                    args.traceCookie);
1539                        }
1540                    } else {
1541                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1542                    }
1543
1544                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1545                } break;
1546                case UPDATED_MEDIA_STATUS: {
1547                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1548                    boolean reportStatus = msg.arg1 == 1;
1549                    boolean doGc = msg.arg2 == 1;
1550                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1551                    if (doGc) {
1552                        // Force a gc to clear up stale containers.
1553                        Runtime.getRuntime().gc();
1554                    }
1555                    if (msg.obj != null) {
1556                        @SuppressWarnings("unchecked")
1557                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1558                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1559                        // Unload containers
1560                        unloadAllContainers(args);
1561                    }
1562                    if (reportStatus) {
1563                        try {
1564                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1565                                    "Invoking StorageManagerService call back");
1566                            PackageHelper.getStorageManager().finishMediaUpdate();
1567                        } catch (RemoteException e) {
1568                            Log.e(TAG, "StorageManagerService not running?");
1569                        }
1570                    }
1571                } break;
1572                case WRITE_SETTINGS: {
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    synchronized (mPackages) {
1575                        removeMessages(WRITE_SETTINGS);
1576                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1577                        mSettings.writeLPr();
1578                        mDirtyUsers.clear();
1579                    }
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1581                } break;
1582                case WRITE_PACKAGE_RESTRICTIONS: {
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1586                        for (int userId : mDirtyUsers) {
1587                            mSettings.writePackageRestrictionsLPr(userId);
1588                        }
1589                        mDirtyUsers.clear();
1590                    }
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1592                } break;
1593                case WRITE_PACKAGE_LIST: {
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        removeMessages(WRITE_PACKAGE_LIST);
1597                        mSettings.writePackageListLPr(msg.arg1);
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case CHECK_PENDING_VERIFICATION: {
1602                    final int verificationId = msg.arg1;
1603                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1604
1605                    if ((state != null) && !state.timeoutExtended()) {
1606                        final InstallArgs args = state.getInstallArgs();
1607                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1608
1609                        Slog.i(TAG, "Verification timed out for " + originUri);
1610                        mPendingVerification.remove(verificationId);
1611
1612                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1613
1614                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1615                            Slog.i(TAG, "Continuing with installation of " + originUri);
1616                            state.setVerifierResponse(Binder.getCallingUid(),
1617                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1618                            broadcastPackageVerified(verificationId, originUri,
1619                                    PackageManager.VERIFICATION_ALLOW,
1620                                    state.getInstallArgs().getUser());
1621                            try {
1622                                ret = args.copyApk(mContainerService, true);
1623                            } catch (RemoteException e) {
1624                                Slog.e(TAG, "Could not contact the ContainerService");
1625                            }
1626                        } else {
1627                            broadcastPackageVerified(verificationId, originUri,
1628                                    PackageManager.VERIFICATION_REJECT,
1629                                    state.getInstallArgs().getUser());
1630                        }
1631
1632                        Trace.asyncTraceEnd(
1633                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1634
1635                        processPendingInstall(args, ret);
1636                        mHandler.sendEmptyMessage(MCS_UNBIND);
1637                    }
1638                    break;
1639                }
1640                case PACKAGE_VERIFIED: {
1641                    final int verificationId = msg.arg1;
1642
1643                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1644                    if (state == null) {
1645                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1646                        break;
1647                    }
1648
1649                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1650
1651                    state.setVerifierResponse(response.callerUid, response.code);
1652
1653                    if (state.isVerificationComplete()) {
1654                        mPendingVerification.remove(verificationId);
1655
1656                        final InstallArgs args = state.getInstallArgs();
1657                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1658
1659                        int ret;
1660                        if (state.isInstallAllowed()) {
1661                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1662                            broadcastPackageVerified(verificationId, originUri,
1663                                    response.code, state.getInstallArgs().getUser());
1664                            try {
1665                                ret = args.copyApk(mContainerService, true);
1666                            } catch (RemoteException e) {
1667                                Slog.e(TAG, "Could not contact the ContainerService");
1668                            }
1669                        } else {
1670                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1671                        }
1672
1673                        Trace.asyncTraceEnd(
1674                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1675
1676                        processPendingInstall(args, ret);
1677                        mHandler.sendEmptyMessage(MCS_UNBIND);
1678                    }
1679
1680                    break;
1681                }
1682                case START_INTENT_FILTER_VERIFICATIONS: {
1683                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1684                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1685                            params.replacing, params.pkg);
1686                    break;
1687                }
1688                case INTENT_FILTER_VERIFIED: {
1689                    final int verificationId = msg.arg1;
1690
1691                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1692                            verificationId);
1693                    if (state == null) {
1694                        Slog.w(TAG, "Invalid IntentFilter verification token "
1695                                + verificationId + " received");
1696                        break;
1697                    }
1698
1699                    final int userId = state.getUserId();
1700
1701                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1702                            "Processing IntentFilter verification with token:"
1703                            + verificationId + " and userId:" + userId);
1704
1705                    final IntentFilterVerificationResponse response =
1706                            (IntentFilterVerificationResponse) msg.obj;
1707
1708                    state.setVerifierResponse(response.callerUid, response.code);
1709
1710                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1711                            "IntentFilter verification with token:" + verificationId
1712                            + " and userId:" + userId
1713                            + " is settings verifier response with response code:"
1714                            + response.code);
1715
1716                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1717                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1718                                + response.getFailedDomainsString());
1719                    }
1720
1721                    if (state.isVerificationComplete()) {
1722                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1723                    } else {
1724                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1725                                "IntentFilter verification with token:" + verificationId
1726                                + " was not said to be complete");
1727                    }
1728
1729                    break;
1730                }
1731                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1732                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1733                            mEphemeralResolverConnection,
1734                            (EphemeralRequest) msg.obj,
1735                            mEphemeralInstallerActivity,
1736                            mHandler);
1737                }
1738            }
1739        }
1740    }
1741
1742    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1743            boolean killApp, String[] grantedPermissions,
1744            boolean launchedForRestore, String installerPackage,
1745            IPackageInstallObserver2 installObserver) {
1746        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1747            // Send the removed broadcasts
1748            if (res.removedInfo != null) {
1749                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1750            }
1751
1752            // Now that we successfully installed the package, grant runtime
1753            // permissions if requested before broadcasting the install. Also
1754            // for legacy apps in permission review mode we clear the permission
1755            // review flag which is used to emulate runtime permissions for
1756            // legacy apps.
1757            if (grantPermissions) {
1758                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1759            }
1760
1761            final boolean update = res.removedInfo != null
1762                    && res.removedInfo.removedPackage != null;
1763
1764            // If this is the first time we have child packages for a disabled privileged
1765            // app that had no children, we grant requested runtime permissions to the new
1766            // children if the parent on the system image had them already granted.
1767            if (res.pkg.parentPackage != null) {
1768                synchronized (mPackages) {
1769                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1770                }
1771            }
1772
1773            synchronized (mPackages) {
1774                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1775            }
1776
1777            final String packageName = res.pkg.applicationInfo.packageName;
1778
1779            // Determine the set of users who are adding this package for
1780            // the first time vs. those who are seeing an update.
1781            int[] firstUsers = EMPTY_INT_ARRAY;
1782            int[] updateUsers = EMPTY_INT_ARRAY;
1783            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1784            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1785            for (int newUser : res.newUsers) {
1786                if (ps.getInstantApp(newUser)) {
1787                    continue;
1788                }
1789                if (allNewUsers) {
1790                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1791                    continue;
1792                }
1793                boolean isNew = true;
1794                for (int origUser : res.origUsers) {
1795                    if (origUser == newUser) {
1796                        isNew = false;
1797                        break;
1798                    }
1799                }
1800                if (isNew) {
1801                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1802                } else {
1803                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1804                }
1805            }
1806
1807            // Send installed broadcasts if the package is not a static shared lib.
1808            if (res.pkg.staticSharedLibName == null) {
1809                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1810
1811                // Send added for users that see the package for the first time
1812                // sendPackageAddedForNewUsers also deals with system apps
1813                int appId = UserHandle.getAppId(res.uid);
1814                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1815                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1816
1817                // Send added for users that don't see the package for the first time
1818                Bundle extras = new Bundle(1);
1819                extras.putInt(Intent.EXTRA_UID, res.uid);
1820                if (update) {
1821                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1822                }
1823                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1824                        extras, 0 /*flags*/, null /*targetPackage*/,
1825                        null /*finishedReceiver*/, updateUsers);
1826
1827                // Send replaced for users that don't see the package for the first time
1828                if (update) {
1829                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1830                            packageName, extras, 0 /*flags*/,
1831                            null /*targetPackage*/, null /*finishedReceiver*/,
1832                            updateUsers);
1833                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1834                            null /*package*/, null /*extras*/, 0 /*flags*/,
1835                            packageName /*targetPackage*/,
1836                            null /*finishedReceiver*/, updateUsers);
1837                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1838                    // First-install and we did a restore, so we're responsible for the
1839                    // first-launch broadcast.
1840                    if (DEBUG_BACKUP) {
1841                        Slog.i(TAG, "Post-restore of " + packageName
1842                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1843                    }
1844                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1845                }
1846
1847                // Send broadcast package appeared if forward locked/external for all users
1848                // treat asec-hosted packages like removable media on upgrade
1849                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1850                    if (DEBUG_INSTALL) {
1851                        Slog.i(TAG, "upgrading pkg " + res.pkg
1852                                + " is ASEC-hosted -> AVAILABLE");
1853                    }
1854                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1855                    ArrayList<String> pkgList = new ArrayList<>(1);
1856                    pkgList.add(packageName);
1857                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1858                }
1859            }
1860
1861            // Work that needs to happen on first install within each user
1862            if (firstUsers != null && firstUsers.length > 0) {
1863                synchronized (mPackages) {
1864                    for (int userId : firstUsers) {
1865                        // If this app is a browser and it's newly-installed for some
1866                        // users, clear any default-browser state in those users. The
1867                        // app's nature doesn't depend on the user, so we can just check
1868                        // its browser nature in any user and generalize.
1869                        if (packageIsBrowser(packageName, userId)) {
1870                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1871                        }
1872
1873                        // We may also need to apply pending (restored) runtime
1874                        // permission grants within these users.
1875                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1876                    }
1877                }
1878            }
1879
1880            // Log current value of "unknown sources" setting
1881            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1882                    getUnknownSourcesSettings());
1883
1884            // Force a gc to clear up things
1885            Runtime.getRuntime().gc();
1886
1887            // Remove the replaced package's older resources safely now
1888            // We delete after a gc for applications  on sdcard.
1889            if (res.removedInfo != null && res.removedInfo.args != null) {
1890                synchronized (mInstallLock) {
1891                    res.removedInfo.args.doPostDeleteLI(true);
1892                }
1893            }
1894
1895            // Notify DexManager that the package was installed for new users.
1896            // The updated users should already be indexed and the package code paths
1897            // should not change.
1898            // Don't notify the manager for ephemeral apps as they are not expected to
1899            // survive long enough to benefit of background optimizations.
1900            for (int userId : firstUsers) {
1901                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1902                mDexManager.notifyPackageInstalled(info, userId);
1903            }
1904        }
1905
1906        // If someone is watching installs - notify them
1907        if (installObserver != null) {
1908            try {
1909                Bundle extras = extrasForInstallResult(res);
1910                installObserver.onPackageInstalled(res.name, res.returnCode,
1911                        res.returnMsg, extras);
1912            } catch (RemoteException e) {
1913                Slog.i(TAG, "Observer no longer exists.");
1914            }
1915        }
1916    }
1917
1918    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1919            PackageParser.Package pkg) {
1920        if (pkg.parentPackage == null) {
1921            return;
1922        }
1923        if (pkg.requestedPermissions == null) {
1924            return;
1925        }
1926        final PackageSetting disabledSysParentPs = mSettings
1927                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1928        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1929                || !disabledSysParentPs.isPrivileged()
1930                || (disabledSysParentPs.childPackageNames != null
1931                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1932            return;
1933        }
1934        final int[] allUserIds = sUserManager.getUserIds();
1935        final int permCount = pkg.requestedPermissions.size();
1936        for (int i = 0; i < permCount; i++) {
1937            String permission = pkg.requestedPermissions.get(i);
1938            BasePermission bp = mSettings.mPermissions.get(permission);
1939            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1940                continue;
1941            }
1942            for (int userId : allUserIds) {
1943                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1944                        permission, userId)) {
1945                    grantRuntimePermission(pkg.packageName, permission, userId);
1946                }
1947            }
1948        }
1949    }
1950
1951    private StorageEventListener mStorageListener = new StorageEventListener() {
1952        @Override
1953        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1954            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1955                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1956                    final String volumeUuid = vol.getFsUuid();
1957
1958                    // Clean up any users or apps that were removed or recreated
1959                    // while this volume was missing
1960                    sUserManager.reconcileUsers(volumeUuid);
1961                    reconcileApps(volumeUuid);
1962
1963                    // Clean up any install sessions that expired or were
1964                    // cancelled while this volume was missing
1965                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1966
1967                    loadPrivatePackages(vol);
1968
1969                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1970                    unloadPrivatePackages(vol);
1971                }
1972            }
1973
1974            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1975                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1976                    updateExternalMediaStatus(true, false);
1977                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1978                    updateExternalMediaStatus(false, false);
1979                }
1980            }
1981        }
1982
1983        @Override
1984        public void onVolumeForgotten(String fsUuid) {
1985            if (TextUtils.isEmpty(fsUuid)) {
1986                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1987                return;
1988            }
1989
1990            // Remove any apps installed on the forgotten volume
1991            synchronized (mPackages) {
1992                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1993                for (PackageSetting ps : packages) {
1994                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1995                    deletePackageVersioned(new VersionedPackage(ps.name,
1996                            PackageManager.VERSION_CODE_HIGHEST),
1997                            new LegacyPackageDeleteObserver(null).getBinder(),
1998                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1999                    // Try very hard to release any references to this package
2000                    // so we don't risk the system server being killed due to
2001                    // open FDs
2002                    AttributeCache.instance().removePackage(ps.name);
2003                }
2004
2005                mSettings.onVolumeForgotten(fsUuid);
2006                mSettings.writeLPr();
2007            }
2008        }
2009    };
2010
2011    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2012            String[] grantedPermissions) {
2013        for (int userId : userIds) {
2014            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2015        }
2016    }
2017
2018    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2019            String[] grantedPermissions) {
2020        SettingBase sb = (SettingBase) pkg.mExtras;
2021        if (sb == null) {
2022            return;
2023        }
2024
2025        PermissionsState permissionsState = sb.getPermissionsState();
2026
2027        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2028                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2029
2030        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2031                >= Build.VERSION_CODES.M;
2032
2033        for (String permission : pkg.requestedPermissions) {
2034            final BasePermission bp;
2035            synchronized (mPackages) {
2036                bp = mSettings.mPermissions.get(permission);
2037            }
2038            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2039                    && (grantedPermissions == null
2040                           || ArrayUtils.contains(grantedPermissions, permission))) {
2041                final int flags = permissionsState.getPermissionFlags(permission, userId);
2042                if (supportsRuntimePermissions) {
2043                    // Installer cannot change immutable permissions.
2044                    if ((flags & immutableFlags) == 0) {
2045                        grantRuntimePermission(pkg.packageName, permission, userId);
2046                    }
2047                } else if (mPermissionReviewRequired) {
2048                    // In permission review mode we clear the review flag when we
2049                    // are asked to install the app with all permissions granted.
2050                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2051                        updatePermissionFlags(permission, pkg.packageName,
2052                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2053                    }
2054                }
2055            }
2056        }
2057    }
2058
2059    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2060        Bundle extras = null;
2061        switch (res.returnCode) {
2062            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2063                extras = new Bundle();
2064                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2065                        res.origPermission);
2066                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2067                        res.origPackage);
2068                break;
2069            }
2070            case PackageManager.INSTALL_SUCCEEDED: {
2071                extras = new Bundle();
2072                extras.putBoolean(Intent.EXTRA_REPLACING,
2073                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2074                break;
2075            }
2076        }
2077        return extras;
2078    }
2079
2080    void scheduleWriteSettingsLocked() {
2081        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2082            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2083        }
2084    }
2085
2086    void scheduleWritePackageListLocked(int userId) {
2087        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2088            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2089            msg.arg1 = userId;
2090            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2091        }
2092    }
2093
2094    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2095        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2096        scheduleWritePackageRestrictionsLocked(userId);
2097    }
2098
2099    void scheduleWritePackageRestrictionsLocked(int userId) {
2100        final int[] userIds = (userId == UserHandle.USER_ALL)
2101                ? sUserManager.getUserIds() : new int[]{userId};
2102        for (int nextUserId : userIds) {
2103            if (!sUserManager.exists(nextUserId)) return;
2104            mDirtyUsers.add(nextUserId);
2105            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2106                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2107            }
2108        }
2109    }
2110
2111    public static PackageManagerService main(Context context, Installer installer,
2112            boolean factoryTest, boolean onlyCore) {
2113        // Self-check for initial settings.
2114        PackageManagerServiceCompilerMapping.checkProperties();
2115
2116        PackageManagerService m = new PackageManagerService(context, installer,
2117                factoryTest, onlyCore);
2118        m.enableSystemUserPackages();
2119        ServiceManager.addService("package", m);
2120        return m;
2121    }
2122
2123    private void enableSystemUserPackages() {
2124        if (!UserManager.isSplitSystemUser()) {
2125            return;
2126        }
2127        // For system user, enable apps based on the following conditions:
2128        // - app is whitelisted or belong to one of these groups:
2129        //   -- system app which has no launcher icons
2130        //   -- system app which has INTERACT_ACROSS_USERS permission
2131        //   -- system IME app
2132        // - app is not in the blacklist
2133        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2134        Set<String> enableApps = new ArraySet<>();
2135        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2136                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2137                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2138        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2139        enableApps.addAll(wlApps);
2140        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2141                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2142        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2143        enableApps.removeAll(blApps);
2144        Log.i(TAG, "Applications installed for system user: " + enableApps);
2145        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2146                UserHandle.SYSTEM);
2147        final int allAppsSize = allAps.size();
2148        synchronized (mPackages) {
2149            for (int i = 0; i < allAppsSize; i++) {
2150                String pName = allAps.get(i);
2151                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2152                // Should not happen, but we shouldn't be failing if it does
2153                if (pkgSetting == null) {
2154                    continue;
2155                }
2156                boolean install = enableApps.contains(pName);
2157                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2158                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2159                            + " for system user");
2160                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2161                }
2162            }
2163            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2164        }
2165    }
2166
2167    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2168        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2169                Context.DISPLAY_SERVICE);
2170        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2171    }
2172
2173    /**
2174     * Requests that files preopted on a secondary system partition be copied to the data partition
2175     * if possible.  Note that the actual copying of the files is accomplished by init for security
2176     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2177     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2178     */
2179    private static void requestCopyPreoptedFiles() {
2180        final int WAIT_TIME_MS = 100;
2181        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2182        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2183            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2184            // We will wait for up to 100 seconds.
2185            final long timeStart = SystemClock.uptimeMillis();
2186            final long timeEnd = timeStart + 100 * 1000;
2187            long timeNow = timeStart;
2188            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2189                try {
2190                    Thread.sleep(WAIT_TIME_MS);
2191                } catch (InterruptedException e) {
2192                    // Do nothing
2193                }
2194                timeNow = SystemClock.uptimeMillis();
2195                if (timeNow > timeEnd) {
2196                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2197                    Slog.wtf(TAG, "cppreopt did not finish!");
2198                    break;
2199                }
2200            }
2201
2202            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2203        }
2204    }
2205
2206    public PackageManagerService(Context context, Installer installer,
2207            boolean factoryTest, boolean onlyCore) {
2208        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2209        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2210                SystemClock.uptimeMillis());
2211
2212        if (mSdkVersion <= 0) {
2213            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2214        }
2215
2216        mContext = context;
2217
2218        mPermissionReviewRequired = context.getResources().getBoolean(
2219                R.bool.config_permissionReviewRequired);
2220
2221        mFactoryTest = factoryTest;
2222        mOnlyCore = onlyCore;
2223        mMetrics = new DisplayMetrics();
2224        mSettings = new Settings(mPackages);
2225        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2226                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2227        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2228                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2229        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2230                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2231        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2232                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2233        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2234                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2235        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237
2238        String separateProcesses = SystemProperties.get("debug.separate_processes");
2239        if (separateProcesses != null && separateProcesses.length() > 0) {
2240            if ("*".equals(separateProcesses)) {
2241                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2242                mSeparateProcesses = null;
2243                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2244            } else {
2245                mDefParseFlags = 0;
2246                mSeparateProcesses = separateProcesses.split(",");
2247                Slog.w(TAG, "Running with debug.separate_processes: "
2248                        + separateProcesses);
2249            }
2250        } else {
2251            mDefParseFlags = 0;
2252            mSeparateProcesses = null;
2253        }
2254
2255        mInstaller = installer;
2256        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2257                "*dexopt*");
2258        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2259        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2260
2261        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2262                FgThread.get().getLooper());
2263
2264        getDefaultDisplayMetrics(context, mMetrics);
2265
2266        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2267        SystemConfig systemConfig = SystemConfig.getInstance();
2268        mGlobalGids = systemConfig.getGlobalGids();
2269        mSystemPermissions = systemConfig.getSystemPermissions();
2270        mAvailableFeatures = systemConfig.getAvailableFeatures();
2271        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2272
2273        mProtectedPackages = new ProtectedPackages(mContext);
2274
2275        synchronized (mInstallLock) {
2276        // writer
2277        synchronized (mPackages) {
2278            mHandlerThread = new ServiceThread(TAG,
2279                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2280            mHandlerThread.start();
2281            mHandler = new PackageHandler(mHandlerThread.getLooper());
2282            mProcessLoggingHandler = new ProcessLoggingHandler();
2283            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2284
2285            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2286            mInstantAppRegistry = new InstantAppRegistry(this);
2287
2288            File dataDir = Environment.getDataDirectory();
2289            mAppInstallDir = new File(dataDir, "app");
2290            mAppLib32InstallDir = new File(dataDir, "app-lib");
2291            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2292            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2293            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2294            sUserManager = new UserManagerService(context, this,
2295                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2296
2297            // Propagate permission configuration in to package manager.
2298            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2299                    = systemConfig.getPermissions();
2300            for (int i=0; i<permConfig.size(); i++) {
2301                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2302                BasePermission bp = mSettings.mPermissions.get(perm.name);
2303                if (bp == null) {
2304                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2305                    mSettings.mPermissions.put(perm.name, bp);
2306                }
2307                if (perm.gids != null) {
2308                    bp.setGids(perm.gids, perm.perUser);
2309                }
2310            }
2311
2312            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2313            final int builtInLibCount = libConfig.size();
2314            for (int i = 0; i < builtInLibCount; i++) {
2315                String name = libConfig.keyAt(i);
2316                String path = libConfig.valueAt(i);
2317                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2318                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2319            }
2320
2321            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2322
2323            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2324            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2325            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2326
2327            // Clean up orphaned packages for which the code path doesn't exist
2328            // and they are an update to a system app - caused by bug/32321269
2329            final int packageSettingCount = mSettings.mPackages.size();
2330            for (int i = packageSettingCount - 1; i >= 0; i--) {
2331                PackageSetting ps = mSettings.mPackages.valueAt(i);
2332                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2333                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2334                    mSettings.mPackages.removeAt(i);
2335                    mSettings.enableSystemPackageLPw(ps.name);
2336                }
2337            }
2338
2339            if (mFirstBoot) {
2340                requestCopyPreoptedFiles();
2341            }
2342
2343            String customResolverActivity = Resources.getSystem().getString(
2344                    R.string.config_customResolverActivity);
2345            if (TextUtils.isEmpty(customResolverActivity)) {
2346                customResolverActivity = null;
2347            } else {
2348                mCustomResolverComponentName = ComponentName.unflattenFromString(
2349                        customResolverActivity);
2350            }
2351
2352            long startTime = SystemClock.uptimeMillis();
2353
2354            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2355                    startTime);
2356
2357            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2358            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2359
2360            if (bootClassPath == null) {
2361                Slog.w(TAG, "No BOOTCLASSPATH found!");
2362            }
2363
2364            if (systemServerClassPath == null) {
2365                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2366            }
2367
2368            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2369            final String[] dexCodeInstructionSets =
2370                    getDexCodeInstructionSets(
2371                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2372
2373            /**
2374             * Ensure all external libraries have had dexopt run on them.
2375             */
2376            if (mSharedLibraries.size() > 0) {
2377                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2378                // NOTE: For now, we're compiling these system "shared libraries"
2379                // (and framework jars) into all available architectures. It's possible
2380                // to compile them only when we come across an app that uses them (there's
2381                // already logic for that in scanPackageLI) but that adds some complexity.
2382                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2383                    final int libCount = mSharedLibraries.size();
2384                    for (int i = 0; i < libCount; i++) {
2385                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2386                        final int versionCount = versionedLib.size();
2387                        for (int j = 0; j < versionCount; j++) {
2388                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2389                            final String libPath = libEntry.path != null
2390                                    ? libEntry.path : libEntry.apk;
2391                            if (libPath == null) {
2392                                continue;
2393                            }
2394                            try {
2395                                // Shared libraries do not have profiles so we perform a full
2396                                // AOT compilation (if needed).
2397                                int dexoptNeeded = DexFile.getDexOptNeeded(
2398                                        libPath, dexCodeInstructionSet,
2399                                        getCompilerFilterForReason(REASON_SHARED_APK),
2400                                        false /* newProfile */);
2401                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2402                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2403                                            dexCodeInstructionSet, dexoptNeeded, null,
2404                                            DEXOPT_PUBLIC,
2405                                            getCompilerFilterForReason(REASON_SHARED_APK),
2406                                            StorageManager.UUID_PRIVATE_INTERNAL,
2407                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2408                                }
2409                            } catch (FileNotFoundException e) {
2410                                Slog.w(TAG, "Library not found: " + libPath);
2411                            } catch (IOException | InstallerException e) {
2412                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2413                                        + e.getMessage());
2414                            }
2415                        }
2416                    }
2417                }
2418                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2419            }
2420
2421            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2422
2423            final VersionInfo ver = mSettings.getInternalVersion();
2424            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2425
2426            // when upgrading from pre-M, promote system app permissions from install to runtime
2427            mPromoteSystemApps =
2428                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2429
2430            // When upgrading from pre-N, we need to handle package extraction like first boot,
2431            // as there is no profiling data available.
2432            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2433
2434            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2435
2436            // save off the names of pre-existing system packages prior to scanning; we don't
2437            // want to automatically grant runtime permissions for new system apps
2438            if (mPromoteSystemApps) {
2439                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2440                while (pkgSettingIter.hasNext()) {
2441                    PackageSetting ps = pkgSettingIter.next();
2442                    if (isSystemApp(ps)) {
2443                        mExistingSystemPackages.add(ps.name);
2444                    }
2445                }
2446            }
2447
2448            mCacheDir = preparePackageParserCache(mIsUpgrade);
2449
2450            // Set flag to monitor and not change apk file paths when
2451            // scanning install directories.
2452            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2453
2454            if (mIsUpgrade || mFirstBoot) {
2455                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2456            }
2457
2458            // Collect vendor overlay packages. (Do this before scanning any apps.)
2459            // For security and version matching reason, only consider
2460            // overlay packages if they reside in the right directory.
2461            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2462            if (overlayThemeDir.isEmpty()) {
2463                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2464            }
2465            if (!overlayThemeDir.isEmpty()) {
2466                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2467                        | PackageParser.PARSE_IS_SYSTEM
2468                        | PackageParser.PARSE_IS_SYSTEM_DIR
2469                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2470            }
2471            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2472                    | PackageParser.PARSE_IS_SYSTEM
2473                    | PackageParser.PARSE_IS_SYSTEM_DIR
2474                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2475
2476            // Find base frameworks (resource packages without code).
2477            scanDirTracedLI(frameworkDir, mDefParseFlags
2478                    | PackageParser.PARSE_IS_SYSTEM
2479                    | PackageParser.PARSE_IS_SYSTEM_DIR
2480                    | PackageParser.PARSE_IS_PRIVILEGED,
2481                    scanFlags | SCAN_NO_DEX, 0);
2482
2483            // Collected privileged system packages.
2484            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2485            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2486                    | PackageParser.PARSE_IS_SYSTEM
2487                    | PackageParser.PARSE_IS_SYSTEM_DIR
2488                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2489
2490            // Collect ordinary system packages.
2491            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2492            scanDirTracedLI(systemAppDir, mDefParseFlags
2493                    | PackageParser.PARSE_IS_SYSTEM
2494                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2495
2496            // Collect all vendor packages.
2497            File vendorAppDir = new File("/vendor/app");
2498            try {
2499                vendorAppDir = vendorAppDir.getCanonicalFile();
2500            } catch (IOException e) {
2501                // failed to look up canonical path, continue with original one
2502            }
2503            scanDirTracedLI(vendorAppDir, mDefParseFlags
2504                    | PackageParser.PARSE_IS_SYSTEM
2505                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2506
2507            // Collect all OEM packages.
2508            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2509            scanDirTracedLI(oemAppDir, mDefParseFlags
2510                    | PackageParser.PARSE_IS_SYSTEM
2511                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2512
2513            // Prune any system packages that no longer exist.
2514            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2515            if (!mOnlyCore) {
2516                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2517                while (psit.hasNext()) {
2518                    PackageSetting ps = psit.next();
2519
2520                    /*
2521                     * If this is not a system app, it can't be a
2522                     * disable system app.
2523                     */
2524                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2525                        continue;
2526                    }
2527
2528                    /*
2529                     * If the package is scanned, it's not erased.
2530                     */
2531                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2532                    if (scannedPkg != null) {
2533                        /*
2534                         * If the system app is both scanned and in the
2535                         * disabled packages list, then it must have been
2536                         * added via OTA. Remove it from the currently
2537                         * scanned package so the previously user-installed
2538                         * application can be scanned.
2539                         */
2540                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2541                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2542                                    + ps.name + "; removing system app.  Last known codePath="
2543                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2544                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2545                                    + scannedPkg.mVersionCode);
2546                            removePackageLI(scannedPkg, true);
2547                            mExpectingBetter.put(ps.name, ps.codePath);
2548                        }
2549
2550                        continue;
2551                    }
2552
2553                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2554                        psit.remove();
2555                        logCriticalInfo(Log.WARN, "System package " + ps.name
2556                                + " no longer exists; it's data will be wiped");
2557                        // Actual deletion of code and data will be handled by later
2558                        // reconciliation step
2559                    } else {
2560                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2561                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2562                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2563                        }
2564                    }
2565                }
2566            }
2567
2568            //look for any incomplete package installations
2569            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2570            for (int i = 0; i < deletePkgsList.size(); i++) {
2571                // Actual deletion of code and data will be handled by later
2572                // reconciliation step
2573                final String packageName = deletePkgsList.get(i).name;
2574                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2575                synchronized (mPackages) {
2576                    mSettings.removePackageLPw(packageName);
2577                }
2578            }
2579
2580            //delete tmp files
2581            deleteTempPackageFiles();
2582
2583            // Remove any shared userIDs that have no associated packages
2584            mSettings.pruneSharedUsersLPw();
2585
2586            if (!mOnlyCore) {
2587                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2588                        SystemClock.uptimeMillis());
2589                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2590
2591                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2592                        | PackageParser.PARSE_FORWARD_LOCK,
2593                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2594
2595                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2596                        | PackageParser.PARSE_IS_EPHEMERAL,
2597                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2598
2599                /**
2600                 * Remove disable package settings for any updated system
2601                 * apps that were removed via an OTA. If they're not a
2602                 * previously-updated app, remove them completely.
2603                 * Otherwise, just revoke their system-level permissions.
2604                 */
2605                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2606                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2607                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2608
2609                    String msg;
2610                    if (deletedPkg == null) {
2611                        msg = "Updated system package " + deletedAppName
2612                                + " no longer exists; it's data will be wiped";
2613                        // Actual deletion of code and data will be handled by later
2614                        // reconciliation step
2615                    } else {
2616                        msg = "Updated system app + " + deletedAppName
2617                                + " no longer present; removing system privileges for "
2618                                + deletedAppName;
2619
2620                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2621
2622                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2623                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2624                    }
2625                    logCriticalInfo(Log.WARN, msg);
2626                }
2627
2628                /**
2629                 * Make sure all system apps that we expected to appear on
2630                 * the userdata partition actually showed up. If they never
2631                 * appeared, crawl back and revive the system version.
2632                 */
2633                for (int i = 0; i < mExpectingBetter.size(); i++) {
2634                    final String packageName = mExpectingBetter.keyAt(i);
2635                    if (!mPackages.containsKey(packageName)) {
2636                        final File scanFile = mExpectingBetter.valueAt(i);
2637
2638                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2639                                + " but never showed up; reverting to system");
2640
2641                        int reparseFlags = mDefParseFlags;
2642                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2643                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2644                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2645                                    | PackageParser.PARSE_IS_PRIVILEGED;
2646                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2652                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2653                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2654                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2655                        } else {
2656                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2657                            continue;
2658                        }
2659
2660                        mSettings.enableSystemPackageLPw(packageName);
2661
2662                        try {
2663                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2664                        } catch (PackageManagerException e) {
2665                            Slog.e(TAG, "Failed to parse original system package: "
2666                                    + e.getMessage());
2667                        }
2668                    }
2669                }
2670            }
2671            mExpectingBetter.clear();
2672
2673            // Resolve the storage manager.
2674            mStorageManagerPackage = getStorageManagerPackageName();
2675
2676            // Resolve protected action filters. Only the setup wizard is allowed to
2677            // have a high priority filter for these actions.
2678            mSetupWizardPackage = getSetupWizardPackageName();
2679            if (mProtectedFilters.size() > 0) {
2680                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2681                    Slog.i(TAG, "No setup wizard;"
2682                        + " All protected intents capped to priority 0");
2683                }
2684                for (ActivityIntentInfo filter : mProtectedFilters) {
2685                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2686                        if (DEBUG_FILTERS) {
2687                            Slog.i(TAG, "Found setup wizard;"
2688                                + " allow priority " + filter.getPriority() + ";"
2689                                + " package: " + filter.activity.info.packageName
2690                                + " activity: " + filter.activity.className
2691                                + " priority: " + filter.getPriority());
2692                        }
2693                        // skip setup wizard; allow it to keep the high priority filter
2694                        continue;
2695                    }
2696                    Slog.w(TAG, "Protected action; cap priority to 0;"
2697                            + " package: " + filter.activity.info.packageName
2698                            + " activity: " + filter.activity.className
2699                            + " origPrio: " + filter.getPriority());
2700                    filter.setPriority(0);
2701                }
2702            }
2703            mDeferProtectedFilters = false;
2704            mProtectedFilters.clear();
2705
2706            // Now that we know all of the shared libraries, update all clients to have
2707            // the correct library paths.
2708            updateAllSharedLibrariesLPw(null);
2709
2710            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2711                // NOTE: We ignore potential failures here during a system scan (like
2712                // the rest of the commands above) because there's precious little we
2713                // can do about it. A settings error is reported, though.
2714                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2715            }
2716
2717            // Now that we know all the packages we are keeping,
2718            // read and update their last usage times.
2719            mPackageUsage.read(mPackages);
2720            mCompilerStats.read();
2721
2722            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2723                    SystemClock.uptimeMillis());
2724            Slog.i(TAG, "Time to scan packages: "
2725                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2726                    + " seconds");
2727
2728            // If the platform SDK has changed since the last time we booted,
2729            // we need to re-grant app permission to catch any new ones that
2730            // appear.  This is really a hack, and means that apps can in some
2731            // cases get permissions that the user didn't initially explicitly
2732            // allow...  it would be nice to have some better way to handle
2733            // this situation.
2734            int updateFlags = UPDATE_PERMISSIONS_ALL;
2735            if (ver.sdkVersion != mSdkVersion) {
2736                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2737                        + mSdkVersion + "; regranting permissions for internal storage");
2738                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2739            }
2740            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2741            ver.sdkVersion = mSdkVersion;
2742
2743            // If this is the first boot or an update from pre-M, and it is a normal
2744            // boot, then we need to initialize the default preferred apps across
2745            // all defined users.
2746            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2747                for (UserInfo user : sUserManager.getUsers(true)) {
2748                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2749                    applyFactoryDefaultBrowserLPw(user.id);
2750                    primeDomainVerificationsLPw(user.id);
2751                }
2752            }
2753
2754            // Prepare storage for system user really early during boot,
2755            // since core system apps like SettingsProvider and SystemUI
2756            // can't wait for user to start
2757            final int storageFlags;
2758            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2759                storageFlags = StorageManager.FLAG_STORAGE_DE;
2760            } else {
2761                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2762            }
2763            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2764                    storageFlags, true /* migrateAppData */);
2765
2766            // If this is first boot after an OTA, and a normal boot, then
2767            // we need to clear code cache directories.
2768            // Note that we do *not* clear the application profiles. These remain valid
2769            // across OTAs and are used to drive profile verification (post OTA) and
2770            // profile compilation (without waiting to collect a fresh set of profiles).
2771            if (mIsUpgrade && !onlyCore) {
2772                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2773                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2774                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2775                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2776                        // No apps are running this early, so no need to freeze
2777                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2778                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2779                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2780                    }
2781                }
2782                ver.fingerprint = Build.FINGERPRINT;
2783            }
2784
2785            checkDefaultBrowser();
2786
2787            // clear only after permissions and other defaults have been updated
2788            mExistingSystemPackages.clear();
2789            mPromoteSystemApps = false;
2790
2791            // All the changes are done during package scanning.
2792            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2793
2794            // can downgrade to reader
2795            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2796            mSettings.writeLPr();
2797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2798
2799            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2800            // early on (before the package manager declares itself as early) because other
2801            // components in the system server might ask for package contexts for these apps.
2802            //
2803            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2804            // (i.e, that the data partition is unavailable).
2805            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2806                long start = System.nanoTime();
2807                List<PackageParser.Package> coreApps = new ArrayList<>();
2808                for (PackageParser.Package pkg : mPackages.values()) {
2809                    if (pkg.coreApp) {
2810                        coreApps.add(pkg);
2811                    }
2812                }
2813
2814                int[] stats = performDexOptUpgrade(coreApps, false,
2815                        getCompilerFilterForReason(REASON_CORE_APP));
2816
2817                final int elapsedTimeSeconds =
2818                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2819                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2820
2821                if (DEBUG_DEXOPT) {
2822                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2823                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2824                }
2825
2826
2827                // TODO: Should we log these stats to tron too ?
2828                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2829                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2830                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2831                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2832            }
2833
2834            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2835                    SystemClock.uptimeMillis());
2836
2837            if (!mOnlyCore) {
2838                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2839                mRequiredInstallerPackage = getRequiredInstallerLPr();
2840                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2841                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2842                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2843                        mIntentFilterVerifierComponent);
2844                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2845                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2846                        SharedLibraryInfo.VERSION_UNDEFINED);
2847                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2848                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2849                        SharedLibraryInfo.VERSION_UNDEFINED);
2850            } else {
2851                mRequiredVerifierPackage = null;
2852                mRequiredInstallerPackage = null;
2853                mRequiredUninstallerPackage = null;
2854                mIntentFilterVerifierComponent = null;
2855                mIntentFilterVerifier = null;
2856                mServicesSystemSharedLibraryPackageName = null;
2857                mSharedSystemSharedLibraryPackageName = null;
2858            }
2859
2860            mInstallerService = new PackageInstallerService(context, this);
2861
2862            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2863            if (ephemeralResolverComponent != null) {
2864                if (DEBUG_EPHEMERAL) {
2865                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2866                }
2867                mEphemeralResolverConnection =
2868                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2869            } else {
2870                mEphemeralResolverConnection = null;
2871            }
2872            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2873            if (mEphemeralInstallerComponent != null) {
2874                if (DEBUG_EPHEMERAL) {
2875                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2876                }
2877                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2878            }
2879
2880            // Read and update the usage of dex files.
2881            // Do this at the end of PM init so that all the packages have their
2882            // data directory reconciled.
2883            // At this point we know the code paths of the packages, so we can validate
2884            // the disk file and build the internal cache.
2885            // The usage file is expected to be small so loading and verifying it
2886            // should take a fairly small time compare to the other activities (e.g. package
2887            // scanning).
2888            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2889            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2890            for (int userId : currentUserIds) {
2891                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2892            }
2893            mDexManager.load(userPackages);
2894        } // synchronized (mPackages)
2895        } // synchronized (mInstallLock)
2896
2897        // Now after opening every single application zip, make sure they
2898        // are all flushed.  Not really needed, but keeps things nice and
2899        // tidy.
2900        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2901        Runtime.getRuntime().gc();
2902        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2903
2904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2905        FallbackCategoryProvider.loadFallbacks();
2906        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2907
2908        // The initial scanning above does many calls into installd while
2909        // holding the mPackages lock, but we're mostly interested in yelling
2910        // once we have a booted system.
2911        mInstaller.setWarnIfHeld(mPackages);
2912
2913        // Expose private service for system components to use.
2914        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2915        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2916    }
2917
2918    private static File preparePackageParserCache(boolean isUpgrade) {
2919        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2920            return null;
2921        }
2922
2923        // Disable package parsing on eng builds to allow for faster incremental development.
2924        if ("eng".equals(Build.TYPE)) {
2925            return null;
2926        }
2927
2928        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2929            Slog.i(TAG, "Disabling package parser cache due to system property.");
2930            return null;
2931        }
2932
2933        // The base directory for the package parser cache lives under /data/system/.
2934        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2935                "package_cache");
2936        if (cacheBaseDir == null) {
2937            return null;
2938        }
2939
2940        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2941        // This also serves to "GC" unused entries when the package cache version changes (which
2942        // can only happen during upgrades).
2943        if (isUpgrade) {
2944            FileUtils.deleteContents(cacheBaseDir);
2945        }
2946
2947
2948        // Return the versioned package cache directory. This is something like
2949        // "/data/system/package_cache/1"
2950        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2951
2952        // The following is a workaround to aid development on non-numbered userdebug
2953        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2954        // the system partition is newer.
2955        //
2956        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2957        // that starts with "eng." to signify that this is an engineering build and not
2958        // destined for release.
2959        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2960            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2961
2962            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2963            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2964            // in general and should not be used for production changes. In this specific case,
2965            // we know that they will work.
2966            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2967            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2968                FileUtils.deleteContents(cacheBaseDir);
2969                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2970            }
2971        }
2972
2973        return cacheDir;
2974    }
2975
2976    @Override
2977    public boolean isFirstBoot() {
2978        return mFirstBoot;
2979    }
2980
2981    @Override
2982    public boolean isOnlyCoreApps() {
2983        return mOnlyCore;
2984    }
2985
2986    @Override
2987    public boolean isUpgrade() {
2988        return mIsUpgrade;
2989    }
2990
2991    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2992        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2993
2994        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2995                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2996                UserHandle.USER_SYSTEM);
2997        if (matches.size() == 1) {
2998            return matches.get(0).getComponentInfo().packageName;
2999        } else if (matches.size() == 0) {
3000            Log.e(TAG, "There should probably be a verifier, but, none were found");
3001            return null;
3002        }
3003        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3004    }
3005
3006    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3007        synchronized (mPackages) {
3008            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3009            if (libraryEntry == null) {
3010                throw new IllegalStateException("Missing required shared library:" + name);
3011            }
3012            return libraryEntry.apk;
3013        }
3014    }
3015
3016    private @NonNull String getRequiredInstallerLPr() {
3017        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3018        intent.addCategory(Intent.CATEGORY_DEFAULT);
3019        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3020
3021        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3022                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3023                UserHandle.USER_SYSTEM);
3024        if (matches.size() == 1) {
3025            ResolveInfo resolveInfo = matches.get(0);
3026            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3027                throw new RuntimeException("The installer must be a privileged app");
3028            }
3029            return matches.get(0).getComponentInfo().packageName;
3030        } else {
3031            throw new RuntimeException("There must be exactly one installer; found " + matches);
3032        }
3033    }
3034
3035    private @NonNull String getRequiredUninstallerLPr() {
3036        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3037        intent.addCategory(Intent.CATEGORY_DEFAULT);
3038        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3039
3040        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3041                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3042                UserHandle.USER_SYSTEM);
3043        if (resolveInfo == null ||
3044                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3045            throw new RuntimeException("There must be exactly one uninstaller; found "
3046                    + resolveInfo);
3047        }
3048        return resolveInfo.getComponentInfo().packageName;
3049    }
3050
3051    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3052        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3053
3054        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3055                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3056                UserHandle.USER_SYSTEM);
3057        ResolveInfo best = null;
3058        final int N = matches.size();
3059        for (int i = 0; i < N; i++) {
3060            final ResolveInfo cur = matches.get(i);
3061            final String packageName = cur.getComponentInfo().packageName;
3062            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3063                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3064                continue;
3065            }
3066
3067            if (best == null || cur.priority > best.priority) {
3068                best = cur;
3069            }
3070        }
3071
3072        if (best != null) {
3073            return best.getComponentInfo().getComponentName();
3074        } else {
3075            throw new RuntimeException("There must be at least one intent filter verifier");
3076        }
3077    }
3078
3079    private @Nullable ComponentName getEphemeralResolverLPr() {
3080        final String[] packageArray =
3081                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3082        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3083            if (DEBUG_EPHEMERAL) {
3084                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3085            }
3086            return null;
3087        }
3088
3089        final int resolveFlags =
3090                MATCH_DIRECT_BOOT_AWARE
3091                | MATCH_DIRECT_BOOT_UNAWARE
3092                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3093        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3094        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3095                resolveFlags, UserHandle.USER_SYSTEM);
3096
3097        final int N = resolvers.size();
3098        if (N == 0) {
3099            if (DEBUG_EPHEMERAL) {
3100                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3101            }
3102            return null;
3103        }
3104
3105        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3106        for (int i = 0; i < N; i++) {
3107            final ResolveInfo info = resolvers.get(i);
3108
3109            if (info.serviceInfo == null) {
3110                continue;
3111            }
3112
3113            final String packageName = info.serviceInfo.packageName;
3114            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3115                if (DEBUG_EPHEMERAL) {
3116                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3117                            + " pkg: " + packageName + ", info:" + info);
3118                }
3119                continue;
3120            }
3121
3122            if (DEBUG_EPHEMERAL) {
3123                Slog.v(TAG, "Ephemeral resolver found;"
3124                        + " pkg: " + packageName + ", info:" + info);
3125            }
3126            return new ComponentName(packageName, info.serviceInfo.name);
3127        }
3128        if (DEBUG_EPHEMERAL) {
3129            Slog.v(TAG, "Ephemeral resolver NOT found");
3130        }
3131        return null;
3132    }
3133
3134    private @Nullable ComponentName getEphemeralInstallerLPr() {
3135        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3136        intent.addCategory(Intent.CATEGORY_DEFAULT);
3137        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3138
3139        final int resolveFlags =
3140                MATCH_DIRECT_BOOT_AWARE
3141                | MATCH_DIRECT_BOOT_UNAWARE
3142                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3143        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3144                resolveFlags, UserHandle.USER_SYSTEM);
3145        Iterator<ResolveInfo> iter = matches.iterator();
3146        while (iter.hasNext()) {
3147            final ResolveInfo rInfo = iter.next();
3148            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3149            if (ps != null) {
3150                final PermissionsState permissionsState = ps.getPermissionsState();
3151                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3152                    continue;
3153                }
3154            }
3155            iter.remove();
3156        }
3157        if (matches.size() == 0) {
3158            return null;
3159        } else if (matches.size() == 1) {
3160            return matches.get(0).getComponentInfo().getComponentName();
3161        } else {
3162            throw new RuntimeException(
3163                    "There must be at most one ephemeral installer; found " + matches);
3164        }
3165    }
3166
3167    private void primeDomainVerificationsLPw(int userId) {
3168        if (DEBUG_DOMAIN_VERIFICATION) {
3169            Slog.d(TAG, "Priming domain verifications in user " + userId);
3170        }
3171
3172        SystemConfig systemConfig = SystemConfig.getInstance();
3173        ArraySet<String> packages = systemConfig.getLinkedApps();
3174
3175        for (String packageName : packages) {
3176            PackageParser.Package pkg = mPackages.get(packageName);
3177            if (pkg != null) {
3178                if (!pkg.isSystemApp()) {
3179                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3180                    continue;
3181                }
3182
3183                ArraySet<String> domains = null;
3184                for (PackageParser.Activity a : pkg.activities) {
3185                    for (ActivityIntentInfo filter : a.intents) {
3186                        if (hasValidDomains(filter)) {
3187                            if (domains == null) {
3188                                domains = new ArraySet<String>();
3189                            }
3190                            domains.addAll(filter.getHostsList());
3191                        }
3192                    }
3193                }
3194
3195                if (domains != null && domains.size() > 0) {
3196                    if (DEBUG_DOMAIN_VERIFICATION) {
3197                        Slog.v(TAG, "      + " + packageName);
3198                    }
3199                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3200                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3201                    // and then 'always' in the per-user state actually used for intent resolution.
3202                    final IntentFilterVerificationInfo ivi;
3203                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3204                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3205                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3206                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3207                } else {
3208                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3209                            + "' does not handle web links");
3210                }
3211            } else {
3212                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3213            }
3214        }
3215
3216        scheduleWritePackageRestrictionsLocked(userId);
3217        scheduleWriteSettingsLocked();
3218    }
3219
3220    private void applyFactoryDefaultBrowserLPw(int userId) {
3221        // The default browser app's package name is stored in a string resource,
3222        // with a product-specific overlay used for vendor customization.
3223        String browserPkg = mContext.getResources().getString(
3224                com.android.internal.R.string.default_browser);
3225        if (!TextUtils.isEmpty(browserPkg)) {
3226            // non-empty string => required to be a known package
3227            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3228            if (ps == null) {
3229                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3230                browserPkg = null;
3231            } else {
3232                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3233            }
3234        }
3235
3236        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3237        // default.  If there's more than one, just leave everything alone.
3238        if (browserPkg == null) {
3239            calculateDefaultBrowserLPw(userId);
3240        }
3241    }
3242
3243    private void calculateDefaultBrowserLPw(int userId) {
3244        List<String> allBrowsers = resolveAllBrowserApps(userId);
3245        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3246        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3247    }
3248
3249    private List<String> resolveAllBrowserApps(int userId) {
3250        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3251        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3252                PackageManager.MATCH_ALL, userId);
3253
3254        final int count = list.size();
3255        List<String> result = new ArrayList<String>(count);
3256        for (int i=0; i<count; i++) {
3257            ResolveInfo info = list.get(i);
3258            if (info.activityInfo == null
3259                    || !info.handleAllWebDataURI
3260                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3261                    || result.contains(info.activityInfo.packageName)) {
3262                continue;
3263            }
3264            result.add(info.activityInfo.packageName);
3265        }
3266
3267        return result;
3268    }
3269
3270    private boolean packageIsBrowser(String packageName, int userId) {
3271        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3272                PackageManager.MATCH_ALL, userId);
3273        final int N = list.size();
3274        for (int i = 0; i < N; i++) {
3275            ResolveInfo info = list.get(i);
3276            if (packageName.equals(info.activityInfo.packageName)) {
3277                return true;
3278            }
3279        }
3280        return false;
3281    }
3282
3283    private void checkDefaultBrowser() {
3284        final int myUserId = UserHandle.myUserId();
3285        final String packageName = getDefaultBrowserPackageName(myUserId);
3286        if (packageName != null) {
3287            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3288            if (info == null) {
3289                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3290                synchronized (mPackages) {
3291                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3292                }
3293            }
3294        }
3295    }
3296
3297    @Override
3298    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3299            throws RemoteException {
3300        try {
3301            return super.onTransact(code, data, reply, flags);
3302        } catch (RuntimeException e) {
3303            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3304                Slog.wtf(TAG, "Package Manager Crash", e);
3305            }
3306            throw e;
3307        }
3308    }
3309
3310    static int[] appendInts(int[] cur, int[] add) {
3311        if (add == null) return cur;
3312        if (cur == null) return add;
3313        final int N = add.length;
3314        for (int i=0; i<N; i++) {
3315            cur = appendInt(cur, add[i]);
3316        }
3317        return cur;
3318    }
3319
3320    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3321        if (!sUserManager.exists(userId)) return null;
3322        if (ps == null) {
3323            return null;
3324        }
3325        final PackageParser.Package p = ps.pkg;
3326        if (p == null) {
3327            return null;
3328        }
3329        // Filter out ephemeral app metadata:
3330        //   * The system/shell/root can see metadata for any app
3331        //   * An installed app can see metadata for 1) other installed apps
3332        //     and 2) ephemeral apps that have explicitly interacted with it
3333        //   * Ephemeral apps can only see their own metadata
3334        //   * Holding a signature permission allows seeing instant apps
3335        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3336        if (callingAppId != Process.SYSTEM_UID
3337                && callingAppId != Process.SHELL_UID
3338                && callingAppId != Process.ROOT_UID
3339                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3340                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3341            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3342            if (instantAppPackageName != null) {
3343                // ephemeral apps can only get information on themselves
3344                if (!instantAppPackageName.equals(p.packageName)) {
3345                    return null;
3346                }
3347            } else {
3348                if (ps.getInstantApp(userId)) {
3349                    // only get access to the ephemeral app if we've been granted access
3350                    if (!mInstantAppRegistry.isInstantAccessGranted(
3351                            userId, callingAppId, ps.appId)) {
3352                        return null;
3353                    }
3354                }
3355            }
3356        }
3357
3358        final PermissionsState permissionsState = ps.getPermissionsState();
3359
3360        // Compute GIDs only if requested
3361        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3362                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3363        // Compute granted permissions only if package has requested permissions
3364        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3365                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3366        final PackageUserState state = ps.readUserState(userId);
3367
3368        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3369                && ps.isSystem()) {
3370            flags |= MATCH_ANY_USER;
3371        }
3372
3373        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3374                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3375
3376        if (packageInfo == null) {
3377            return null;
3378        }
3379
3380        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3381                resolveExternalPackageNameLPr(p);
3382
3383        return packageInfo;
3384    }
3385
3386    @Override
3387    public void checkPackageStartable(String packageName, int userId) {
3388        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3389
3390        synchronized (mPackages) {
3391            final PackageSetting ps = mSettings.mPackages.get(packageName);
3392            if (ps == null) {
3393                throw new SecurityException("Package " + packageName + " was not found!");
3394            }
3395
3396            if (!ps.getInstalled(userId)) {
3397                throw new SecurityException(
3398                        "Package " + packageName + " was not installed for user " + userId + "!");
3399            }
3400
3401            if (mSafeMode && !ps.isSystem()) {
3402                throw new SecurityException("Package " + packageName + " not a system app!");
3403            }
3404
3405            if (mFrozenPackages.contains(packageName)) {
3406                throw new SecurityException("Package " + packageName + " is currently frozen!");
3407            }
3408
3409            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3410                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3411                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3412            }
3413        }
3414    }
3415
3416    @Override
3417    public boolean isPackageAvailable(String packageName, int userId) {
3418        if (!sUserManager.exists(userId)) return false;
3419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3420                false /* requireFullPermission */, false /* checkShell */, "is package available");
3421        synchronized (mPackages) {
3422            PackageParser.Package p = mPackages.get(packageName);
3423            if (p != null) {
3424                final PackageSetting ps = (PackageSetting) p.mExtras;
3425                if (ps != null) {
3426                    final PackageUserState state = ps.readUserState(userId);
3427                    if (state != null) {
3428                        return PackageParser.isAvailable(state);
3429                    }
3430                }
3431            }
3432        }
3433        return false;
3434    }
3435
3436    @Override
3437    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3438        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3439                flags, userId);
3440    }
3441
3442    @Override
3443    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3444            int flags, int userId) {
3445        return getPackageInfoInternal(versionedPackage.getPackageName(),
3446                // TODO: We will change version code to long, so in the new API it is long
3447                (int) versionedPackage.getVersionCode(), flags, userId);
3448    }
3449
3450    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3451            int flags, int userId) {
3452        if (!sUserManager.exists(userId)) return null;
3453        flags = updateFlagsForPackage(flags, userId, packageName);
3454        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3455                false /* requireFullPermission */, false /* checkShell */, "get package info");
3456
3457        // reader
3458        synchronized (mPackages) {
3459            // Normalize package name to handle renamed packages and static libs
3460            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3461
3462            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3463            if (matchFactoryOnly) {
3464                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3465                if (ps != null) {
3466                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3467                        return null;
3468                    }
3469                    return generatePackageInfo(ps, flags, userId);
3470                }
3471            }
3472
3473            PackageParser.Package p = mPackages.get(packageName);
3474            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3475                return null;
3476            }
3477            if (DEBUG_PACKAGE_INFO)
3478                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3479            if (p != null) {
3480                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3481                        Binder.getCallingUid(), userId)) {
3482                    return null;
3483                }
3484                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3485            }
3486            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3487                final PackageSetting ps = mSettings.mPackages.get(packageName);
3488                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3489                    return null;
3490                }
3491                return generatePackageInfo(ps, flags, userId);
3492            }
3493        }
3494        return null;
3495    }
3496
3497
3498    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3499        // System/shell/root get to see all static libs
3500        final int appId = UserHandle.getAppId(uid);
3501        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3502                || appId == Process.ROOT_UID) {
3503            return false;
3504        }
3505
3506        // No package means no static lib as it is always on internal storage
3507        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3508            return false;
3509        }
3510
3511        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3512                ps.pkg.staticSharedLibVersion);
3513        if (libEntry == null) {
3514            return false;
3515        }
3516
3517        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3518        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3519        if (uidPackageNames == null) {
3520            return true;
3521        }
3522
3523        for (String uidPackageName : uidPackageNames) {
3524            if (ps.name.equals(uidPackageName)) {
3525                return false;
3526            }
3527            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3528            if (uidPs != null) {
3529                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3530                        libEntry.info.getName());
3531                if (index < 0) {
3532                    continue;
3533                }
3534                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3535                    return false;
3536                }
3537            }
3538        }
3539        return true;
3540    }
3541
3542    @Override
3543    public String[] currentToCanonicalPackageNames(String[] names) {
3544        String[] out = new String[names.length];
3545        // reader
3546        synchronized (mPackages) {
3547            for (int i=names.length-1; i>=0; i--) {
3548                PackageSetting ps = mSettings.mPackages.get(names[i]);
3549                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3550            }
3551        }
3552        return out;
3553    }
3554
3555    @Override
3556    public String[] canonicalToCurrentPackageNames(String[] names) {
3557        String[] out = new String[names.length];
3558        // reader
3559        synchronized (mPackages) {
3560            for (int i=names.length-1; i>=0; i--) {
3561                String cur = mSettings.getRenamedPackageLPr(names[i]);
3562                out[i] = cur != null ? cur : names[i];
3563            }
3564        }
3565        return out;
3566    }
3567
3568    @Override
3569    public int getPackageUid(String packageName, int flags, int userId) {
3570        if (!sUserManager.exists(userId)) return -1;
3571        flags = updateFlagsForPackage(flags, userId, packageName);
3572        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3573                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3574
3575        // reader
3576        synchronized (mPackages) {
3577            final PackageParser.Package p = mPackages.get(packageName);
3578            if (p != null && p.isMatch(flags)) {
3579                return UserHandle.getUid(userId, p.applicationInfo.uid);
3580            }
3581            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3582                final PackageSetting ps = mSettings.mPackages.get(packageName);
3583                if (ps != null && ps.isMatch(flags)) {
3584                    return UserHandle.getUid(userId, ps.appId);
3585                }
3586            }
3587        }
3588
3589        return -1;
3590    }
3591
3592    @Override
3593    public int[] getPackageGids(String packageName, int flags, int userId) {
3594        if (!sUserManager.exists(userId)) return null;
3595        flags = updateFlagsForPackage(flags, userId, packageName);
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3597                false /* requireFullPermission */, false /* checkShell */,
3598                "getPackageGids");
3599
3600        // reader
3601        synchronized (mPackages) {
3602            final PackageParser.Package p = mPackages.get(packageName);
3603            if (p != null && p.isMatch(flags)) {
3604                PackageSetting ps = (PackageSetting) p.mExtras;
3605                // TODO: Shouldn't this be checking for package installed state for userId and
3606                // return null?
3607                return ps.getPermissionsState().computeGids(userId);
3608            }
3609            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3610                final PackageSetting ps = mSettings.mPackages.get(packageName);
3611                if (ps != null && ps.isMatch(flags)) {
3612                    return ps.getPermissionsState().computeGids(userId);
3613                }
3614            }
3615        }
3616
3617        return null;
3618    }
3619
3620    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3621        if (bp.perm != null) {
3622            return PackageParser.generatePermissionInfo(bp.perm, flags);
3623        }
3624        PermissionInfo pi = new PermissionInfo();
3625        pi.name = bp.name;
3626        pi.packageName = bp.sourcePackage;
3627        pi.nonLocalizedLabel = bp.name;
3628        pi.protectionLevel = bp.protectionLevel;
3629        return pi;
3630    }
3631
3632    @Override
3633    public PermissionInfo getPermissionInfo(String name, int flags) {
3634        // reader
3635        synchronized (mPackages) {
3636            final BasePermission p = mSettings.mPermissions.get(name);
3637            if (p != null) {
3638                return generatePermissionInfo(p, flags);
3639            }
3640            return null;
3641        }
3642    }
3643
3644    @Override
3645    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3646            int flags) {
3647        // reader
3648        synchronized (mPackages) {
3649            if (group != null && !mPermissionGroups.containsKey(group)) {
3650                // This is thrown as NameNotFoundException
3651                return null;
3652            }
3653
3654            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3655            for (BasePermission p : mSettings.mPermissions.values()) {
3656                if (group == null) {
3657                    if (p.perm == null || p.perm.info.group == null) {
3658                        out.add(generatePermissionInfo(p, flags));
3659                    }
3660                } else {
3661                    if (p.perm != null && group.equals(p.perm.info.group)) {
3662                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3663                    }
3664                }
3665            }
3666            return new ParceledListSlice<>(out);
3667        }
3668    }
3669
3670    @Override
3671    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3672        // reader
3673        synchronized (mPackages) {
3674            return PackageParser.generatePermissionGroupInfo(
3675                    mPermissionGroups.get(name), flags);
3676        }
3677    }
3678
3679    @Override
3680    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3681        // reader
3682        synchronized (mPackages) {
3683            final int N = mPermissionGroups.size();
3684            ArrayList<PermissionGroupInfo> out
3685                    = new ArrayList<PermissionGroupInfo>(N);
3686            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3687                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3688            }
3689            return new ParceledListSlice<>(out);
3690        }
3691    }
3692
3693    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3694            int uid, int userId) {
3695        if (!sUserManager.exists(userId)) return null;
3696        PackageSetting ps = mSettings.mPackages.get(packageName);
3697        if (ps != null) {
3698            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3699                return null;
3700            }
3701            if (ps.pkg == null) {
3702                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3703                if (pInfo != null) {
3704                    return pInfo.applicationInfo;
3705                }
3706                return null;
3707            }
3708            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3709                    ps.readUserState(userId), userId);
3710            if (ai != null) {
3711                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3712            }
3713            return ai;
3714        }
3715        return null;
3716    }
3717
3718    @Override
3719    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3720        if (!sUserManager.exists(userId)) return null;
3721        flags = updateFlagsForApplication(flags, userId, packageName);
3722        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3723                false /* requireFullPermission */, false /* checkShell */, "get application info");
3724
3725        // writer
3726        synchronized (mPackages) {
3727            // Normalize package name to handle renamed packages and static libs
3728            packageName = resolveInternalPackageNameLPr(packageName,
3729                    PackageManager.VERSION_CODE_HIGHEST);
3730
3731            PackageParser.Package p = mPackages.get(packageName);
3732            if (DEBUG_PACKAGE_INFO) Log.v(
3733                    TAG, "getApplicationInfo " + packageName
3734                    + ": " + p);
3735            if (p != null) {
3736                PackageSetting ps = mSettings.mPackages.get(packageName);
3737                if (ps == null) return null;
3738                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3739                    return null;
3740                }
3741                // Note: isEnabledLP() does not apply here - always return info
3742                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3743                        p, flags, ps.readUserState(userId), userId);
3744                if (ai != null) {
3745                    ai.packageName = resolveExternalPackageNameLPr(p);
3746                }
3747                return ai;
3748            }
3749            if ("android".equals(packageName)||"system".equals(packageName)) {
3750                return mAndroidApplication;
3751            }
3752            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3753                // Already generates the external package name
3754                return generateApplicationInfoFromSettingsLPw(packageName,
3755                        Binder.getCallingUid(), flags, userId);
3756            }
3757        }
3758        return null;
3759    }
3760
3761    private String normalizePackageNameLPr(String packageName) {
3762        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3763        return normalizedPackageName != null ? normalizedPackageName : packageName;
3764    }
3765
3766    @Override
3767    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3768            final IPackageDataObserver observer) {
3769        mContext.enforceCallingOrSelfPermission(
3770                android.Manifest.permission.CLEAR_APP_CACHE, null);
3771        // Queue up an async operation since clearing cache may take a little while.
3772        mHandler.post(new Runnable() {
3773            public void run() {
3774                mHandler.removeCallbacks(this);
3775                boolean success = true;
3776                synchronized (mInstallLock) {
3777                    try {
3778                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3779                    } catch (InstallerException e) {
3780                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3781                        success = false;
3782                    }
3783                }
3784                if (observer != null) {
3785                    try {
3786                        observer.onRemoveCompleted(null, success);
3787                    } catch (RemoteException e) {
3788                        Slog.w(TAG, "RemoveException when invoking call back");
3789                    }
3790                }
3791            }
3792        });
3793    }
3794
3795    @Override
3796    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3797            final IntentSender pi) {
3798        mContext.enforceCallingOrSelfPermission(
3799                android.Manifest.permission.CLEAR_APP_CACHE, null);
3800        // Queue up an async operation since clearing cache may take a little while.
3801        mHandler.post(new Runnable() {
3802            public void run() {
3803                mHandler.removeCallbacks(this);
3804                boolean success = true;
3805                synchronized (mInstallLock) {
3806                    try {
3807                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3808                    } catch (InstallerException e) {
3809                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3810                        success = false;
3811                    }
3812                }
3813                if(pi != null) {
3814                    try {
3815                        // Callback via pending intent
3816                        int code = success ? 1 : 0;
3817                        pi.sendIntent(null, code, null,
3818                                null, null);
3819                    } catch (SendIntentException e1) {
3820                        Slog.i(TAG, "Failed to send pending intent");
3821                    }
3822                }
3823            }
3824        });
3825    }
3826
3827    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3828        synchronized (mInstallLock) {
3829            try {
3830                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3831            } catch (InstallerException e) {
3832                throw new IOException("Failed to free enough space", e);
3833            }
3834        }
3835    }
3836
3837    /**
3838     * Update given flags based on encryption status of current user.
3839     */
3840    private int updateFlags(int flags, int userId) {
3841        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3842                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3843            // Caller expressed an explicit opinion about what encryption
3844            // aware/unaware components they want to see, so fall through and
3845            // give them what they want
3846        } else {
3847            // Caller expressed no opinion, so match based on user state
3848            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3849                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3850            } else {
3851                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3852            }
3853        }
3854        return flags;
3855    }
3856
3857    private UserManagerInternal getUserManagerInternal() {
3858        if (mUserManagerInternal == null) {
3859            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3860        }
3861        return mUserManagerInternal;
3862    }
3863
3864    /**
3865     * Update given flags when being used to request {@link PackageInfo}.
3866     */
3867    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3868        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3869        boolean triaged = true;
3870        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3871                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3872            // Caller is asking for component details, so they'd better be
3873            // asking for specific encryption matching behavior, or be triaged
3874            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3875                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3876                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3877                triaged = false;
3878            }
3879        }
3880        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3881                | PackageManager.MATCH_SYSTEM_ONLY
3882                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3883            triaged = false;
3884        }
3885        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3886            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3887                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3888                    + Debug.getCallers(5));
3889        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3890                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3891            // If the caller wants all packages and has a restricted profile associated with it,
3892            // then match all users. This is to make sure that launchers that need to access work
3893            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3894            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3895            flags |= PackageManager.MATCH_ANY_USER;
3896        }
3897        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3898            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3899                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3900        }
3901        return updateFlags(flags, userId);
3902    }
3903
3904    /**
3905     * Update given flags when being used to request {@link ApplicationInfo}.
3906     */
3907    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3908        return updateFlagsForPackage(flags, userId, cookie);
3909    }
3910
3911    /**
3912     * Update given flags when being used to request {@link ComponentInfo}.
3913     */
3914    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3915        if (cookie instanceof Intent) {
3916            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3917                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3918            }
3919        }
3920
3921        boolean triaged = true;
3922        // Caller is asking for component details, so they'd better be
3923        // asking for specific encryption matching behavior, or be triaged
3924        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3925                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3926                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3927            triaged = false;
3928        }
3929        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3930            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3931                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3932        }
3933
3934        return updateFlags(flags, userId);
3935    }
3936
3937    /**
3938     * Update given intent when being used to request {@link ResolveInfo}.
3939     */
3940    private Intent updateIntentForResolve(Intent intent) {
3941        if (intent.getSelector() != null) {
3942            intent = intent.getSelector();
3943        }
3944        if (DEBUG_PREFERRED) {
3945            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3946        }
3947        return intent;
3948    }
3949
3950    /**
3951     * Update given flags when being used to request {@link ResolveInfo}.
3952     */
3953    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3954        // Safe mode means we shouldn't match any third-party components
3955        if (mSafeMode) {
3956            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3957        }
3958        final int callingUid = Binder.getCallingUid();
3959        if (getInstantAppPackageName(callingUid) != null) {
3960            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3961            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
3962            flags |= PackageManager.MATCH_INSTANT;
3963        } else {
3964            // Otherwise, prevent leaking ephemeral components
3965            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
3966            if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3967                // Unless called from the system process
3968                flags &= ~PackageManager.MATCH_INSTANT;
3969            }
3970        }
3971        return updateFlagsForComponent(flags, userId, cookie);
3972    }
3973
3974    @Override
3975    public ActivityInfo getActivityInfo(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 activity info");
3980        synchronized (mPackages) {
3981            PackageParser.Activity a = mActivities.mActivities.get(component);
3982
3983            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + 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            if (mResolveComponentName.equals(component)) {
3991                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3992                        new PackageUserState(), userId);
3993            }
3994        }
3995        return null;
3996    }
3997
3998    @Override
3999    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4000            String resolvedType) {
4001        synchronized (mPackages) {
4002            if (component.equals(mResolveComponentName)) {
4003                // The resolver supports EVERYTHING!
4004                return true;
4005            }
4006            PackageParser.Activity a = mActivities.mActivities.get(component);
4007            if (a == null) {
4008                return false;
4009            }
4010            for (int i=0; i<a.intents.size(); i++) {
4011                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4012                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4013                    return true;
4014                }
4015            }
4016            return false;
4017        }
4018    }
4019
4020    @Override
4021    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4022        if (!sUserManager.exists(userId)) return null;
4023        flags = updateFlagsForComponent(flags, userId, component);
4024        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4025                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4026        synchronized (mPackages) {
4027            PackageParser.Activity a = mReceivers.mActivities.get(component);
4028            if (DEBUG_PACKAGE_INFO) Log.v(
4029                TAG, "getReceiverInfo " + component + ": " + a);
4030            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4032                if (ps == null) return null;
4033                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4034                        userId);
4035            }
4036        }
4037        return null;
4038    }
4039
4040    @Override
4041    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4042        if (!sUserManager.exists(userId)) return null;
4043        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4044
4045        flags = updateFlagsForPackage(flags, userId, null);
4046
4047        final boolean canSeeStaticLibraries =
4048                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4049                        == PERMISSION_GRANTED
4050                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4051                        == PERMISSION_GRANTED
4052                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4053                        == PERMISSION_GRANTED
4054                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4055                        == PERMISSION_GRANTED;
4056
4057        synchronized (mPackages) {
4058            List<SharedLibraryInfo> result = null;
4059
4060            final int libCount = mSharedLibraries.size();
4061            for (int i = 0; i < libCount; i++) {
4062                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4063                if (versionedLib == null) {
4064                    continue;
4065                }
4066
4067                final int versionCount = versionedLib.size();
4068                for (int j = 0; j < versionCount; j++) {
4069                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4070                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4071                        break;
4072                    }
4073                    final long identity = Binder.clearCallingIdentity();
4074                    try {
4075                        // TODO: We will change version code to long, so in the new API it is long
4076                        PackageInfo packageInfo = getPackageInfoVersioned(
4077                                libInfo.getDeclaringPackage(), flags, userId);
4078                        if (packageInfo == null) {
4079                            continue;
4080                        }
4081                    } finally {
4082                        Binder.restoreCallingIdentity(identity);
4083                    }
4084
4085                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4086                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4087                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4088
4089                    if (result == null) {
4090                        result = new ArrayList<>();
4091                    }
4092                    result.add(resLibInfo);
4093                }
4094            }
4095
4096            return result != null ? new ParceledListSlice<>(result) : null;
4097        }
4098    }
4099
4100    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4101            SharedLibraryInfo libInfo, int flags, int userId) {
4102        List<VersionedPackage> versionedPackages = null;
4103        final int packageCount = mSettings.mPackages.size();
4104        for (int i = 0; i < packageCount; i++) {
4105            PackageSetting ps = mSettings.mPackages.valueAt(i);
4106
4107            if (ps == null) {
4108                continue;
4109            }
4110
4111            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4112                continue;
4113            }
4114
4115            final String libName = libInfo.getName();
4116            if (libInfo.isStatic()) {
4117                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4118                if (libIdx < 0) {
4119                    continue;
4120                }
4121                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4122                    continue;
4123                }
4124                if (versionedPackages == null) {
4125                    versionedPackages = new ArrayList<>();
4126                }
4127                // If the dependent is a static shared lib, use the public package name
4128                String dependentPackageName = ps.name;
4129                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4130                    dependentPackageName = ps.pkg.manifestPackageName;
4131                }
4132                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4133            } else if (ps.pkg != null) {
4134                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4135                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4136                    if (versionedPackages == null) {
4137                        versionedPackages = new ArrayList<>();
4138                    }
4139                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4140                }
4141            }
4142        }
4143
4144        return versionedPackages;
4145    }
4146
4147    @Override
4148    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4149        if (!sUserManager.exists(userId)) return null;
4150        flags = updateFlagsForComponent(flags, userId, component);
4151        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4152                false /* requireFullPermission */, false /* checkShell */, "get service info");
4153        synchronized (mPackages) {
4154            PackageParser.Service s = mServices.mServices.get(component);
4155            if (DEBUG_PACKAGE_INFO) Log.v(
4156                TAG, "getServiceInfo " + component + ": " + s);
4157            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4158                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4159                if (ps == null) return null;
4160                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4161                        userId);
4162            }
4163        }
4164        return null;
4165    }
4166
4167    @Override
4168    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4169        if (!sUserManager.exists(userId)) return null;
4170        flags = updateFlagsForComponent(flags, userId, component);
4171        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4172                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4173        synchronized (mPackages) {
4174            PackageParser.Provider p = mProviders.mProviders.get(component);
4175            if (DEBUG_PACKAGE_INFO) Log.v(
4176                TAG, "getProviderInfo " + component + ": " + p);
4177            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4178                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4179                if (ps == null) return null;
4180                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4181                        userId);
4182            }
4183        }
4184        return null;
4185    }
4186
4187    @Override
4188    public String[] getSystemSharedLibraryNames() {
4189        synchronized (mPackages) {
4190            Set<String> libs = null;
4191            final int libCount = mSharedLibraries.size();
4192            for (int i = 0; i < libCount; i++) {
4193                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4194                if (versionedLib == null) {
4195                    continue;
4196                }
4197                final int versionCount = versionedLib.size();
4198                for (int j = 0; j < versionCount; j++) {
4199                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4200                    if (!libEntry.info.isStatic()) {
4201                        if (libs == null) {
4202                            libs = new ArraySet<>();
4203                        }
4204                        libs.add(libEntry.info.getName());
4205                        break;
4206                    }
4207                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4208                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4209                            UserHandle.getUserId(Binder.getCallingUid()))) {
4210                        if (libs == null) {
4211                            libs = new ArraySet<>();
4212                        }
4213                        libs.add(libEntry.info.getName());
4214                        break;
4215                    }
4216                }
4217            }
4218
4219            if (libs != null) {
4220                String[] libsArray = new String[libs.size()];
4221                libs.toArray(libsArray);
4222                return libsArray;
4223            }
4224
4225            return null;
4226        }
4227    }
4228
4229    @Override
4230    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4231        synchronized (mPackages) {
4232            return mServicesSystemSharedLibraryPackageName;
4233        }
4234    }
4235
4236    @Override
4237    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4238        synchronized (mPackages) {
4239            return mSharedSystemSharedLibraryPackageName;
4240        }
4241    }
4242
4243    private void updateSequenceNumberLP(String packageName, int[] userList) {
4244        for (int i = userList.length - 1; i >= 0; --i) {
4245            final int userId = userList[i];
4246            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4247            if (changedPackages == null) {
4248                changedPackages = new SparseArray<>();
4249                mChangedPackages.put(userId, changedPackages);
4250            }
4251            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4252            if (sequenceNumbers == null) {
4253                sequenceNumbers = new HashMap<>();
4254                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4255            }
4256            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4257            if (sequenceNumber != null) {
4258                changedPackages.remove(sequenceNumber);
4259            }
4260            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4261            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4262        }
4263        mChangedPackagesSequenceNumber++;
4264    }
4265
4266    @Override
4267    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4268        synchronized (mPackages) {
4269            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4270                return null;
4271            }
4272            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4273            if (changedPackages == null) {
4274                return null;
4275            }
4276            final List<String> packageNames =
4277                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4278            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4279                final String packageName = changedPackages.get(i);
4280                if (packageName != null) {
4281                    packageNames.add(packageName);
4282                }
4283            }
4284            return packageNames.isEmpty()
4285                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4286        }
4287    }
4288
4289    @Override
4290    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4291        ArrayList<FeatureInfo> res;
4292        synchronized (mAvailableFeatures) {
4293            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4294            res.addAll(mAvailableFeatures.values());
4295        }
4296        final FeatureInfo fi = new FeatureInfo();
4297        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4298                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4299        res.add(fi);
4300
4301        return new ParceledListSlice<>(res);
4302    }
4303
4304    @Override
4305    public boolean hasSystemFeature(String name, int version) {
4306        synchronized (mAvailableFeatures) {
4307            final FeatureInfo feat = mAvailableFeatures.get(name);
4308            if (feat == null) {
4309                return false;
4310            } else {
4311                return feat.version >= version;
4312            }
4313        }
4314    }
4315
4316    @Override
4317    public int checkPermission(String permName, String pkgName, int userId) {
4318        if (!sUserManager.exists(userId)) {
4319            return PackageManager.PERMISSION_DENIED;
4320        }
4321
4322        synchronized (mPackages) {
4323            final PackageParser.Package p = mPackages.get(pkgName);
4324            if (p != null && p.mExtras != null) {
4325                final PackageSetting ps = (PackageSetting) p.mExtras;
4326                final PermissionsState permissionsState = ps.getPermissionsState();
4327                if (permissionsState.hasPermission(permName, userId)) {
4328                    return PackageManager.PERMISSION_GRANTED;
4329                }
4330                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4331                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4332                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4333                    return PackageManager.PERMISSION_GRANTED;
4334                }
4335            }
4336        }
4337
4338        return PackageManager.PERMISSION_DENIED;
4339    }
4340
4341    @Override
4342    public int checkUidPermission(String permName, int uid) {
4343        final int userId = UserHandle.getUserId(uid);
4344
4345        if (!sUserManager.exists(userId)) {
4346            return PackageManager.PERMISSION_DENIED;
4347        }
4348
4349        synchronized (mPackages) {
4350            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4351            if (obj != null) {
4352                final SettingBase ps = (SettingBase) obj;
4353                final PermissionsState permissionsState = ps.getPermissionsState();
4354                if (permissionsState.hasPermission(permName, userId)) {
4355                    return PackageManager.PERMISSION_GRANTED;
4356                }
4357                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4358                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4359                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4360                    return PackageManager.PERMISSION_GRANTED;
4361                }
4362            } else {
4363                ArraySet<String> perms = mSystemPermissions.get(uid);
4364                if (perms != null) {
4365                    if (perms.contains(permName)) {
4366                        return PackageManager.PERMISSION_GRANTED;
4367                    }
4368                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4369                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4370                        return PackageManager.PERMISSION_GRANTED;
4371                    }
4372                }
4373            }
4374        }
4375
4376        return PackageManager.PERMISSION_DENIED;
4377    }
4378
4379    @Override
4380    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4381        if (UserHandle.getCallingUserId() != userId) {
4382            mContext.enforceCallingPermission(
4383                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4384                    "isPermissionRevokedByPolicy for user " + userId);
4385        }
4386
4387        if (checkPermission(permission, packageName, userId)
4388                == PackageManager.PERMISSION_GRANTED) {
4389            return false;
4390        }
4391
4392        final long identity = Binder.clearCallingIdentity();
4393        try {
4394            final int flags = getPermissionFlags(permission, packageName, userId);
4395            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4396        } finally {
4397            Binder.restoreCallingIdentity(identity);
4398        }
4399    }
4400
4401    @Override
4402    public String getPermissionControllerPackageName() {
4403        synchronized (mPackages) {
4404            return mRequiredInstallerPackage;
4405        }
4406    }
4407
4408    /**
4409     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4410     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4411     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4412     * @param message the message to log on security exception
4413     */
4414    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4415            boolean checkShell, String message) {
4416        if (userId < 0) {
4417            throw new IllegalArgumentException("Invalid userId " + userId);
4418        }
4419        if (checkShell) {
4420            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4421        }
4422        if (userId == UserHandle.getUserId(callingUid)) return;
4423        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4424            if (requireFullPermission) {
4425                mContext.enforceCallingOrSelfPermission(
4426                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4427            } else {
4428                try {
4429                    mContext.enforceCallingOrSelfPermission(
4430                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4431                } catch (SecurityException se) {
4432                    mContext.enforceCallingOrSelfPermission(
4433                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4434                }
4435            }
4436        }
4437    }
4438
4439    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4440        if (callingUid == Process.SHELL_UID) {
4441            if (userHandle >= 0
4442                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4443                throw new SecurityException("Shell does not have permission to access user "
4444                        + userHandle);
4445            } else if (userHandle < 0) {
4446                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4447                        + Debug.getCallers(3));
4448            }
4449        }
4450    }
4451
4452    private BasePermission findPermissionTreeLP(String permName) {
4453        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4454            if (permName.startsWith(bp.name) &&
4455                    permName.length() > bp.name.length() &&
4456                    permName.charAt(bp.name.length()) == '.') {
4457                return bp;
4458            }
4459        }
4460        return null;
4461    }
4462
4463    private BasePermission checkPermissionTreeLP(String permName) {
4464        if (permName != null) {
4465            BasePermission bp = findPermissionTreeLP(permName);
4466            if (bp != null) {
4467                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4468                    return bp;
4469                }
4470                throw new SecurityException("Calling uid "
4471                        + Binder.getCallingUid()
4472                        + " is not allowed to add to permission tree "
4473                        + bp.name + " owned by uid " + bp.uid);
4474            }
4475        }
4476        throw new SecurityException("No permission tree found for " + permName);
4477    }
4478
4479    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4480        if (s1 == null) {
4481            return s2 == null;
4482        }
4483        if (s2 == null) {
4484            return false;
4485        }
4486        if (s1.getClass() != s2.getClass()) {
4487            return false;
4488        }
4489        return s1.equals(s2);
4490    }
4491
4492    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4493        if (pi1.icon != pi2.icon) return false;
4494        if (pi1.logo != pi2.logo) return false;
4495        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4496        if (!compareStrings(pi1.name, pi2.name)) return false;
4497        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4498        // We'll take care of setting this one.
4499        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4500        // These are not currently stored in settings.
4501        //if (!compareStrings(pi1.group, pi2.group)) return false;
4502        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4503        //if (pi1.labelRes != pi2.labelRes) return false;
4504        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4505        return true;
4506    }
4507
4508    int permissionInfoFootprint(PermissionInfo info) {
4509        int size = info.name.length();
4510        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4511        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4512        return size;
4513    }
4514
4515    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4516        int size = 0;
4517        for (BasePermission perm : mSettings.mPermissions.values()) {
4518            if (perm.uid == tree.uid) {
4519                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4520            }
4521        }
4522        return size;
4523    }
4524
4525    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4526        // We calculate the max size of permissions defined by this uid and throw
4527        // if that plus the size of 'info' would exceed our stated maximum.
4528        if (tree.uid != Process.SYSTEM_UID) {
4529            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4530            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4531                throw new SecurityException("Permission tree size cap exceeded");
4532            }
4533        }
4534    }
4535
4536    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4537        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4538            throw new SecurityException("Label must be specified in permission");
4539        }
4540        BasePermission tree = checkPermissionTreeLP(info.name);
4541        BasePermission bp = mSettings.mPermissions.get(info.name);
4542        boolean added = bp == null;
4543        boolean changed = true;
4544        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4545        if (added) {
4546            enforcePermissionCapLocked(info, tree);
4547            bp = new BasePermission(info.name, tree.sourcePackage,
4548                    BasePermission.TYPE_DYNAMIC);
4549        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4550            throw new SecurityException(
4551                    "Not allowed to modify non-dynamic permission "
4552                    + info.name);
4553        } else {
4554            if (bp.protectionLevel == fixedLevel
4555                    && bp.perm.owner.equals(tree.perm.owner)
4556                    && bp.uid == tree.uid
4557                    && comparePermissionInfos(bp.perm.info, info)) {
4558                changed = false;
4559            }
4560        }
4561        bp.protectionLevel = fixedLevel;
4562        info = new PermissionInfo(info);
4563        info.protectionLevel = fixedLevel;
4564        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4565        bp.perm.info.packageName = tree.perm.info.packageName;
4566        bp.uid = tree.uid;
4567        if (added) {
4568            mSettings.mPermissions.put(info.name, bp);
4569        }
4570        if (changed) {
4571            if (!async) {
4572                mSettings.writeLPr();
4573            } else {
4574                scheduleWriteSettingsLocked();
4575            }
4576        }
4577        return added;
4578    }
4579
4580    @Override
4581    public boolean addPermission(PermissionInfo info) {
4582        synchronized (mPackages) {
4583            return addPermissionLocked(info, false);
4584        }
4585    }
4586
4587    @Override
4588    public boolean addPermissionAsync(PermissionInfo info) {
4589        synchronized (mPackages) {
4590            return addPermissionLocked(info, true);
4591        }
4592    }
4593
4594    @Override
4595    public void removePermission(String name) {
4596        synchronized (mPackages) {
4597            checkPermissionTreeLP(name);
4598            BasePermission bp = mSettings.mPermissions.get(name);
4599            if (bp != null) {
4600                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4601                    throw new SecurityException(
4602                            "Not allowed to modify non-dynamic permission "
4603                            + name);
4604                }
4605                mSettings.mPermissions.remove(name);
4606                mSettings.writeLPr();
4607            }
4608        }
4609    }
4610
4611    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4612            BasePermission bp) {
4613        int index = pkg.requestedPermissions.indexOf(bp.name);
4614        if (index == -1) {
4615            throw new SecurityException("Package " + pkg.packageName
4616                    + " has not requested permission " + bp.name);
4617        }
4618        if (!bp.isRuntime() && !bp.isDevelopment()) {
4619            throw new SecurityException("Permission " + bp.name
4620                    + " is not a changeable permission type");
4621        }
4622    }
4623
4624    @Override
4625    public void grantRuntimePermission(String packageName, String name, final int userId) {
4626        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4627    }
4628
4629    private void grantRuntimePermission(String packageName, String name, final int userId,
4630            boolean overridePolicy) {
4631        if (!sUserManager.exists(userId)) {
4632            Log.e(TAG, "No such user:" + userId);
4633            return;
4634        }
4635
4636        mContext.enforceCallingOrSelfPermission(
4637                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4638                "grantRuntimePermission");
4639
4640        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4641                true /* requireFullPermission */, true /* checkShell */,
4642                "grantRuntimePermission");
4643
4644        final int uid;
4645        final SettingBase sb;
4646
4647        synchronized (mPackages) {
4648            final PackageParser.Package pkg = mPackages.get(packageName);
4649            if (pkg == null) {
4650                throw new IllegalArgumentException("Unknown package: " + packageName);
4651            }
4652
4653            final BasePermission bp = mSettings.mPermissions.get(name);
4654            if (bp == null) {
4655                throw new IllegalArgumentException("Unknown permission: " + name);
4656            }
4657
4658            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4659
4660            // If a permission review is required for legacy apps we represent
4661            // their permissions as always granted runtime ones since we need
4662            // to keep the review required permission flag per user while an
4663            // install permission's state is shared across all users.
4664            if (mPermissionReviewRequired
4665                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4666                    && bp.isRuntime()) {
4667                return;
4668            }
4669
4670            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4671            sb = (SettingBase) pkg.mExtras;
4672            if (sb == null) {
4673                throw new IllegalArgumentException("Unknown package: " + packageName);
4674            }
4675
4676            final PermissionsState permissionsState = sb.getPermissionsState();
4677
4678            final int flags = permissionsState.getPermissionFlags(name, userId);
4679            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4680                throw new SecurityException("Cannot grant system fixed permission "
4681                        + name + " for package " + packageName);
4682            }
4683            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4684                throw new SecurityException("Cannot grant policy fixed permission "
4685                        + name + " for package " + packageName);
4686            }
4687
4688            if (bp.isDevelopment()) {
4689                // Development permissions must be handled specially, since they are not
4690                // normal runtime permissions.  For now they apply to all users.
4691                if (permissionsState.grantInstallPermission(bp) !=
4692                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4693                    scheduleWriteSettingsLocked();
4694                }
4695                return;
4696            }
4697
4698            final PackageSetting ps = mSettings.mPackages.get(packageName);
4699            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4700                throw new SecurityException("Cannot grant non-ephemeral permission"
4701                        + name + " for package " + packageName);
4702            }
4703
4704            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4705                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4706                return;
4707            }
4708
4709            final int result = permissionsState.grantRuntimePermission(bp, userId);
4710            switch (result) {
4711                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4712                    return;
4713                }
4714
4715                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4716                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4717                    mHandler.post(new Runnable() {
4718                        @Override
4719                        public void run() {
4720                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4721                        }
4722                    });
4723                }
4724                break;
4725            }
4726
4727            if (bp.isRuntime()) {
4728                logPermissionGranted(mContext, name, packageName);
4729            }
4730
4731            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4732
4733            // Not critical if that is lost - app has to request again.
4734            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4735        }
4736
4737        // Only need to do this if user is initialized. Otherwise it's a new user
4738        // and there are no processes running as the user yet and there's no need
4739        // to make an expensive call to remount processes for the changed permissions.
4740        if (READ_EXTERNAL_STORAGE.equals(name)
4741                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4742            final long token = Binder.clearCallingIdentity();
4743            try {
4744                if (sUserManager.isInitialized(userId)) {
4745                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4746                            StorageManagerInternal.class);
4747                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4748                }
4749            } finally {
4750                Binder.restoreCallingIdentity(token);
4751            }
4752        }
4753    }
4754
4755    @Override
4756    public void revokeRuntimePermission(String packageName, String name, int userId) {
4757        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4758    }
4759
4760    private void revokeRuntimePermission(String packageName, String name, int userId,
4761            boolean overridePolicy) {
4762        if (!sUserManager.exists(userId)) {
4763            Log.e(TAG, "No such user:" + userId);
4764            return;
4765        }
4766
4767        mContext.enforceCallingOrSelfPermission(
4768                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4769                "revokeRuntimePermission");
4770
4771        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4772                true /* requireFullPermission */, true /* checkShell */,
4773                "revokeRuntimePermission");
4774
4775        final int appId;
4776
4777        synchronized (mPackages) {
4778            final PackageParser.Package pkg = mPackages.get(packageName);
4779            if (pkg == null) {
4780                throw new IllegalArgumentException("Unknown package: " + packageName);
4781            }
4782
4783            final BasePermission bp = mSettings.mPermissions.get(name);
4784            if (bp == null) {
4785                throw new IllegalArgumentException("Unknown permission: " + name);
4786            }
4787
4788            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4789
4790            // If a permission review is required for legacy apps we represent
4791            // their permissions as always granted runtime ones since we need
4792            // to keep the review required permission flag per user while an
4793            // install permission's state is shared across all users.
4794            if (mPermissionReviewRequired
4795                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4796                    && bp.isRuntime()) {
4797                return;
4798            }
4799
4800            SettingBase sb = (SettingBase) pkg.mExtras;
4801            if (sb == null) {
4802                throw new IllegalArgumentException("Unknown package: " + packageName);
4803            }
4804
4805            final PermissionsState permissionsState = sb.getPermissionsState();
4806
4807            final int flags = permissionsState.getPermissionFlags(name, userId);
4808            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4809                throw new SecurityException("Cannot revoke system fixed permission "
4810                        + name + " for package " + packageName);
4811            }
4812            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4813                throw new SecurityException("Cannot revoke policy fixed permission "
4814                        + name + " for package " + packageName);
4815            }
4816
4817            if (bp.isDevelopment()) {
4818                // Development permissions must be handled specially, since they are not
4819                // normal runtime permissions.  For now they apply to all users.
4820                if (permissionsState.revokeInstallPermission(bp) !=
4821                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4822                    scheduleWriteSettingsLocked();
4823                }
4824                return;
4825            }
4826
4827            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4828                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4829                return;
4830            }
4831
4832            if (bp.isRuntime()) {
4833                logPermissionRevoked(mContext, name, packageName);
4834            }
4835
4836            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4837
4838            // Critical, after this call app should never have the permission.
4839            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4840
4841            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4842        }
4843
4844        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4845    }
4846
4847    /**
4848     * Get the first event id for the permission.
4849     *
4850     * <p>There are four events for each permission: <ul>
4851     *     <li>Request permission: first id + 0</li>
4852     *     <li>Grant permission: first id + 1</li>
4853     *     <li>Request for permission denied: first id + 2</li>
4854     *     <li>Revoke permission: first id + 3</li>
4855     * </ul></p>
4856     *
4857     * @param name name of the permission
4858     *
4859     * @return The first event id for the permission
4860     */
4861    private static int getBaseEventId(@NonNull String name) {
4862        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4863
4864        if (eventIdIndex == -1) {
4865            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4866                    || "user".equals(Build.TYPE)) {
4867                Log.i(TAG, "Unknown permission " + name);
4868
4869                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4870            } else {
4871                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4872                //
4873                // Also update
4874                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4875                // - metrics_constants.proto
4876                throw new IllegalStateException("Unknown permission " + name);
4877            }
4878        }
4879
4880        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4881    }
4882
4883    /**
4884     * Log that a permission was revoked.
4885     *
4886     * @param context Context of the caller
4887     * @param name name of the permission
4888     * @param packageName package permission if for
4889     */
4890    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4891            @NonNull String packageName) {
4892        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4893    }
4894
4895    /**
4896     * Log that a permission request was granted.
4897     *
4898     * @param context Context of the caller
4899     * @param name name of the permission
4900     * @param packageName package permission if for
4901     */
4902    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4903            @NonNull String packageName) {
4904        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4905    }
4906
4907    @Override
4908    public void resetRuntimePermissions() {
4909        mContext.enforceCallingOrSelfPermission(
4910                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4911                "revokeRuntimePermission");
4912
4913        int callingUid = Binder.getCallingUid();
4914        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4915            mContext.enforceCallingOrSelfPermission(
4916                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4917                    "resetRuntimePermissions");
4918        }
4919
4920        synchronized (mPackages) {
4921            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4922            for (int userId : UserManagerService.getInstance().getUserIds()) {
4923                final int packageCount = mPackages.size();
4924                for (int i = 0; i < packageCount; i++) {
4925                    PackageParser.Package pkg = mPackages.valueAt(i);
4926                    if (!(pkg.mExtras instanceof PackageSetting)) {
4927                        continue;
4928                    }
4929                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4930                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4931                }
4932            }
4933        }
4934    }
4935
4936    @Override
4937    public int getPermissionFlags(String name, String packageName, int userId) {
4938        if (!sUserManager.exists(userId)) {
4939            return 0;
4940        }
4941
4942        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4943
4944        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4945                true /* requireFullPermission */, false /* checkShell */,
4946                "getPermissionFlags");
4947
4948        synchronized (mPackages) {
4949            final PackageParser.Package pkg = mPackages.get(packageName);
4950            if (pkg == null) {
4951                return 0;
4952            }
4953
4954            final BasePermission bp = mSettings.mPermissions.get(name);
4955            if (bp == null) {
4956                return 0;
4957            }
4958
4959            SettingBase sb = (SettingBase) pkg.mExtras;
4960            if (sb == null) {
4961                return 0;
4962            }
4963
4964            PermissionsState permissionsState = sb.getPermissionsState();
4965            return permissionsState.getPermissionFlags(name, userId);
4966        }
4967    }
4968
4969    @Override
4970    public void updatePermissionFlags(String name, String packageName, int flagMask,
4971            int flagValues, int userId) {
4972        if (!sUserManager.exists(userId)) {
4973            return;
4974        }
4975
4976        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4977
4978        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4979                true /* requireFullPermission */, true /* checkShell */,
4980                "updatePermissionFlags");
4981
4982        // Only the system can change these flags and nothing else.
4983        if (getCallingUid() != Process.SYSTEM_UID) {
4984            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4985            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4986            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4987            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4988            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4989        }
4990
4991        synchronized (mPackages) {
4992            final PackageParser.Package pkg = mPackages.get(packageName);
4993            if (pkg == null) {
4994                throw new IllegalArgumentException("Unknown package: " + packageName);
4995            }
4996
4997            final BasePermission bp = mSettings.mPermissions.get(name);
4998            if (bp == null) {
4999                throw new IllegalArgumentException("Unknown permission: " + name);
5000            }
5001
5002            SettingBase sb = (SettingBase) pkg.mExtras;
5003            if (sb == null) {
5004                throw new IllegalArgumentException("Unknown package: " + packageName);
5005            }
5006
5007            PermissionsState permissionsState = sb.getPermissionsState();
5008
5009            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5010
5011            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5012                // Install and runtime permissions are stored in different places,
5013                // so figure out what permission changed and persist the change.
5014                if (permissionsState.getInstallPermissionState(name) != null) {
5015                    scheduleWriteSettingsLocked();
5016                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5017                        || hadState) {
5018                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5019                }
5020            }
5021        }
5022    }
5023
5024    /**
5025     * Update the permission flags for all packages and runtime permissions of a user in order
5026     * to allow device or profile owner to remove POLICY_FIXED.
5027     */
5028    @Override
5029    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5030        if (!sUserManager.exists(userId)) {
5031            return;
5032        }
5033
5034        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5035
5036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5037                true /* requireFullPermission */, true /* checkShell */,
5038                "updatePermissionFlagsForAllApps");
5039
5040        // Only the system can change system fixed flags.
5041        if (getCallingUid() != Process.SYSTEM_UID) {
5042            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5043            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5044        }
5045
5046        synchronized (mPackages) {
5047            boolean changed = false;
5048            final int packageCount = mPackages.size();
5049            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5050                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5051                SettingBase sb = (SettingBase) pkg.mExtras;
5052                if (sb == null) {
5053                    continue;
5054                }
5055                PermissionsState permissionsState = sb.getPermissionsState();
5056                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5057                        userId, flagMask, flagValues);
5058            }
5059            if (changed) {
5060                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5061            }
5062        }
5063    }
5064
5065    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5066        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5067                != PackageManager.PERMISSION_GRANTED
5068            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5069                != PackageManager.PERMISSION_GRANTED) {
5070            throw new SecurityException(message + " requires "
5071                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5072                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5073        }
5074    }
5075
5076    @Override
5077    public boolean shouldShowRequestPermissionRationale(String permissionName,
5078            String packageName, int userId) {
5079        if (UserHandle.getCallingUserId() != userId) {
5080            mContext.enforceCallingPermission(
5081                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5082                    "canShowRequestPermissionRationale for user " + userId);
5083        }
5084
5085        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5086        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5087            return false;
5088        }
5089
5090        if (checkPermission(permissionName, packageName, userId)
5091                == PackageManager.PERMISSION_GRANTED) {
5092            return false;
5093        }
5094
5095        final int flags;
5096
5097        final long identity = Binder.clearCallingIdentity();
5098        try {
5099            flags = getPermissionFlags(permissionName,
5100                    packageName, userId);
5101        } finally {
5102            Binder.restoreCallingIdentity(identity);
5103        }
5104
5105        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5106                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5107                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5108
5109        if ((flags & fixedFlags) != 0) {
5110            return false;
5111        }
5112
5113        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5114    }
5115
5116    @Override
5117    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5118        mContext.enforceCallingOrSelfPermission(
5119                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5120                "addOnPermissionsChangeListener");
5121
5122        synchronized (mPackages) {
5123            mOnPermissionChangeListeners.addListenerLocked(listener);
5124        }
5125    }
5126
5127    @Override
5128    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5129        synchronized (mPackages) {
5130            mOnPermissionChangeListeners.removeListenerLocked(listener);
5131        }
5132    }
5133
5134    @Override
5135    public boolean isProtectedBroadcast(String actionName) {
5136        synchronized (mPackages) {
5137            if (mProtectedBroadcasts.contains(actionName)) {
5138                return true;
5139            } else if (actionName != null) {
5140                // TODO: remove these terrible hacks
5141                if (actionName.startsWith("android.net.netmon.lingerExpired")
5142                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5143                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5144                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5145                    return true;
5146                }
5147            }
5148        }
5149        return false;
5150    }
5151
5152    @Override
5153    public int checkSignatures(String pkg1, String pkg2) {
5154        synchronized (mPackages) {
5155            final PackageParser.Package p1 = mPackages.get(pkg1);
5156            final PackageParser.Package p2 = mPackages.get(pkg2);
5157            if (p1 == null || p1.mExtras == null
5158                    || p2 == null || p2.mExtras == null) {
5159                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5160            }
5161            return compareSignatures(p1.mSignatures, p2.mSignatures);
5162        }
5163    }
5164
5165    @Override
5166    public int checkUidSignatures(int uid1, int uid2) {
5167        // Map to base uids.
5168        uid1 = UserHandle.getAppId(uid1);
5169        uid2 = UserHandle.getAppId(uid2);
5170        // reader
5171        synchronized (mPackages) {
5172            Signature[] s1;
5173            Signature[] s2;
5174            Object obj = mSettings.getUserIdLPr(uid1);
5175            if (obj != null) {
5176                if (obj instanceof SharedUserSetting) {
5177                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5178                } else if (obj instanceof PackageSetting) {
5179                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5180                } else {
5181                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5182                }
5183            } else {
5184                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5185            }
5186            obj = mSettings.getUserIdLPr(uid2);
5187            if (obj != null) {
5188                if (obj instanceof SharedUserSetting) {
5189                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5190                } else if (obj instanceof PackageSetting) {
5191                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5192                } else {
5193                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5194                }
5195            } else {
5196                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5197            }
5198            return compareSignatures(s1, s2);
5199        }
5200    }
5201
5202    /**
5203     * This method should typically only be used when granting or revoking
5204     * permissions, since the app may immediately restart after this call.
5205     * <p>
5206     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5207     * guard your work against the app being relaunched.
5208     */
5209    private void killUid(int appId, int userId, String reason) {
5210        final long identity = Binder.clearCallingIdentity();
5211        try {
5212            IActivityManager am = ActivityManager.getService();
5213            if (am != null) {
5214                try {
5215                    am.killUid(appId, userId, reason);
5216                } catch (RemoteException e) {
5217                    /* ignore - same process */
5218                }
5219            }
5220        } finally {
5221            Binder.restoreCallingIdentity(identity);
5222        }
5223    }
5224
5225    /**
5226     * Compares two sets of signatures. Returns:
5227     * <br />
5228     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5229     * <br />
5230     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5231     * <br />
5232     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5233     * <br />
5234     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5235     * <br />
5236     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5237     */
5238    static int compareSignatures(Signature[] s1, Signature[] s2) {
5239        if (s1 == null) {
5240            return s2 == null
5241                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5242                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5243        }
5244
5245        if (s2 == null) {
5246            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5247        }
5248
5249        if (s1.length != s2.length) {
5250            return PackageManager.SIGNATURE_NO_MATCH;
5251        }
5252
5253        // Since both signature sets are of size 1, we can compare without HashSets.
5254        if (s1.length == 1) {
5255            return s1[0].equals(s2[0]) ?
5256                    PackageManager.SIGNATURE_MATCH :
5257                    PackageManager.SIGNATURE_NO_MATCH;
5258        }
5259
5260        ArraySet<Signature> set1 = new ArraySet<Signature>();
5261        for (Signature sig : s1) {
5262            set1.add(sig);
5263        }
5264        ArraySet<Signature> set2 = new ArraySet<Signature>();
5265        for (Signature sig : s2) {
5266            set2.add(sig);
5267        }
5268        // Make sure s2 contains all signatures in s1.
5269        if (set1.equals(set2)) {
5270            return PackageManager.SIGNATURE_MATCH;
5271        }
5272        return PackageManager.SIGNATURE_NO_MATCH;
5273    }
5274
5275    /**
5276     * If the database version for this type of package (internal storage or
5277     * external storage) is less than the version where package signatures
5278     * were updated, return true.
5279     */
5280    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5281        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5282        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5283    }
5284
5285    /**
5286     * Used for backward compatibility to make sure any packages with
5287     * certificate chains get upgraded to the new style. {@code existingSigs}
5288     * will be in the old format (since they were stored on disk from before the
5289     * system upgrade) and {@code scannedSigs} will be in the newer format.
5290     */
5291    private int compareSignaturesCompat(PackageSignatures existingSigs,
5292            PackageParser.Package scannedPkg) {
5293        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5294            return PackageManager.SIGNATURE_NO_MATCH;
5295        }
5296
5297        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5298        for (Signature sig : existingSigs.mSignatures) {
5299            existingSet.add(sig);
5300        }
5301        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5302        for (Signature sig : scannedPkg.mSignatures) {
5303            try {
5304                Signature[] chainSignatures = sig.getChainSignatures();
5305                for (Signature chainSig : chainSignatures) {
5306                    scannedCompatSet.add(chainSig);
5307                }
5308            } catch (CertificateEncodingException e) {
5309                scannedCompatSet.add(sig);
5310            }
5311        }
5312        /*
5313         * Make sure the expanded scanned set contains all signatures in the
5314         * existing one.
5315         */
5316        if (scannedCompatSet.equals(existingSet)) {
5317            // Migrate the old signatures to the new scheme.
5318            existingSigs.assignSignatures(scannedPkg.mSignatures);
5319            // The new KeySets will be re-added later in the scanning process.
5320            synchronized (mPackages) {
5321                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5322            }
5323            return PackageManager.SIGNATURE_MATCH;
5324        }
5325        return PackageManager.SIGNATURE_NO_MATCH;
5326    }
5327
5328    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5329        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5330        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5331    }
5332
5333    private int compareSignaturesRecover(PackageSignatures existingSigs,
5334            PackageParser.Package scannedPkg) {
5335        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5336            return PackageManager.SIGNATURE_NO_MATCH;
5337        }
5338
5339        String msg = null;
5340        try {
5341            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5342                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5343                        + scannedPkg.packageName);
5344                return PackageManager.SIGNATURE_MATCH;
5345            }
5346        } catch (CertificateException e) {
5347            msg = e.getMessage();
5348        }
5349
5350        logCriticalInfo(Log.INFO,
5351                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5352        return PackageManager.SIGNATURE_NO_MATCH;
5353    }
5354
5355    @Override
5356    public List<String> getAllPackages() {
5357        synchronized (mPackages) {
5358            return new ArrayList<String>(mPackages.keySet());
5359        }
5360    }
5361
5362    @Override
5363    public String[] getPackagesForUid(int uid) {
5364        final int userId = UserHandle.getUserId(uid);
5365        uid = UserHandle.getAppId(uid);
5366        // reader
5367        synchronized (mPackages) {
5368            Object obj = mSettings.getUserIdLPr(uid);
5369            if (obj instanceof SharedUserSetting) {
5370                final SharedUserSetting sus = (SharedUserSetting) obj;
5371                final int N = sus.packages.size();
5372                String[] res = new String[N];
5373                final Iterator<PackageSetting> it = sus.packages.iterator();
5374                int i = 0;
5375                while (it.hasNext()) {
5376                    PackageSetting ps = it.next();
5377                    if (ps.getInstalled(userId)) {
5378                        res[i++] = ps.name;
5379                    } else {
5380                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5381                    }
5382                }
5383                return res;
5384            } else if (obj instanceof PackageSetting) {
5385                final PackageSetting ps = (PackageSetting) obj;
5386                if (ps.getInstalled(userId)) {
5387                    return new String[]{ps.name};
5388                }
5389            }
5390        }
5391        return null;
5392    }
5393
5394    @Override
5395    public String getNameForUid(int uid) {
5396        // reader
5397        synchronized (mPackages) {
5398            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5399            if (obj instanceof SharedUserSetting) {
5400                final SharedUserSetting sus = (SharedUserSetting) obj;
5401                return sus.name + ":" + sus.userId;
5402            } else if (obj instanceof PackageSetting) {
5403                final PackageSetting ps = (PackageSetting) obj;
5404                return ps.name;
5405            }
5406        }
5407        return null;
5408    }
5409
5410    @Override
5411    public int getUidForSharedUser(String sharedUserName) {
5412        if(sharedUserName == null) {
5413            return -1;
5414        }
5415        // reader
5416        synchronized (mPackages) {
5417            SharedUserSetting suid;
5418            try {
5419                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5420                if (suid != null) {
5421                    return suid.userId;
5422                }
5423            } catch (PackageManagerException ignore) {
5424                // can't happen, but, still need to catch it
5425            }
5426            return -1;
5427        }
5428    }
5429
5430    @Override
5431    public int getFlagsForUid(int uid) {
5432        synchronized (mPackages) {
5433            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5434            if (obj instanceof SharedUserSetting) {
5435                final SharedUserSetting sus = (SharedUserSetting) obj;
5436                return sus.pkgFlags;
5437            } else if (obj instanceof PackageSetting) {
5438                final PackageSetting ps = (PackageSetting) obj;
5439                return ps.pkgFlags;
5440            }
5441        }
5442        return 0;
5443    }
5444
5445    @Override
5446    public int getPrivateFlagsForUid(int uid) {
5447        synchronized (mPackages) {
5448            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5449            if (obj instanceof SharedUserSetting) {
5450                final SharedUserSetting sus = (SharedUserSetting) obj;
5451                return sus.pkgPrivateFlags;
5452            } else if (obj instanceof PackageSetting) {
5453                final PackageSetting ps = (PackageSetting) obj;
5454                return ps.pkgPrivateFlags;
5455            }
5456        }
5457        return 0;
5458    }
5459
5460    @Override
5461    public boolean isUidPrivileged(int uid) {
5462        uid = UserHandle.getAppId(uid);
5463        // reader
5464        synchronized (mPackages) {
5465            Object obj = mSettings.getUserIdLPr(uid);
5466            if (obj instanceof SharedUserSetting) {
5467                final SharedUserSetting sus = (SharedUserSetting) obj;
5468                final Iterator<PackageSetting> it = sus.packages.iterator();
5469                while (it.hasNext()) {
5470                    if (it.next().isPrivileged()) {
5471                        return true;
5472                    }
5473                }
5474            } else if (obj instanceof PackageSetting) {
5475                final PackageSetting ps = (PackageSetting) obj;
5476                return ps.isPrivileged();
5477            }
5478        }
5479        return false;
5480    }
5481
5482    @Override
5483    public String[] getAppOpPermissionPackages(String permissionName) {
5484        synchronized (mPackages) {
5485            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5486            if (pkgs == null) {
5487                return null;
5488            }
5489            return pkgs.toArray(new String[pkgs.size()]);
5490        }
5491    }
5492
5493    @Override
5494    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5495            int flags, int userId) {
5496        try {
5497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5498
5499            if (!sUserManager.exists(userId)) return null;
5500            flags = updateFlagsForResolve(flags, userId, intent);
5501            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5502                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5503
5504            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5505            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5506                    flags, userId);
5507            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5508
5509            final ResolveInfo bestChoice =
5510                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5511            return bestChoice;
5512        } finally {
5513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5514        }
5515    }
5516
5517    @Override
5518    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5519        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5520            throw new SecurityException(
5521                    "findPersistentPreferredActivity can only be run by the system");
5522        }
5523        if (!sUserManager.exists(userId)) {
5524            return null;
5525        }
5526        intent = updateIntentForResolve(intent);
5527        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5528        final int flags = updateFlagsForResolve(0, userId, intent);
5529        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5530                userId);
5531        synchronized (mPackages) {
5532            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5533                    userId);
5534        }
5535    }
5536
5537    @Override
5538    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5539            IntentFilter filter, int match, ComponentName activity) {
5540        final int userId = UserHandle.getCallingUserId();
5541        if (DEBUG_PREFERRED) {
5542            Log.v(TAG, "setLastChosenActivity intent=" + intent
5543                + " resolvedType=" + resolvedType
5544                + " flags=" + flags
5545                + " filter=" + filter
5546                + " match=" + match
5547                + " activity=" + activity);
5548            filter.dump(new PrintStreamPrinter(System.out), "    ");
5549        }
5550        intent.setComponent(null);
5551        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5552                userId);
5553        // Find any earlier preferred or last chosen entries and nuke them
5554        findPreferredActivity(intent, resolvedType,
5555                flags, query, 0, false, true, false, userId);
5556        // Add the new activity as the last chosen for this filter
5557        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5558                "Setting last chosen");
5559    }
5560
5561    @Override
5562    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5563        final int userId = UserHandle.getCallingUserId();
5564        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5565        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5566                userId);
5567        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5568                false, false, false, userId);
5569    }
5570
5571    private boolean isEphemeralDisabled() {
5572        // ephemeral apps have been disabled across the board
5573        if (DISABLE_EPHEMERAL_APPS) {
5574            return true;
5575        }
5576        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5577        if (!mSystemReady) {
5578            return true;
5579        }
5580        // we can't get a content resolver until the system is ready; these checks must happen last
5581        final ContentResolver resolver = mContext.getContentResolver();
5582        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5583            return true;
5584        }
5585        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5586    }
5587
5588    private boolean isEphemeralAllowed(
5589            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5590            boolean skipPackageCheck) {
5591        // Short circuit and return early if possible.
5592        if (isEphemeralDisabled()) {
5593            return false;
5594        }
5595        final int callingUser = UserHandle.getCallingUserId();
5596        if (callingUser != UserHandle.USER_SYSTEM) {
5597            return false;
5598        }
5599        if (mEphemeralResolverConnection == null) {
5600            return false;
5601        }
5602        if (mEphemeralInstallerComponent == null) {
5603            return false;
5604        }
5605        if (intent.getComponent() != null) {
5606            return false;
5607        }
5608        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5609            return false;
5610        }
5611        if (!skipPackageCheck && intent.getPackage() != null) {
5612            return false;
5613        }
5614        final boolean isWebUri = hasWebURI(intent);
5615        if (!isWebUri || intent.getData().getHost() == null) {
5616            return false;
5617        }
5618        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5619        synchronized (mPackages) {
5620            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5621            for (int n = 0; n < count; n++) {
5622                ResolveInfo info = resolvedActivities.get(n);
5623                String packageName = info.activityInfo.packageName;
5624                PackageSetting ps = mSettings.mPackages.get(packageName);
5625                if (ps != null) {
5626                    // Try to get the status from User settings first
5627                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5628                    int status = (int) (packedStatus >> 32);
5629                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5630                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5631                        if (DEBUG_EPHEMERAL) {
5632                            Slog.v(TAG, "DENY ephemeral apps;"
5633                                + " pkg: " + packageName + ", status: " + status);
5634                        }
5635                        return false;
5636                    }
5637                }
5638            }
5639        }
5640        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5641        return true;
5642    }
5643
5644    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5645            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5646            int userId) {
5647        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5648                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5649                        callingPackage, userId));
5650        mHandler.sendMessage(msg);
5651    }
5652
5653    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5654            int flags, List<ResolveInfo> query, int userId) {
5655        if (query != null) {
5656            final int N = query.size();
5657            if (N == 1) {
5658                return query.get(0);
5659            } else if (N > 1) {
5660                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5661                // If there is more than one activity with the same priority,
5662                // then let the user decide between them.
5663                ResolveInfo r0 = query.get(0);
5664                ResolveInfo r1 = query.get(1);
5665                if (DEBUG_INTENT_MATCHING || debug) {
5666                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5667                            + r1.activityInfo.name + "=" + r1.priority);
5668                }
5669                // If the first activity has a higher priority, or a different
5670                // default, then it is always desirable to pick it.
5671                if (r0.priority != r1.priority
5672                        || r0.preferredOrder != r1.preferredOrder
5673                        || r0.isDefault != r1.isDefault) {
5674                    return query.get(0);
5675                }
5676                // If we have saved a preference for a preferred activity for
5677                // this Intent, use that.
5678                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5679                        flags, query, r0.priority, true, false, debug, userId);
5680                if (ri != null) {
5681                    return ri;
5682                }
5683                ri = new ResolveInfo(mResolveInfo);
5684                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5685                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5686                // If all of the options come from the same package, show the application's
5687                // label and icon instead of the generic resolver's.
5688                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5689                // and then throw away the ResolveInfo itself, meaning that the caller loses
5690                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5691                // a fallback for this case; we only set the target package's resources on
5692                // the ResolveInfo, not the ActivityInfo.
5693                final String intentPackage = intent.getPackage();
5694                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5695                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5696                    ri.resolvePackageName = intentPackage;
5697                    if (userNeedsBadging(userId)) {
5698                        ri.noResourceId = true;
5699                    } else {
5700                        ri.icon = appi.icon;
5701                    }
5702                    ri.iconResourceId = appi.icon;
5703                    ri.labelRes = appi.labelRes;
5704                }
5705                ri.activityInfo.applicationInfo = new ApplicationInfo(
5706                        ri.activityInfo.applicationInfo);
5707                if (userId != 0) {
5708                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5709                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5710                }
5711                // Make sure that the resolver is displayable in car mode
5712                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5713                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5714                return ri;
5715            }
5716        }
5717        return null;
5718    }
5719
5720    /**
5721     * Return true if the given list is not empty and all of its contents have
5722     * an activityInfo with the given package name.
5723     */
5724    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5725        if (ArrayUtils.isEmpty(list)) {
5726            return false;
5727        }
5728        for (int i = 0, N = list.size(); i < N; i++) {
5729            final ResolveInfo ri = list.get(i);
5730            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5731            if (ai == null || !packageName.equals(ai.packageName)) {
5732                return false;
5733            }
5734        }
5735        return true;
5736    }
5737
5738    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5739            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5740        final int N = query.size();
5741        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5742                .get(userId);
5743        // Get the list of persistent preferred activities that handle the intent
5744        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5745        List<PersistentPreferredActivity> pprefs = ppir != null
5746                ? ppir.queryIntent(intent, resolvedType,
5747                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5748                        userId)
5749                : null;
5750        if (pprefs != null && pprefs.size() > 0) {
5751            final int M = pprefs.size();
5752            for (int i=0; i<M; i++) {
5753                final PersistentPreferredActivity ppa = pprefs.get(i);
5754                if (DEBUG_PREFERRED || debug) {
5755                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5756                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5757                            + "\n  component=" + ppa.mComponent);
5758                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5759                }
5760                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5761                        flags | MATCH_DISABLED_COMPONENTS, userId);
5762                if (DEBUG_PREFERRED || debug) {
5763                    Slog.v(TAG, "Found persistent preferred activity:");
5764                    if (ai != null) {
5765                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5766                    } else {
5767                        Slog.v(TAG, "  null");
5768                    }
5769                }
5770                if (ai == null) {
5771                    // This previously registered persistent preferred activity
5772                    // component is no longer known. Ignore it and do NOT remove it.
5773                    continue;
5774                }
5775                for (int j=0; j<N; j++) {
5776                    final ResolveInfo ri = query.get(j);
5777                    if (!ri.activityInfo.applicationInfo.packageName
5778                            .equals(ai.applicationInfo.packageName)) {
5779                        continue;
5780                    }
5781                    if (!ri.activityInfo.name.equals(ai.name)) {
5782                        continue;
5783                    }
5784                    //  Found a persistent preference that can handle the intent.
5785                    if (DEBUG_PREFERRED || debug) {
5786                        Slog.v(TAG, "Returning persistent preferred activity: " +
5787                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5788                    }
5789                    return ri;
5790                }
5791            }
5792        }
5793        return null;
5794    }
5795
5796    // TODO: handle preferred activities missing while user has amnesia
5797    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5798            List<ResolveInfo> query, int priority, boolean always,
5799            boolean removeMatches, boolean debug, int userId) {
5800        if (!sUserManager.exists(userId)) return null;
5801        flags = updateFlagsForResolve(flags, userId, intent);
5802        intent = updateIntentForResolve(intent);
5803        // writer
5804        synchronized (mPackages) {
5805            // Try to find a matching persistent preferred activity.
5806            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5807                    debug, userId);
5808
5809            // If a persistent preferred activity matched, use it.
5810            if (pri != null) {
5811                return pri;
5812            }
5813
5814            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5815            // Get the list of preferred activities that handle the intent
5816            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5817            List<PreferredActivity> prefs = pir != null
5818                    ? pir.queryIntent(intent, resolvedType,
5819                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5820                            userId)
5821                    : null;
5822            if (prefs != null && prefs.size() > 0) {
5823                boolean changed = false;
5824                try {
5825                    // First figure out how good the original match set is.
5826                    // We will only allow preferred activities that came
5827                    // from the same match quality.
5828                    int match = 0;
5829
5830                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5831
5832                    final int N = query.size();
5833                    for (int j=0; j<N; j++) {
5834                        final ResolveInfo ri = query.get(j);
5835                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5836                                + ": 0x" + Integer.toHexString(match));
5837                        if (ri.match > match) {
5838                            match = ri.match;
5839                        }
5840                    }
5841
5842                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5843                            + Integer.toHexString(match));
5844
5845                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5846                    final int M = prefs.size();
5847                    for (int i=0; i<M; i++) {
5848                        final PreferredActivity pa = prefs.get(i);
5849                        if (DEBUG_PREFERRED || debug) {
5850                            Slog.v(TAG, "Checking PreferredActivity ds="
5851                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5852                                    + "\n  component=" + pa.mPref.mComponent);
5853                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5854                        }
5855                        if (pa.mPref.mMatch != match) {
5856                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5857                                    + Integer.toHexString(pa.mPref.mMatch));
5858                            continue;
5859                        }
5860                        // If it's not an "always" type preferred activity and that's what we're
5861                        // looking for, skip it.
5862                        if (always && !pa.mPref.mAlways) {
5863                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5864                            continue;
5865                        }
5866                        final ActivityInfo ai = getActivityInfo(
5867                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5868                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5869                                userId);
5870                        if (DEBUG_PREFERRED || debug) {
5871                            Slog.v(TAG, "Found preferred activity:");
5872                            if (ai != null) {
5873                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5874                            } else {
5875                                Slog.v(TAG, "  null");
5876                            }
5877                        }
5878                        if (ai == null) {
5879                            // This previously registered preferred activity
5880                            // component is no longer known.  Most likely an update
5881                            // to the app was installed and in the new version this
5882                            // component no longer exists.  Clean it up by removing
5883                            // it from the preferred activities list, and skip it.
5884                            Slog.w(TAG, "Removing dangling preferred activity: "
5885                                    + pa.mPref.mComponent);
5886                            pir.removeFilter(pa);
5887                            changed = true;
5888                            continue;
5889                        }
5890                        for (int j=0; j<N; j++) {
5891                            final ResolveInfo ri = query.get(j);
5892                            if (!ri.activityInfo.applicationInfo.packageName
5893                                    .equals(ai.applicationInfo.packageName)) {
5894                                continue;
5895                            }
5896                            if (!ri.activityInfo.name.equals(ai.name)) {
5897                                continue;
5898                            }
5899
5900                            if (removeMatches) {
5901                                pir.removeFilter(pa);
5902                                changed = true;
5903                                if (DEBUG_PREFERRED) {
5904                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5905                                }
5906                                break;
5907                            }
5908
5909                            // Okay we found a previously set preferred or last chosen app.
5910                            // If the result set is different from when this
5911                            // was created, we need to clear it and re-ask the
5912                            // user their preference, if we're looking for an "always" type entry.
5913                            if (always && !pa.mPref.sameSet(query)) {
5914                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5915                                        + intent + " type " + resolvedType);
5916                                if (DEBUG_PREFERRED) {
5917                                    Slog.v(TAG, "Removing preferred activity since set changed "
5918                                            + pa.mPref.mComponent);
5919                                }
5920                                pir.removeFilter(pa);
5921                                // Re-add the filter as a "last chosen" entry (!always)
5922                                PreferredActivity lastChosen = new PreferredActivity(
5923                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5924                                pir.addFilter(lastChosen);
5925                                changed = true;
5926                                return null;
5927                            }
5928
5929                            // Yay! Either the set matched or we're looking for the last chosen
5930                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5931                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5932                            return ri;
5933                        }
5934                    }
5935                } finally {
5936                    if (changed) {
5937                        if (DEBUG_PREFERRED) {
5938                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5939                        }
5940                        scheduleWritePackageRestrictionsLocked(userId);
5941                    }
5942                }
5943            }
5944        }
5945        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5946        return null;
5947    }
5948
5949    /*
5950     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5951     */
5952    @Override
5953    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5954            int targetUserId) {
5955        mContext.enforceCallingOrSelfPermission(
5956                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5957        List<CrossProfileIntentFilter> matches =
5958                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5959        if (matches != null) {
5960            int size = matches.size();
5961            for (int i = 0; i < size; i++) {
5962                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5963            }
5964        }
5965        if (hasWebURI(intent)) {
5966            // cross-profile app linking works only towards the parent.
5967            final UserInfo parent = getProfileParent(sourceUserId);
5968            synchronized(mPackages) {
5969                int flags = updateFlagsForResolve(0, parent.id, intent);
5970                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5971                        intent, resolvedType, flags, sourceUserId, parent.id);
5972                return xpDomainInfo != null;
5973            }
5974        }
5975        return false;
5976    }
5977
5978    private UserInfo getProfileParent(int userId) {
5979        final long identity = Binder.clearCallingIdentity();
5980        try {
5981            return sUserManager.getProfileParent(userId);
5982        } finally {
5983            Binder.restoreCallingIdentity(identity);
5984        }
5985    }
5986
5987    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5988            String resolvedType, int userId) {
5989        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5990        if (resolver != null) {
5991            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
5992        }
5993        return null;
5994    }
5995
5996    @Override
5997    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5998            String resolvedType, int flags, int userId) {
5999        try {
6000            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6001
6002            return new ParceledListSlice<>(
6003                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6004        } finally {
6005            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6006        }
6007    }
6008
6009    /**
6010     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6011     * instant, returns {@code null}.
6012     */
6013    private String getInstantAppPackageName(int callingUid) {
6014        final int appId = UserHandle.getAppId(callingUid);
6015        synchronized (mPackages) {
6016            final Object obj = mSettings.getUserIdLPr(appId);
6017            if (obj instanceof PackageSetting) {
6018                final PackageSetting ps = (PackageSetting) obj;
6019                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6020                return isInstantApp ? ps.pkg.packageName : null;
6021            }
6022        }
6023        return null;
6024    }
6025
6026    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6027            String resolvedType, int flags, int userId) {
6028        if (!sUserManager.exists(userId)) return Collections.emptyList();
6029        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6030        flags = updateFlagsForResolve(flags, userId, intent);
6031        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6032                false /* requireFullPermission */, false /* checkShell */,
6033                "query intent activities");
6034        ComponentName comp = intent.getComponent();
6035        if (comp == null) {
6036            if (intent.getSelector() != null) {
6037                intent = intent.getSelector();
6038                comp = intent.getComponent();
6039            }
6040        }
6041
6042        if (comp != null) {
6043            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6044            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6045            if (ai != null) {
6046                // When specifying an explicit component, we prevent the activity from being
6047                // used when either 1) the calling package is normal and the activity is within
6048                // an ephemeral application or 2) the calling package is ephemeral and the
6049                // activity is not visible to ephemeral applications.
6050                boolean matchEphemeral =
6051                        (flags & PackageManager.MATCH_INSTANT) != 0;
6052                boolean ephemeralVisibleOnly =
6053                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6054                boolean blockResolution =
6055                        (!matchEphemeral && instantAppPkgName == null
6056                                && (ai.applicationInfo.privateFlags
6057                                        & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0)
6058                        || (ephemeralVisibleOnly && instantAppPkgName != null
6059                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
6060                if (!blockResolution) {
6061                    final ResolveInfo ri = new ResolveInfo();
6062                    ri.activityInfo = ai;
6063                    list.add(ri);
6064                }
6065            }
6066            return list;
6067        }
6068
6069        // reader
6070        boolean sortResult = false;
6071        boolean addEphemeral = false;
6072        List<ResolveInfo> result;
6073        final String pkgName = intent.getPackage();
6074        synchronized (mPackages) {
6075            if (pkgName == null) {
6076                List<CrossProfileIntentFilter> matchingFilters =
6077                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6078                // Check for results that need to skip the current profile.
6079                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6080                        resolvedType, flags, userId);
6081                if (xpResolveInfo != null) {
6082                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6083                    xpResult.add(xpResolveInfo);
6084                    return filterForEphemeral(
6085                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6086                }
6087
6088                // Check for results in the current profile.
6089                result = filterIfNotSystemUser(mActivities.queryIntent(
6090                        intent, resolvedType, flags, userId), userId);
6091                addEphemeral =
6092                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6093
6094                // Check for cross profile results.
6095                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6096                xpResolveInfo = queryCrossProfileIntents(
6097                        matchingFilters, intent, resolvedType, flags, userId,
6098                        hasNonNegativePriorityResult);
6099                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6100                    boolean isVisibleToUser = filterIfNotSystemUser(
6101                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6102                    if (isVisibleToUser) {
6103                        result.add(xpResolveInfo);
6104                        sortResult = true;
6105                    }
6106                }
6107                if (hasWebURI(intent)) {
6108                    CrossProfileDomainInfo xpDomainInfo = null;
6109                    final UserInfo parent = getProfileParent(userId);
6110                    if (parent != null) {
6111                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6112                                flags, userId, parent.id);
6113                    }
6114                    if (xpDomainInfo != null) {
6115                        if (xpResolveInfo != null) {
6116                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6117                            // in the result.
6118                            result.remove(xpResolveInfo);
6119                        }
6120                        if (result.size() == 0 && !addEphemeral) {
6121                            // No result in current profile, but found candidate in parent user.
6122                            // And we are not going to add emphemeral app, so we can return the
6123                            // result straight away.
6124                            result.add(xpDomainInfo.resolveInfo);
6125                            return filterForEphemeral(result, instantAppPkgName);
6126                        }
6127                    } else if (result.size() <= 1 && !addEphemeral) {
6128                        // No result in parent user and <= 1 result in current profile, and we
6129                        // are not going to add emphemeral app, so we can return the result without
6130                        // further processing.
6131                        return filterForEphemeral(result, instantAppPkgName);
6132                    }
6133                    // We have more than one candidate (combining results from current and parent
6134                    // profile), so we need filtering and sorting.
6135                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6136                            intent, flags, result, xpDomainInfo, userId);
6137                    sortResult = true;
6138                }
6139            } else {
6140                final PackageParser.Package pkg = mPackages.get(pkgName);
6141                if (pkg != null) {
6142                    result = filterForEphemeral(filterIfNotSystemUser(
6143                            mActivities.queryIntentForPackage(
6144                                    intent, resolvedType, flags, pkg.activities, userId),
6145                            userId), instantAppPkgName);
6146                } else {
6147                    // the caller wants to resolve for a particular package; however, there
6148                    // were no installed results, so, try to find an ephemeral result
6149                    addEphemeral = isEphemeralAllowed(
6150                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6151                    result = new ArrayList<ResolveInfo>();
6152                }
6153            }
6154        }
6155        if (addEphemeral) {
6156            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6157            final EphemeralRequest requestObject = new EphemeralRequest(
6158                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6159                    null /*launchIntent*/, null /*callingPackage*/, userId);
6160            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6161                    mContext, mEphemeralResolverConnection, requestObject);
6162            if (intentInfo != null) {
6163                if (DEBUG_EPHEMERAL) {
6164                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6165                }
6166                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6167                ephemeralInstaller.ephemeralResponse = intentInfo;
6168                // make sure this resolver is the default
6169                ephemeralInstaller.isDefault = true;
6170                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6171                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6172                // add a non-generic filter
6173                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6174                ephemeralInstaller.filter.addDataPath(
6175                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6176                result.add(ephemeralInstaller);
6177            }
6178            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6179        }
6180        if (sortResult) {
6181            Collections.sort(result, mResolvePrioritySorter);
6182        }
6183        return filterForEphemeral(result, instantAppPkgName);
6184    }
6185
6186    private static class CrossProfileDomainInfo {
6187        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6188        ResolveInfo resolveInfo;
6189        /* Best domain verification status of the activities found in the other profile */
6190        int bestDomainVerificationStatus;
6191    }
6192
6193    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6194            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6195        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6196                sourceUserId)) {
6197            return null;
6198        }
6199        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6200                resolvedType, flags, parentUserId);
6201
6202        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6203            return null;
6204        }
6205        CrossProfileDomainInfo result = null;
6206        int size = resultTargetUser.size();
6207        for (int i = 0; i < size; i++) {
6208            ResolveInfo riTargetUser = resultTargetUser.get(i);
6209            // Intent filter verification is only for filters that specify a host. So don't return
6210            // those that handle all web uris.
6211            if (riTargetUser.handleAllWebDataURI) {
6212                continue;
6213            }
6214            String packageName = riTargetUser.activityInfo.packageName;
6215            PackageSetting ps = mSettings.mPackages.get(packageName);
6216            if (ps == null) {
6217                continue;
6218            }
6219            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6220            int status = (int)(verificationState >> 32);
6221            if (result == null) {
6222                result = new CrossProfileDomainInfo();
6223                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6224                        sourceUserId, parentUserId);
6225                result.bestDomainVerificationStatus = status;
6226            } else {
6227                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6228                        result.bestDomainVerificationStatus);
6229            }
6230        }
6231        // Don't consider matches with status NEVER across profiles.
6232        if (result != null && result.bestDomainVerificationStatus
6233                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6234            return null;
6235        }
6236        return result;
6237    }
6238
6239    /**
6240     * Verification statuses are ordered from the worse to the best, except for
6241     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6242     */
6243    private int bestDomainVerificationStatus(int status1, int status2) {
6244        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6245            return status2;
6246        }
6247        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6248            return status1;
6249        }
6250        return (int) MathUtils.max(status1, status2);
6251    }
6252
6253    private boolean isUserEnabled(int userId) {
6254        long callingId = Binder.clearCallingIdentity();
6255        try {
6256            UserInfo userInfo = sUserManager.getUserInfo(userId);
6257            return userInfo != null && userInfo.isEnabled();
6258        } finally {
6259            Binder.restoreCallingIdentity(callingId);
6260        }
6261    }
6262
6263    /**
6264     * Filter out activities with systemUserOnly flag set, when current user is not System.
6265     *
6266     * @return filtered list
6267     */
6268    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6269        if (userId == UserHandle.USER_SYSTEM) {
6270            return resolveInfos;
6271        }
6272        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6273            ResolveInfo info = resolveInfos.get(i);
6274            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6275                resolveInfos.remove(i);
6276            }
6277        }
6278        return resolveInfos;
6279    }
6280
6281    /**
6282     * Filters out ephemeral activities.
6283     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6284     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6285     *
6286     * @param resolveInfos The pre-filtered list of resolved activities
6287     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6288     *          is performed.
6289     * @return A filtered list of resolved activities.
6290     */
6291    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6292            String ephemeralPkgName) {
6293        if (ephemeralPkgName == null) {
6294            return resolveInfos;
6295        }
6296        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6297            ResolveInfo info = resolveInfos.get(i);
6298            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6299            // allow activities that are defined in the provided package
6300            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6301                continue;
6302            }
6303            // allow activities that have been explicitly exposed to ephemeral apps
6304            if (!isEphemeralApp
6305                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6306                continue;
6307            }
6308            resolveInfos.remove(i);
6309        }
6310        return resolveInfos;
6311    }
6312
6313    /**
6314     * @param resolveInfos list of resolve infos in descending priority order
6315     * @return if the list contains a resolve info with non-negative priority
6316     */
6317    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6318        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6319    }
6320
6321    private static boolean hasWebURI(Intent intent) {
6322        if (intent.getData() == null) {
6323            return false;
6324        }
6325        final String scheme = intent.getScheme();
6326        if (TextUtils.isEmpty(scheme)) {
6327            return false;
6328        }
6329        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6330    }
6331
6332    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6333            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6334            int userId) {
6335        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6336
6337        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6338            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6339                    candidates.size());
6340        }
6341
6342        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6343        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6344        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6345        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6346        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6347        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6348
6349        synchronized (mPackages) {
6350            final int count = candidates.size();
6351            // First, try to use linked apps. Partition the candidates into four lists:
6352            // one for the final results, one for the "do not use ever", one for "undefined status"
6353            // and finally one for "browser app type".
6354            for (int n=0; n<count; n++) {
6355                ResolveInfo info = candidates.get(n);
6356                String packageName = info.activityInfo.packageName;
6357                PackageSetting ps = mSettings.mPackages.get(packageName);
6358                if (ps != null) {
6359                    // Add to the special match all list (Browser use case)
6360                    if (info.handleAllWebDataURI) {
6361                        matchAllList.add(info);
6362                        continue;
6363                    }
6364                    // Try to get the status from User settings first
6365                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6366                    int status = (int)(packedStatus >> 32);
6367                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6368                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6369                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6370                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6371                                    + " : linkgen=" + linkGeneration);
6372                        }
6373                        // Use link-enabled generation as preferredOrder, i.e.
6374                        // prefer newly-enabled over earlier-enabled.
6375                        info.preferredOrder = linkGeneration;
6376                        alwaysList.add(info);
6377                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6378                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6379                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6380                        }
6381                        neverList.add(info);
6382                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6383                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6384                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6385                        }
6386                        alwaysAskList.add(info);
6387                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6388                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6389                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6390                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6391                        }
6392                        undefinedList.add(info);
6393                    }
6394                }
6395            }
6396
6397            // We'll want to include browser possibilities in a few cases
6398            boolean includeBrowser = false;
6399
6400            // First try to add the "always" resolution(s) for the current user, if any
6401            if (alwaysList.size() > 0) {
6402                result.addAll(alwaysList);
6403            } else {
6404                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6405                result.addAll(undefinedList);
6406                // Maybe add one for the other profile.
6407                if (xpDomainInfo != null && (
6408                        xpDomainInfo.bestDomainVerificationStatus
6409                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6410                    result.add(xpDomainInfo.resolveInfo);
6411                }
6412                includeBrowser = true;
6413            }
6414
6415            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6416            // If there were 'always' entries their preferred order has been set, so we also
6417            // back that off to make the alternatives equivalent
6418            if (alwaysAskList.size() > 0) {
6419                for (ResolveInfo i : result) {
6420                    i.preferredOrder = 0;
6421                }
6422                result.addAll(alwaysAskList);
6423                includeBrowser = true;
6424            }
6425
6426            if (includeBrowser) {
6427                // Also add browsers (all of them or only the default one)
6428                if (DEBUG_DOMAIN_VERIFICATION) {
6429                    Slog.v(TAG, "   ...including browsers in candidate set");
6430                }
6431                if ((matchFlags & MATCH_ALL) != 0) {
6432                    result.addAll(matchAllList);
6433                } else {
6434                    // Browser/generic handling case.  If there's a default browser, go straight
6435                    // to that (but only if there is no other higher-priority match).
6436                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6437                    int maxMatchPrio = 0;
6438                    ResolveInfo defaultBrowserMatch = null;
6439                    final int numCandidates = matchAllList.size();
6440                    for (int n = 0; n < numCandidates; n++) {
6441                        ResolveInfo info = matchAllList.get(n);
6442                        // track the highest overall match priority...
6443                        if (info.priority > maxMatchPrio) {
6444                            maxMatchPrio = info.priority;
6445                        }
6446                        // ...and the highest-priority default browser match
6447                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6448                            if (defaultBrowserMatch == null
6449                                    || (defaultBrowserMatch.priority < info.priority)) {
6450                                if (debug) {
6451                                    Slog.v(TAG, "Considering default browser match " + info);
6452                                }
6453                                defaultBrowserMatch = info;
6454                            }
6455                        }
6456                    }
6457                    if (defaultBrowserMatch != null
6458                            && defaultBrowserMatch.priority >= maxMatchPrio
6459                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6460                    {
6461                        if (debug) {
6462                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6463                        }
6464                        result.add(defaultBrowserMatch);
6465                    } else {
6466                        result.addAll(matchAllList);
6467                    }
6468                }
6469
6470                // If there is nothing selected, add all candidates and remove the ones that the user
6471                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6472                if (result.size() == 0) {
6473                    result.addAll(candidates);
6474                    result.removeAll(neverList);
6475                }
6476            }
6477        }
6478        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6479            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6480                    result.size());
6481            for (ResolveInfo info : result) {
6482                Slog.v(TAG, "  + " + info.activityInfo);
6483            }
6484        }
6485        return result;
6486    }
6487
6488    // Returns a packed value as a long:
6489    //
6490    // high 'int'-sized word: link status: undefined/ask/never/always.
6491    // low 'int'-sized word: relative priority among 'always' results.
6492    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6493        long result = ps.getDomainVerificationStatusForUser(userId);
6494        // if none available, get the master status
6495        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6496            if (ps.getIntentFilterVerificationInfo() != null) {
6497                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6498            }
6499        }
6500        return result;
6501    }
6502
6503    private ResolveInfo querySkipCurrentProfileIntents(
6504            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6505            int flags, int sourceUserId) {
6506        if (matchingFilters != null) {
6507            int size = matchingFilters.size();
6508            for (int i = 0; i < size; i ++) {
6509                CrossProfileIntentFilter filter = matchingFilters.get(i);
6510                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6511                    // Checking if there are activities in the target user that can handle the
6512                    // intent.
6513                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6514                            resolvedType, flags, sourceUserId);
6515                    if (resolveInfo != null) {
6516                        return resolveInfo;
6517                    }
6518                }
6519            }
6520        }
6521        return null;
6522    }
6523
6524    // Return matching ResolveInfo in target user if any.
6525    private ResolveInfo queryCrossProfileIntents(
6526            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6527            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6528        if (matchingFilters != null) {
6529            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6530            // match the same intent. For performance reasons, it is better not to
6531            // run queryIntent twice for the same userId
6532            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6533            int size = matchingFilters.size();
6534            for (int i = 0; i < size; i++) {
6535                CrossProfileIntentFilter filter = matchingFilters.get(i);
6536                int targetUserId = filter.getTargetUserId();
6537                boolean skipCurrentProfile =
6538                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6539                boolean skipCurrentProfileIfNoMatchFound =
6540                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6541                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6542                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6543                    // Checking if there are activities in the target user that can handle the
6544                    // intent.
6545                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6546                            resolvedType, flags, sourceUserId);
6547                    if (resolveInfo != null) return resolveInfo;
6548                    alreadyTriedUserIds.put(targetUserId, true);
6549                }
6550            }
6551        }
6552        return null;
6553    }
6554
6555    /**
6556     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6557     * will forward the intent to the filter's target user.
6558     * Otherwise, returns null.
6559     */
6560    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6561            String resolvedType, int flags, int sourceUserId) {
6562        int targetUserId = filter.getTargetUserId();
6563        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6564                resolvedType, flags, targetUserId);
6565        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6566            // If all the matches in the target profile are suspended, return null.
6567            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6568                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6569                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6570                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6571                            targetUserId);
6572                }
6573            }
6574        }
6575        return null;
6576    }
6577
6578    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6579            int sourceUserId, int targetUserId) {
6580        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6581        long ident = Binder.clearCallingIdentity();
6582        boolean targetIsProfile;
6583        try {
6584            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6585        } finally {
6586            Binder.restoreCallingIdentity(ident);
6587        }
6588        String className;
6589        if (targetIsProfile) {
6590            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6591        } else {
6592            className = FORWARD_INTENT_TO_PARENT;
6593        }
6594        ComponentName forwardingActivityComponentName = new ComponentName(
6595                mAndroidApplication.packageName, className);
6596        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6597                sourceUserId);
6598        if (!targetIsProfile) {
6599            forwardingActivityInfo.showUserIcon = targetUserId;
6600            forwardingResolveInfo.noResourceId = true;
6601        }
6602        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6603        forwardingResolveInfo.priority = 0;
6604        forwardingResolveInfo.preferredOrder = 0;
6605        forwardingResolveInfo.match = 0;
6606        forwardingResolveInfo.isDefault = true;
6607        forwardingResolveInfo.filter = filter;
6608        forwardingResolveInfo.targetUserId = targetUserId;
6609        return forwardingResolveInfo;
6610    }
6611
6612    @Override
6613    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6614            Intent[] specifics, String[] specificTypes, Intent intent,
6615            String resolvedType, int flags, int userId) {
6616        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6617                specificTypes, intent, resolvedType, flags, userId));
6618    }
6619
6620    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6621            Intent[] specifics, String[] specificTypes, Intent intent,
6622            String resolvedType, int flags, int userId) {
6623        if (!sUserManager.exists(userId)) return Collections.emptyList();
6624        flags = updateFlagsForResolve(flags, userId, intent);
6625        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6626                false /* requireFullPermission */, false /* checkShell */,
6627                "query intent activity options");
6628        final String resultsAction = intent.getAction();
6629
6630        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6631                | PackageManager.GET_RESOLVED_FILTER, userId);
6632
6633        if (DEBUG_INTENT_MATCHING) {
6634            Log.v(TAG, "Query " + intent + ": " + results);
6635        }
6636
6637        int specificsPos = 0;
6638        int N;
6639
6640        // todo: note that the algorithm used here is O(N^2).  This
6641        // isn't a problem in our current environment, but if we start running
6642        // into situations where we have more than 5 or 10 matches then this
6643        // should probably be changed to something smarter...
6644
6645        // First we go through and resolve each of the specific items
6646        // that were supplied, taking care of removing any corresponding
6647        // duplicate items in the generic resolve list.
6648        if (specifics != null) {
6649            for (int i=0; i<specifics.length; i++) {
6650                final Intent sintent = specifics[i];
6651                if (sintent == null) {
6652                    continue;
6653                }
6654
6655                if (DEBUG_INTENT_MATCHING) {
6656                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6657                }
6658
6659                String action = sintent.getAction();
6660                if (resultsAction != null && resultsAction.equals(action)) {
6661                    // If this action was explicitly requested, then don't
6662                    // remove things that have it.
6663                    action = null;
6664                }
6665
6666                ResolveInfo ri = null;
6667                ActivityInfo ai = null;
6668
6669                ComponentName comp = sintent.getComponent();
6670                if (comp == null) {
6671                    ri = resolveIntent(
6672                        sintent,
6673                        specificTypes != null ? specificTypes[i] : null,
6674                            flags, userId);
6675                    if (ri == null) {
6676                        continue;
6677                    }
6678                    if (ri == mResolveInfo) {
6679                        // ACK!  Must do something better with this.
6680                    }
6681                    ai = ri.activityInfo;
6682                    comp = new ComponentName(ai.applicationInfo.packageName,
6683                            ai.name);
6684                } else {
6685                    ai = getActivityInfo(comp, flags, userId);
6686                    if (ai == null) {
6687                        continue;
6688                    }
6689                }
6690
6691                // Look for any generic query activities that are duplicates
6692                // of this specific one, and remove them from the results.
6693                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6694                N = results.size();
6695                int j;
6696                for (j=specificsPos; j<N; j++) {
6697                    ResolveInfo sri = results.get(j);
6698                    if ((sri.activityInfo.name.equals(comp.getClassName())
6699                            && sri.activityInfo.applicationInfo.packageName.equals(
6700                                    comp.getPackageName()))
6701                        || (action != null && sri.filter.matchAction(action))) {
6702                        results.remove(j);
6703                        if (DEBUG_INTENT_MATCHING) Log.v(
6704                            TAG, "Removing duplicate item from " + j
6705                            + " due to specific " + specificsPos);
6706                        if (ri == null) {
6707                            ri = sri;
6708                        }
6709                        j--;
6710                        N--;
6711                    }
6712                }
6713
6714                // Add this specific item to its proper place.
6715                if (ri == null) {
6716                    ri = new ResolveInfo();
6717                    ri.activityInfo = ai;
6718                }
6719                results.add(specificsPos, ri);
6720                ri.specificIndex = i;
6721                specificsPos++;
6722            }
6723        }
6724
6725        // Now we go through the remaining generic results and remove any
6726        // duplicate actions that are found here.
6727        N = results.size();
6728        for (int i=specificsPos; i<N-1; i++) {
6729            final ResolveInfo rii = results.get(i);
6730            if (rii.filter == null) {
6731                continue;
6732            }
6733
6734            // Iterate over all of the actions of this result's intent
6735            // filter...  typically this should be just one.
6736            final Iterator<String> it = rii.filter.actionsIterator();
6737            if (it == null) {
6738                continue;
6739            }
6740            while (it.hasNext()) {
6741                final String action = it.next();
6742                if (resultsAction != null && resultsAction.equals(action)) {
6743                    // If this action was explicitly requested, then don't
6744                    // remove things that have it.
6745                    continue;
6746                }
6747                for (int j=i+1; j<N; j++) {
6748                    final ResolveInfo rij = results.get(j);
6749                    if (rij.filter != null && rij.filter.hasAction(action)) {
6750                        results.remove(j);
6751                        if (DEBUG_INTENT_MATCHING) Log.v(
6752                            TAG, "Removing duplicate item from " + j
6753                            + " due to action " + action + " at " + i);
6754                        j--;
6755                        N--;
6756                    }
6757                }
6758            }
6759
6760            // If the caller didn't request filter information, drop it now
6761            // so we don't have to marshall/unmarshall it.
6762            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6763                rii.filter = null;
6764            }
6765        }
6766
6767        // Filter out the caller activity if so requested.
6768        if (caller != null) {
6769            N = results.size();
6770            for (int i=0; i<N; i++) {
6771                ActivityInfo ainfo = results.get(i).activityInfo;
6772                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6773                        && caller.getClassName().equals(ainfo.name)) {
6774                    results.remove(i);
6775                    break;
6776                }
6777            }
6778        }
6779
6780        // If the caller didn't request filter information,
6781        // drop them now so we don't have to
6782        // marshall/unmarshall it.
6783        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6784            N = results.size();
6785            for (int i=0; i<N; i++) {
6786                results.get(i).filter = null;
6787            }
6788        }
6789
6790        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6791        return results;
6792    }
6793
6794    @Override
6795    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6796            String resolvedType, int flags, int userId) {
6797        return new ParceledListSlice<>(
6798                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6799    }
6800
6801    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6802            String resolvedType, int flags, int userId) {
6803        if (!sUserManager.exists(userId)) return Collections.emptyList();
6804        flags = updateFlagsForResolve(flags, userId, intent);
6805        ComponentName comp = intent.getComponent();
6806        if (comp == null) {
6807            if (intent.getSelector() != null) {
6808                intent = intent.getSelector();
6809                comp = intent.getComponent();
6810            }
6811        }
6812        if (comp != null) {
6813            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6814            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6815            if (ai != null) {
6816                ResolveInfo ri = new ResolveInfo();
6817                ri.activityInfo = ai;
6818                list.add(ri);
6819            }
6820            return list;
6821        }
6822
6823        // reader
6824        synchronized (mPackages) {
6825            String pkgName = intent.getPackage();
6826            if (pkgName == null) {
6827                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6828            }
6829            final PackageParser.Package pkg = mPackages.get(pkgName);
6830            if (pkg != null) {
6831                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6832                        userId);
6833            }
6834            return Collections.emptyList();
6835        }
6836    }
6837
6838    @Override
6839    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6840        if (!sUserManager.exists(userId)) return null;
6841        flags = updateFlagsForResolve(flags, userId, intent);
6842        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6843        if (query != null) {
6844            if (query.size() >= 1) {
6845                // If there is more than one service with the same priority,
6846                // just arbitrarily pick the first one.
6847                return query.get(0);
6848            }
6849        }
6850        return null;
6851    }
6852
6853    @Override
6854    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6855            String resolvedType, int flags, int userId) {
6856        return new ParceledListSlice<>(
6857                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6858    }
6859
6860    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6861            String resolvedType, int flags, int userId) {
6862        if (!sUserManager.exists(userId)) return Collections.emptyList();
6863        flags = updateFlagsForResolve(flags, userId, intent);
6864        ComponentName comp = intent.getComponent();
6865        if (comp == null) {
6866            if (intent.getSelector() != null) {
6867                intent = intent.getSelector();
6868                comp = intent.getComponent();
6869            }
6870        }
6871        if (comp != null) {
6872            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6873            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6874            if (si != null) {
6875                final ResolveInfo ri = new ResolveInfo();
6876                ri.serviceInfo = si;
6877                list.add(ri);
6878            }
6879            return list;
6880        }
6881
6882        // reader
6883        synchronized (mPackages) {
6884            String pkgName = intent.getPackage();
6885            if (pkgName == null) {
6886                return mServices.queryIntent(intent, resolvedType, flags, userId);
6887            }
6888            final PackageParser.Package pkg = mPackages.get(pkgName);
6889            if (pkg != null) {
6890                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6891                        userId);
6892            }
6893            return Collections.emptyList();
6894        }
6895    }
6896
6897    @Override
6898    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6899            String resolvedType, int flags, int userId) {
6900        return new ParceledListSlice<>(
6901                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6902    }
6903
6904    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6905            Intent intent, String resolvedType, int flags, int userId) {
6906        if (!sUserManager.exists(userId)) return Collections.emptyList();
6907        flags = updateFlagsForResolve(flags, userId, intent);
6908        ComponentName comp = intent.getComponent();
6909        if (comp == null) {
6910            if (intent.getSelector() != null) {
6911                intent = intent.getSelector();
6912                comp = intent.getComponent();
6913            }
6914        }
6915        if (comp != null) {
6916            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6917            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6918            if (pi != null) {
6919                final ResolveInfo ri = new ResolveInfo();
6920                ri.providerInfo = pi;
6921                list.add(ri);
6922            }
6923            return list;
6924        }
6925
6926        // reader
6927        synchronized (mPackages) {
6928            String pkgName = intent.getPackage();
6929            if (pkgName == null) {
6930                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6931            }
6932            final PackageParser.Package pkg = mPackages.get(pkgName);
6933            if (pkg != null) {
6934                return mProviders.queryIntentForPackage(
6935                        intent, resolvedType, flags, pkg.providers, userId);
6936            }
6937            return Collections.emptyList();
6938        }
6939    }
6940
6941    @Override
6942    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6943        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6944        flags = updateFlagsForPackage(flags, userId, null);
6945        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6947                true /* requireFullPermission */, false /* checkShell */,
6948                "get installed packages");
6949
6950        // writer
6951        synchronized (mPackages) {
6952            ArrayList<PackageInfo> list;
6953            if (listUninstalled) {
6954                list = new ArrayList<>(mSettings.mPackages.size());
6955                for (PackageSetting ps : mSettings.mPackages.values()) {
6956                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6957                        continue;
6958                    }
6959                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6960                    if (pi != null) {
6961                        list.add(pi);
6962                    }
6963                }
6964            } else {
6965                list = new ArrayList<>(mPackages.size());
6966                for (PackageParser.Package p : mPackages.values()) {
6967                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6968                            Binder.getCallingUid(), userId)) {
6969                        continue;
6970                    }
6971                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6972                            p.mExtras, flags, userId);
6973                    if (pi != null) {
6974                        list.add(pi);
6975                    }
6976                }
6977            }
6978
6979            return new ParceledListSlice<>(list);
6980        }
6981    }
6982
6983    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6984            String[] permissions, boolean[] tmp, int flags, int userId) {
6985        int numMatch = 0;
6986        final PermissionsState permissionsState = ps.getPermissionsState();
6987        for (int i=0; i<permissions.length; i++) {
6988            final String permission = permissions[i];
6989            if (permissionsState.hasPermission(permission, userId)) {
6990                tmp[i] = true;
6991                numMatch++;
6992            } else {
6993                tmp[i] = false;
6994            }
6995        }
6996        if (numMatch == 0) {
6997            return;
6998        }
6999        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7000
7001        // The above might return null in cases of uninstalled apps or install-state
7002        // skew across users/profiles.
7003        if (pi != null) {
7004            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7005                if (numMatch == permissions.length) {
7006                    pi.requestedPermissions = permissions;
7007                } else {
7008                    pi.requestedPermissions = new String[numMatch];
7009                    numMatch = 0;
7010                    for (int i=0; i<permissions.length; i++) {
7011                        if (tmp[i]) {
7012                            pi.requestedPermissions[numMatch] = permissions[i];
7013                            numMatch++;
7014                        }
7015                    }
7016                }
7017            }
7018            list.add(pi);
7019        }
7020    }
7021
7022    @Override
7023    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7024            String[] permissions, int flags, int userId) {
7025        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7026        flags = updateFlagsForPackage(flags, userId, permissions);
7027        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7028                true /* requireFullPermission */, false /* checkShell */,
7029                "get packages holding permissions");
7030        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7031
7032        // writer
7033        synchronized (mPackages) {
7034            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7035            boolean[] tmpBools = new boolean[permissions.length];
7036            if (listUninstalled) {
7037                for (PackageSetting ps : mSettings.mPackages.values()) {
7038                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7039                            userId);
7040                }
7041            } else {
7042                for (PackageParser.Package pkg : mPackages.values()) {
7043                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7044                    if (ps != null) {
7045                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7046                                userId);
7047                    }
7048                }
7049            }
7050
7051            return new ParceledListSlice<PackageInfo>(list);
7052        }
7053    }
7054
7055    @Override
7056    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7057        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7058        flags = updateFlagsForApplication(flags, userId, null);
7059        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7060
7061        // writer
7062        synchronized (mPackages) {
7063            ArrayList<ApplicationInfo> list;
7064            if (listUninstalled) {
7065                list = new ArrayList<>(mSettings.mPackages.size());
7066                for (PackageSetting ps : mSettings.mPackages.values()) {
7067                    ApplicationInfo ai;
7068                    int effectiveFlags = flags;
7069                    if (ps.isSystem()) {
7070                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7071                    }
7072                    if (ps.pkg != null) {
7073                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7074                            continue;
7075                        }
7076                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7077                                ps.readUserState(userId), userId);
7078                        if (ai != null) {
7079                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7080                        }
7081                    } else {
7082                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7083                        // and already converts to externally visible package name
7084                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7085                                Binder.getCallingUid(), effectiveFlags, userId);
7086                    }
7087                    if (ai != null) {
7088                        list.add(ai);
7089                    }
7090                }
7091            } else {
7092                list = new ArrayList<>(mPackages.size());
7093                for (PackageParser.Package p : mPackages.values()) {
7094                    if (p.mExtras != null) {
7095                        PackageSetting ps = (PackageSetting) p.mExtras;
7096                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7097                            continue;
7098                        }
7099                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7100                                ps.readUserState(userId), userId);
7101                        if (ai != null) {
7102                            ai.packageName = resolveExternalPackageNameLPr(p);
7103                            list.add(ai);
7104                        }
7105                    }
7106                }
7107            }
7108
7109            return new ParceledListSlice<>(list);
7110        }
7111    }
7112
7113    @Override
7114    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7115        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7116            return null;
7117        }
7118
7119        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7120                "getEphemeralApplications");
7121        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7122                true /* requireFullPermission */, false /* checkShell */,
7123                "getEphemeralApplications");
7124        synchronized (mPackages) {
7125            List<InstantAppInfo> instantApps = mInstantAppRegistry
7126                    .getInstantAppsLPr(userId);
7127            if (instantApps != null) {
7128                return new ParceledListSlice<>(instantApps);
7129            }
7130        }
7131        return null;
7132    }
7133
7134    @Override
7135    public boolean isInstantApp(String packageName, int userId) {
7136        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7137                true /* requireFullPermission */, false /* checkShell */,
7138                "isInstantApp");
7139        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7140            return false;
7141        }
7142
7143        if (!isCallerSameApp(packageName)) {
7144            return false;
7145        }
7146        synchronized (mPackages) {
7147            final PackageSetting ps = mSettings.mPackages.get(packageName);
7148            if (ps != null) {
7149                return ps.getInstantApp(userId);
7150            }
7151        }
7152        return false;
7153    }
7154
7155    @Override
7156    public byte[] getInstantAppCookie(String packageName, int userId) {
7157        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7158            return null;
7159        }
7160
7161        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7162                true /* requireFullPermission */, false /* checkShell */,
7163                "getInstantAppCookie");
7164        if (!isCallerSameApp(packageName)) {
7165            return null;
7166        }
7167        synchronized (mPackages) {
7168            return mInstantAppRegistry.getInstantAppCookieLPw(
7169                    packageName, userId);
7170        }
7171    }
7172
7173    @Override
7174    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7175        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7176            return true;
7177        }
7178
7179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7180                true /* requireFullPermission */, true /* checkShell */,
7181                "setInstantAppCookie");
7182        if (!isCallerSameApp(packageName)) {
7183            return false;
7184        }
7185        synchronized (mPackages) {
7186            return mInstantAppRegistry.setInstantAppCookieLPw(
7187                    packageName, cookie, userId);
7188        }
7189    }
7190
7191    @Override
7192    public Bitmap getInstantAppIcon(String packageName, int userId) {
7193        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7194            return null;
7195        }
7196
7197        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7198                "getInstantAppIcon");
7199
7200        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7201                true /* requireFullPermission */, false /* checkShell */,
7202                "getInstantAppIcon");
7203
7204        synchronized (mPackages) {
7205            return mInstantAppRegistry.getInstantAppIconLPw(
7206                    packageName, userId);
7207        }
7208    }
7209
7210    private boolean isCallerSameApp(String packageName) {
7211        PackageParser.Package pkg = mPackages.get(packageName);
7212        return pkg != null
7213                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7214    }
7215
7216    @Override
7217    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7218        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7219    }
7220
7221    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7222        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7223
7224        // reader
7225        synchronized (mPackages) {
7226            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7227            final int userId = UserHandle.getCallingUserId();
7228            while (i.hasNext()) {
7229                final PackageParser.Package p = i.next();
7230                if (p.applicationInfo == null) continue;
7231
7232                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7233                        && !p.applicationInfo.isDirectBootAware();
7234                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7235                        && p.applicationInfo.isDirectBootAware();
7236
7237                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7238                        && (!mSafeMode || isSystemApp(p))
7239                        && (matchesUnaware || matchesAware)) {
7240                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7241                    if (ps != null) {
7242                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7243                                ps.readUserState(userId), userId);
7244                        if (ai != null) {
7245                            finalList.add(ai);
7246                        }
7247                    }
7248                }
7249            }
7250        }
7251
7252        return finalList;
7253    }
7254
7255    @Override
7256    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7257        if (!sUserManager.exists(userId)) return null;
7258        flags = updateFlagsForComponent(flags, userId, name);
7259        // reader
7260        synchronized (mPackages) {
7261            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7262            PackageSetting ps = provider != null
7263                    ? mSettings.mPackages.get(provider.owner.packageName)
7264                    : null;
7265            return ps != null
7266                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7267                    ? PackageParser.generateProviderInfo(provider, flags,
7268                            ps.readUserState(userId), userId)
7269                    : null;
7270        }
7271    }
7272
7273    /**
7274     * @deprecated
7275     */
7276    @Deprecated
7277    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7278        // reader
7279        synchronized (mPackages) {
7280            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7281                    .entrySet().iterator();
7282            final int userId = UserHandle.getCallingUserId();
7283            while (i.hasNext()) {
7284                Map.Entry<String, PackageParser.Provider> entry = i.next();
7285                PackageParser.Provider p = entry.getValue();
7286                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7287
7288                if (ps != null && p.syncable
7289                        && (!mSafeMode || (p.info.applicationInfo.flags
7290                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7291                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7292                            ps.readUserState(userId), userId);
7293                    if (info != null) {
7294                        outNames.add(entry.getKey());
7295                        outInfo.add(info);
7296                    }
7297                }
7298            }
7299        }
7300    }
7301
7302    @Override
7303    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7304            int uid, int flags) {
7305        final int userId = processName != null ? UserHandle.getUserId(uid)
7306                : UserHandle.getCallingUserId();
7307        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7308        flags = updateFlagsForComponent(flags, userId, processName);
7309
7310        ArrayList<ProviderInfo> finalList = null;
7311        // reader
7312        synchronized (mPackages) {
7313            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7314            while (i.hasNext()) {
7315                final PackageParser.Provider p = i.next();
7316                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7317                if (ps != null && p.info.authority != null
7318                        && (processName == null
7319                                || (p.info.processName.equals(processName)
7320                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7321                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7322                    if (finalList == null) {
7323                        finalList = new ArrayList<ProviderInfo>(3);
7324                    }
7325                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7326                            ps.readUserState(userId), userId);
7327                    if (info != null) {
7328                        finalList.add(info);
7329                    }
7330                }
7331            }
7332        }
7333
7334        if (finalList != null) {
7335            Collections.sort(finalList, mProviderInitOrderSorter);
7336            return new ParceledListSlice<ProviderInfo>(finalList);
7337        }
7338
7339        return ParceledListSlice.emptyList();
7340    }
7341
7342    @Override
7343    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7344        // reader
7345        synchronized (mPackages) {
7346            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7347            return PackageParser.generateInstrumentationInfo(i, flags);
7348        }
7349    }
7350
7351    @Override
7352    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7353            String targetPackage, int flags) {
7354        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7355    }
7356
7357    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7358            int flags) {
7359        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7360
7361        // reader
7362        synchronized (mPackages) {
7363            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7364            while (i.hasNext()) {
7365                final PackageParser.Instrumentation p = i.next();
7366                if (targetPackage == null
7367                        || targetPackage.equals(p.info.targetPackage)) {
7368                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7369                            flags);
7370                    if (ii != null) {
7371                        finalList.add(ii);
7372                    }
7373                }
7374            }
7375        }
7376
7377        return finalList;
7378    }
7379
7380    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7381        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7382        if (overlays == null) {
7383            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7384            return;
7385        }
7386        for (PackageParser.Package opkg : overlays.values()) {
7387            // Not much to do if idmap fails: we already logged the error
7388            // and we certainly don't want to abort installation of pkg simply
7389            // because an overlay didn't fit properly. For these reasons,
7390            // ignore the return value of createIdmapForPackagePairLI.
7391            createIdmapForPackagePairLI(pkg, opkg);
7392        }
7393    }
7394
7395    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7396            PackageParser.Package opkg) {
7397        if (!opkg.mTrustedOverlay) {
7398            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7399                    opkg.baseCodePath + ": overlay not trusted");
7400            return false;
7401        }
7402        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7403        if (overlaySet == null) {
7404            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7405                    opkg.baseCodePath + " but target package has no known overlays");
7406            return false;
7407        }
7408        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7409        // TODO: generate idmap for split APKs
7410        try {
7411            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7412        } catch (InstallerException e) {
7413            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7414                    + opkg.baseCodePath);
7415            return false;
7416        }
7417        PackageParser.Package[] overlayArray =
7418            overlaySet.values().toArray(new PackageParser.Package[0]);
7419        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7420            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7421                return p1.mOverlayPriority - p2.mOverlayPriority;
7422            }
7423        };
7424        Arrays.sort(overlayArray, cmp);
7425
7426        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7427        int i = 0;
7428        for (PackageParser.Package p : overlayArray) {
7429            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7430        }
7431        return true;
7432    }
7433
7434    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7435        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7436        try {
7437            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7438        } finally {
7439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7440        }
7441    }
7442
7443    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7444        final File[] files = dir.listFiles();
7445        if (ArrayUtils.isEmpty(files)) {
7446            Log.d(TAG, "No files in app dir " + dir);
7447            return;
7448        }
7449
7450        if (DEBUG_PACKAGE_SCANNING) {
7451            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7452                    + " flags=0x" + Integer.toHexString(parseFlags));
7453        }
7454        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7455                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7456
7457        // Submit files for parsing in parallel
7458        int fileCount = 0;
7459        for (File file : files) {
7460            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7461                    && !PackageInstallerService.isStageName(file.getName());
7462            if (!isPackage) {
7463                // Ignore entries which are not packages
7464                continue;
7465            }
7466            parallelPackageParser.submit(file, parseFlags);
7467            fileCount++;
7468        }
7469
7470        // Process results one by one
7471        for (; fileCount > 0; fileCount--) {
7472            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7473            Throwable throwable = parseResult.throwable;
7474            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7475
7476            if (throwable == null) {
7477                // Static shared libraries have synthetic package names
7478                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7479                    renameStaticSharedLibraryPackage(parseResult.pkg);
7480                }
7481                try {
7482                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7483                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7484                                currentTime, null);
7485                    }
7486                } catch (PackageManagerException e) {
7487                    errorCode = e.error;
7488                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7489                }
7490            } else if (throwable instanceof PackageParser.PackageParserException) {
7491                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7492                        throwable;
7493                errorCode = e.error;
7494                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7495            } else {
7496                throw new IllegalStateException("Unexpected exception occurred while parsing "
7497                        + parseResult.scanFile, throwable);
7498            }
7499
7500            // Delete invalid userdata apps
7501            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7502                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7503                logCriticalInfo(Log.WARN,
7504                        "Deleting invalid package at " + parseResult.scanFile);
7505                removeCodePathLI(parseResult.scanFile);
7506            }
7507        }
7508        parallelPackageParser.close();
7509    }
7510
7511    private static File getSettingsProblemFile() {
7512        File dataDir = Environment.getDataDirectory();
7513        File systemDir = new File(dataDir, "system");
7514        File fname = new File(systemDir, "uiderrors.txt");
7515        return fname;
7516    }
7517
7518    static void reportSettingsProblem(int priority, String msg) {
7519        logCriticalInfo(priority, msg);
7520    }
7521
7522    static void logCriticalInfo(int priority, String msg) {
7523        Slog.println(priority, TAG, msg);
7524        EventLogTags.writePmCriticalInfo(msg);
7525        try {
7526            File fname = getSettingsProblemFile();
7527            FileOutputStream out = new FileOutputStream(fname, true);
7528            PrintWriter pw = new FastPrintWriter(out);
7529            SimpleDateFormat formatter = new SimpleDateFormat();
7530            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7531            pw.println(dateString + ": " + msg);
7532            pw.close();
7533            FileUtils.setPermissions(
7534                    fname.toString(),
7535                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7536                    -1, -1);
7537        } catch (java.io.IOException e) {
7538        }
7539    }
7540
7541    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7542        if (srcFile.isDirectory()) {
7543            final File baseFile = new File(pkg.baseCodePath);
7544            long maxModifiedTime = baseFile.lastModified();
7545            if (pkg.splitCodePaths != null) {
7546                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7547                    final File splitFile = new File(pkg.splitCodePaths[i]);
7548                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7549                }
7550            }
7551            return maxModifiedTime;
7552        }
7553        return srcFile.lastModified();
7554    }
7555
7556    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7557            final int policyFlags) throws PackageManagerException {
7558        // When upgrading from pre-N MR1, verify the package time stamp using the package
7559        // directory and not the APK file.
7560        final long lastModifiedTime = mIsPreNMR1Upgrade
7561                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7562        if (ps != null
7563                && ps.codePath.equals(srcFile)
7564                && ps.timeStamp == lastModifiedTime
7565                && !isCompatSignatureUpdateNeeded(pkg)
7566                && !isRecoverSignatureUpdateNeeded(pkg)) {
7567            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7568            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7569            ArraySet<PublicKey> signingKs;
7570            synchronized (mPackages) {
7571                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7572            }
7573            if (ps.signatures.mSignatures != null
7574                    && ps.signatures.mSignatures.length != 0
7575                    && signingKs != null) {
7576                // Optimization: reuse the existing cached certificates
7577                // if the package appears to be unchanged.
7578                pkg.mSignatures = ps.signatures.mSignatures;
7579                pkg.mSigningKeys = signingKs;
7580                return;
7581            }
7582
7583            Slog.w(TAG, "PackageSetting for " + ps.name
7584                    + " is missing signatures.  Collecting certs again to recover them.");
7585        } else {
7586            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7587        }
7588
7589        try {
7590            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7591            PackageParser.collectCertificates(pkg, policyFlags);
7592        } catch (PackageParserException e) {
7593            throw PackageManagerException.from(e);
7594        } finally {
7595            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7596        }
7597    }
7598
7599    /**
7600     *  Traces a package scan.
7601     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7602     */
7603    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7604            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7605        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7606        try {
7607            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7608        } finally {
7609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7610        }
7611    }
7612
7613    /**
7614     *  Scans a package and returns the newly parsed package.
7615     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7616     */
7617    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7618            long currentTime, UserHandle user) throws PackageManagerException {
7619        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7620        PackageParser pp = new PackageParser();
7621        pp.setSeparateProcesses(mSeparateProcesses);
7622        pp.setOnlyCoreApps(mOnlyCore);
7623        pp.setDisplayMetrics(mMetrics);
7624
7625        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7626            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7627        }
7628
7629        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7630        final PackageParser.Package pkg;
7631        try {
7632            pkg = pp.parsePackage(scanFile, parseFlags);
7633        } catch (PackageParserException e) {
7634            throw PackageManagerException.from(e);
7635        } finally {
7636            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7637        }
7638
7639        // Static shared libraries have synthetic package names
7640        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7641            renameStaticSharedLibraryPackage(pkg);
7642        }
7643
7644        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7645    }
7646
7647    /**
7648     *  Scans a package and returns the newly parsed package.
7649     *  @throws PackageManagerException on a parse error.
7650     */
7651    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7652            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7653            throws PackageManagerException {
7654        // If the package has children and this is the first dive in the function
7655        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7656        // packages (parent and children) would be successfully scanned before the
7657        // actual scan since scanning mutates internal state and we want to atomically
7658        // install the package and its children.
7659        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7660            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7661                scanFlags |= SCAN_CHECK_ONLY;
7662            }
7663        } else {
7664            scanFlags &= ~SCAN_CHECK_ONLY;
7665        }
7666
7667        // Scan the parent
7668        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7669                scanFlags, currentTime, user);
7670
7671        // Scan the children
7672        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7673        for (int i = 0; i < childCount; i++) {
7674            PackageParser.Package childPackage = pkg.childPackages.get(i);
7675            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7676                    currentTime, user);
7677        }
7678
7679
7680        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7681            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7682        }
7683
7684        return scannedPkg;
7685    }
7686
7687    /**
7688     *  Scans a package and returns the newly parsed package.
7689     *  @throws PackageManagerException on a parse error.
7690     */
7691    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7692            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7693            throws PackageManagerException {
7694        PackageSetting ps = null;
7695        PackageSetting updatedPkg;
7696        // reader
7697        synchronized (mPackages) {
7698            // Look to see if we already know about this package.
7699            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7700            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7701                // This package has been renamed to its original name.  Let's
7702                // use that.
7703                ps = mSettings.getPackageLPr(oldName);
7704            }
7705            // If there was no original package, see one for the real package name.
7706            if (ps == null) {
7707                ps = mSettings.getPackageLPr(pkg.packageName);
7708            }
7709            // Check to see if this package could be hiding/updating a system
7710            // package.  Must look for it either under the original or real
7711            // package name depending on our state.
7712            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7713            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7714
7715            // If this is a package we don't know about on the system partition, we
7716            // may need to remove disabled child packages on the system partition
7717            // or may need to not add child packages if the parent apk is updated
7718            // on the data partition and no longer defines this child package.
7719            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7720                // If this is a parent package for an updated system app and this system
7721                // app got an OTA update which no longer defines some of the child packages
7722                // we have to prune them from the disabled system packages.
7723                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7724                if (disabledPs != null) {
7725                    final int scannedChildCount = (pkg.childPackages != null)
7726                            ? pkg.childPackages.size() : 0;
7727                    final int disabledChildCount = disabledPs.childPackageNames != null
7728                            ? disabledPs.childPackageNames.size() : 0;
7729                    for (int i = 0; i < disabledChildCount; i++) {
7730                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7731                        boolean disabledPackageAvailable = false;
7732                        for (int j = 0; j < scannedChildCount; j++) {
7733                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7734                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7735                                disabledPackageAvailable = true;
7736                                break;
7737                            }
7738                         }
7739                         if (!disabledPackageAvailable) {
7740                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7741                         }
7742                    }
7743                }
7744            }
7745        }
7746
7747        boolean updatedPkgBetter = false;
7748        // First check if this is a system package that may involve an update
7749        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7750            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7751            // it needs to drop FLAG_PRIVILEGED.
7752            if (locationIsPrivileged(scanFile)) {
7753                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7754            } else {
7755                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7756            }
7757
7758            if (ps != null && !ps.codePath.equals(scanFile)) {
7759                // The path has changed from what was last scanned...  check the
7760                // version of the new path against what we have stored to determine
7761                // what to do.
7762                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7763                if (pkg.mVersionCode <= ps.versionCode) {
7764                    // The system package has been updated and the code path does not match
7765                    // Ignore entry. Skip it.
7766                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7767                            + " ignored: updated version " + ps.versionCode
7768                            + " better than this " + pkg.mVersionCode);
7769                    if (!updatedPkg.codePath.equals(scanFile)) {
7770                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7771                                + ps.name + " changing from " + updatedPkg.codePathString
7772                                + " to " + scanFile);
7773                        updatedPkg.codePath = scanFile;
7774                        updatedPkg.codePathString = scanFile.toString();
7775                        updatedPkg.resourcePath = scanFile;
7776                        updatedPkg.resourcePathString = scanFile.toString();
7777                    }
7778                    updatedPkg.pkg = pkg;
7779                    updatedPkg.versionCode = pkg.mVersionCode;
7780
7781                    // Update the disabled system child packages to point to the package too.
7782                    final int childCount = updatedPkg.childPackageNames != null
7783                            ? updatedPkg.childPackageNames.size() : 0;
7784                    for (int i = 0; i < childCount; i++) {
7785                        String childPackageName = updatedPkg.childPackageNames.get(i);
7786                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7787                                childPackageName);
7788                        if (updatedChildPkg != null) {
7789                            updatedChildPkg.pkg = pkg;
7790                            updatedChildPkg.versionCode = pkg.mVersionCode;
7791                        }
7792                    }
7793
7794                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7795                            + scanFile + " ignored: updated version " + ps.versionCode
7796                            + " better than this " + pkg.mVersionCode);
7797                } else {
7798                    // The current app on the system partition is better than
7799                    // what we have updated to on the data partition; switch
7800                    // back to the system partition version.
7801                    // At this point, its safely assumed that package installation for
7802                    // apps in system partition will go through. If not there won't be a working
7803                    // version of the app
7804                    // writer
7805                    synchronized (mPackages) {
7806                        // Just remove the loaded entries from package lists.
7807                        mPackages.remove(ps.name);
7808                    }
7809
7810                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7811                            + " reverting from " + ps.codePathString
7812                            + ": new version " + pkg.mVersionCode
7813                            + " better than installed " + ps.versionCode);
7814
7815                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7816                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7817                    synchronized (mInstallLock) {
7818                        args.cleanUpResourcesLI();
7819                    }
7820                    synchronized (mPackages) {
7821                        mSettings.enableSystemPackageLPw(ps.name);
7822                    }
7823                    updatedPkgBetter = true;
7824                }
7825            }
7826        }
7827
7828        if (updatedPkg != null) {
7829            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7830            // initially
7831            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7832
7833            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7834            // flag set initially
7835            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7836                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7837            }
7838        }
7839
7840        // Verify certificates against what was last scanned
7841        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7842
7843        /*
7844         * A new system app appeared, but we already had a non-system one of the
7845         * same name installed earlier.
7846         */
7847        boolean shouldHideSystemApp = false;
7848        if (updatedPkg == null && ps != null
7849                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7850            /*
7851             * Check to make sure the signatures match first. If they don't,
7852             * wipe the installed application and its data.
7853             */
7854            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7855                    != PackageManager.SIGNATURE_MATCH) {
7856                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7857                        + " signatures don't match existing userdata copy; removing");
7858                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7859                        "scanPackageInternalLI")) {
7860                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7861                }
7862                ps = null;
7863            } else {
7864                /*
7865                 * If the newly-added system app is an older version than the
7866                 * already installed version, hide it. It will be scanned later
7867                 * and re-added like an update.
7868                 */
7869                if (pkg.mVersionCode <= ps.versionCode) {
7870                    shouldHideSystemApp = true;
7871                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7872                            + " but new version " + pkg.mVersionCode + " better than installed "
7873                            + ps.versionCode + "; hiding system");
7874                } else {
7875                    /*
7876                     * The newly found system app is a newer version that the
7877                     * one previously installed. Simply remove the
7878                     * already-installed application and replace it with our own
7879                     * while keeping the application data.
7880                     */
7881                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7882                            + " reverting from " + ps.codePathString + ": new version "
7883                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7884                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7885                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7886                    synchronized (mInstallLock) {
7887                        args.cleanUpResourcesLI();
7888                    }
7889                }
7890            }
7891        }
7892
7893        // The apk is forward locked (not public) if its code and resources
7894        // are kept in different files. (except for app in either system or
7895        // vendor path).
7896        // TODO grab this value from PackageSettings
7897        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7898            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7899                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7900            }
7901        }
7902
7903        // TODO: extend to support forward-locked splits
7904        String resourcePath = null;
7905        String baseResourcePath = null;
7906        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7907            if (ps != null && ps.resourcePathString != null) {
7908                resourcePath = ps.resourcePathString;
7909                baseResourcePath = ps.resourcePathString;
7910            } else {
7911                // Should not happen at all. Just log an error.
7912                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7913            }
7914        } else {
7915            resourcePath = pkg.codePath;
7916            baseResourcePath = pkg.baseCodePath;
7917        }
7918
7919        // Set application objects path explicitly.
7920        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7921        pkg.setApplicationInfoCodePath(pkg.codePath);
7922        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7923        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7924        pkg.setApplicationInfoResourcePath(resourcePath);
7925        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7926        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7927
7928        final int userId = ((user == null) ? 0 : user.getIdentifier());
7929        if (ps != null && ps.getInstantApp(userId)) {
7930            scanFlags |= SCAN_AS_INSTANT_APP;
7931        }
7932
7933        // Note that we invoke the following method only if we are about to unpack an application
7934        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7935                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7936
7937        /*
7938         * If the system app should be overridden by a previously installed
7939         * data, hide the system app now and let the /data/app scan pick it up
7940         * again.
7941         */
7942        if (shouldHideSystemApp) {
7943            synchronized (mPackages) {
7944                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7945            }
7946        }
7947
7948        return scannedPkg;
7949    }
7950
7951    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7952        // Derive the new package synthetic package name
7953        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7954                + pkg.staticSharedLibVersion);
7955    }
7956
7957    private static String fixProcessName(String defProcessName,
7958            String processName) {
7959        if (processName == null) {
7960            return defProcessName;
7961        }
7962        return processName;
7963    }
7964
7965    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7966            throws PackageManagerException {
7967        if (pkgSetting.signatures.mSignatures != null) {
7968            // Already existing package. Make sure signatures match
7969            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7970                    == PackageManager.SIGNATURE_MATCH;
7971            if (!match) {
7972                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7973                        == PackageManager.SIGNATURE_MATCH;
7974            }
7975            if (!match) {
7976                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7977                        == PackageManager.SIGNATURE_MATCH;
7978            }
7979            if (!match) {
7980                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7981                        + pkg.packageName + " signatures do not match the "
7982                        + "previously installed version; ignoring!");
7983            }
7984        }
7985
7986        // Check for shared user signatures
7987        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7988            // Already existing package. Make sure signatures match
7989            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7990                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7991            if (!match) {
7992                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7993                        == PackageManager.SIGNATURE_MATCH;
7994            }
7995            if (!match) {
7996                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7997                        == PackageManager.SIGNATURE_MATCH;
7998            }
7999            if (!match) {
8000                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8001                        "Package " + pkg.packageName
8002                        + " has no signatures that match those in shared user "
8003                        + pkgSetting.sharedUser.name + "; ignoring!");
8004            }
8005        }
8006    }
8007
8008    /**
8009     * Enforces that only the system UID or root's UID can call a method exposed
8010     * via Binder.
8011     *
8012     * @param message used as message if SecurityException is thrown
8013     * @throws SecurityException if the caller is not system or root
8014     */
8015    private static final void enforceSystemOrRoot(String message) {
8016        final int uid = Binder.getCallingUid();
8017        if (uid != Process.SYSTEM_UID && uid != 0) {
8018            throw new SecurityException(message);
8019        }
8020    }
8021
8022    @Override
8023    public void performFstrimIfNeeded() {
8024        enforceSystemOrRoot("Only the system can request fstrim");
8025
8026        // Before everything else, see whether we need to fstrim.
8027        try {
8028            IStorageManager sm = PackageHelper.getStorageManager();
8029            if (sm != null) {
8030                boolean doTrim = false;
8031                final long interval = android.provider.Settings.Global.getLong(
8032                        mContext.getContentResolver(),
8033                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8034                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8035                if (interval > 0) {
8036                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8037                    if (timeSinceLast > interval) {
8038                        doTrim = true;
8039                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8040                                + "; running immediately");
8041                    }
8042                }
8043                if (doTrim) {
8044                    final boolean dexOptDialogShown;
8045                    synchronized (mPackages) {
8046                        dexOptDialogShown = mDexOptDialogShown;
8047                    }
8048                    if (!isFirstBoot() && dexOptDialogShown) {
8049                        try {
8050                            ActivityManager.getService().showBootMessage(
8051                                    mContext.getResources().getString(
8052                                            R.string.android_upgrading_fstrim), true);
8053                        } catch (RemoteException e) {
8054                        }
8055                    }
8056                    sm.runMaintenance();
8057                }
8058            } else {
8059                Slog.e(TAG, "storageManager service unavailable!");
8060            }
8061        } catch (RemoteException e) {
8062            // Can't happen; StorageManagerService is local
8063        }
8064    }
8065
8066    @Override
8067    public void updatePackagesIfNeeded() {
8068        enforceSystemOrRoot("Only the system can request package update");
8069
8070        // We need to re-extract after an OTA.
8071        boolean causeUpgrade = isUpgrade();
8072
8073        // First boot or factory reset.
8074        // Note: we also handle devices that are upgrading to N right now as if it is their
8075        //       first boot, as they do not have profile data.
8076        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8077
8078        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8079        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8080
8081        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8082            return;
8083        }
8084
8085        List<PackageParser.Package> pkgs;
8086        synchronized (mPackages) {
8087            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8088        }
8089
8090        final long startTime = System.nanoTime();
8091        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8092                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8093
8094        final int elapsedTimeSeconds =
8095                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8096
8097        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8098        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8099        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8100        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8101        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8102    }
8103
8104    /**
8105     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8106     * containing statistics about the invocation. The array consists of three elements,
8107     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8108     * and {@code numberOfPackagesFailed}.
8109     */
8110    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8111            String compilerFilter) {
8112
8113        int numberOfPackagesVisited = 0;
8114        int numberOfPackagesOptimized = 0;
8115        int numberOfPackagesSkipped = 0;
8116        int numberOfPackagesFailed = 0;
8117        final int numberOfPackagesToDexopt = pkgs.size();
8118
8119        for (PackageParser.Package pkg : pkgs) {
8120            numberOfPackagesVisited++;
8121
8122            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8123                if (DEBUG_DEXOPT) {
8124                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8125                }
8126                numberOfPackagesSkipped++;
8127                continue;
8128            }
8129
8130            if (DEBUG_DEXOPT) {
8131                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8132                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8133            }
8134
8135            if (showDialog) {
8136                try {
8137                    ActivityManager.getService().showBootMessage(
8138                            mContext.getResources().getString(R.string.android_upgrading_apk,
8139                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8140                } catch (RemoteException e) {
8141                }
8142                synchronized (mPackages) {
8143                    mDexOptDialogShown = true;
8144                }
8145            }
8146
8147            // If the OTA updates a system app which was previously preopted to a non-preopted state
8148            // the app might end up being verified at runtime. That's because by default the apps
8149            // are verify-profile but for preopted apps there's no profile.
8150            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8151            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8152            // filter (by default interpret-only).
8153            // Note that at this stage unused apps are already filtered.
8154            if (isSystemApp(pkg) &&
8155                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8156                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8157                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8158            }
8159
8160            // checkProfiles is false to avoid merging profiles during boot which
8161            // might interfere with background compilation (b/28612421).
8162            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8163            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8164            // trade-off worth doing to save boot time work.
8165            int dexOptStatus = performDexOptTraced(pkg.packageName,
8166                    false /* checkProfiles */,
8167                    compilerFilter,
8168                    false /* force */);
8169            switch (dexOptStatus) {
8170                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8171                    numberOfPackagesOptimized++;
8172                    break;
8173                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8174                    numberOfPackagesSkipped++;
8175                    break;
8176                case PackageDexOptimizer.DEX_OPT_FAILED:
8177                    numberOfPackagesFailed++;
8178                    break;
8179                default:
8180                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8181                    break;
8182            }
8183        }
8184
8185        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8186                numberOfPackagesFailed };
8187    }
8188
8189    @Override
8190    public void notifyPackageUse(String packageName, int reason) {
8191        synchronized (mPackages) {
8192            PackageParser.Package p = mPackages.get(packageName);
8193            if (p == null) {
8194                return;
8195            }
8196            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8197        }
8198    }
8199
8200    @Override
8201    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8202        int userId = UserHandle.getCallingUserId();
8203        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8204        if (ai == null) {
8205            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8206                + loadingPackageName + ", user=" + userId);
8207            return;
8208        }
8209        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8210    }
8211
8212    // TODO: this is not used nor needed. Delete it.
8213    @Override
8214    public boolean performDexOptIfNeeded(String packageName) {
8215        int dexOptStatus = performDexOptTraced(packageName,
8216                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8217        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8218    }
8219
8220    @Override
8221    public boolean performDexOpt(String packageName,
8222            boolean checkProfiles, int compileReason, boolean force) {
8223        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8224                getCompilerFilterForReason(compileReason), force);
8225        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8226    }
8227
8228    @Override
8229    public boolean performDexOptMode(String packageName,
8230            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8231        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8232                targetCompilerFilter, force);
8233        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8234    }
8235
8236    private int performDexOptTraced(String packageName,
8237                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8238        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8239        try {
8240            return performDexOptInternal(packageName, checkProfiles,
8241                    targetCompilerFilter, force);
8242        } finally {
8243            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8244        }
8245    }
8246
8247    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8248    // if the package can now be considered up to date for the given filter.
8249    private int performDexOptInternal(String packageName,
8250                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8251        PackageParser.Package p;
8252        synchronized (mPackages) {
8253            p = mPackages.get(packageName);
8254            if (p == null) {
8255                // Package could not be found. Report failure.
8256                return PackageDexOptimizer.DEX_OPT_FAILED;
8257            }
8258            mPackageUsage.maybeWriteAsync(mPackages);
8259            mCompilerStats.maybeWriteAsync();
8260        }
8261        long callingId = Binder.clearCallingIdentity();
8262        try {
8263            synchronized (mInstallLock) {
8264                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8265                        targetCompilerFilter, force);
8266            }
8267        } finally {
8268            Binder.restoreCallingIdentity(callingId);
8269        }
8270    }
8271
8272    public ArraySet<String> getOptimizablePackages() {
8273        ArraySet<String> pkgs = new ArraySet<String>();
8274        synchronized (mPackages) {
8275            for (PackageParser.Package p : mPackages.values()) {
8276                if (PackageDexOptimizer.canOptimizePackage(p)) {
8277                    pkgs.add(p.packageName);
8278                }
8279            }
8280        }
8281        return pkgs;
8282    }
8283
8284    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8285            boolean checkProfiles, String targetCompilerFilter,
8286            boolean force) {
8287        // Select the dex optimizer based on the force parameter.
8288        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8289        //       allocate an object here.
8290        PackageDexOptimizer pdo = force
8291                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8292                : mPackageDexOptimizer;
8293
8294        // Optimize all dependencies first. Note: we ignore the return value and march on
8295        // on errors.
8296        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8297        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8298        if (!deps.isEmpty()) {
8299            for (PackageParser.Package depPackage : deps) {
8300                // TODO: Analyze and investigate if we (should) profile libraries.
8301                // Currently this will do a full compilation of the library by default.
8302                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8303                        false /* checkProfiles */,
8304                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8305                        getOrCreateCompilerPackageStats(depPackage));
8306            }
8307        }
8308        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8309                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8310    }
8311
8312    // Performs dexopt on the used secondary dex files belonging to the given package.
8313    // Returns true if all dex files were process successfully (which could mean either dexopt or
8314    // skip). Returns false if any of the files caused errors.
8315    @Override
8316    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8317            boolean force) {
8318        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8319    }
8320
8321    /**
8322     * Reconcile the information we have about the secondary dex files belonging to
8323     * {@code packagName} and the actual dex files. For all dex files that were
8324     * deleted, update the internal records and delete the generated oat files.
8325     */
8326    @Override
8327    public void reconcileSecondaryDexFiles(String packageName) {
8328        mDexManager.reconcileSecondaryDexFiles(packageName);
8329    }
8330
8331    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8332    // a reference there.
8333    /*package*/ DexManager getDexManager() {
8334        return mDexManager;
8335    }
8336
8337    /**
8338     * Execute the background dexopt job immediately.
8339     */
8340    @Override
8341    public boolean runBackgroundDexoptJob() {
8342        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8343    }
8344
8345    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8346        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8347                || p.usesStaticLibraries != null) {
8348            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8349            Set<String> collectedNames = new HashSet<>();
8350            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8351
8352            retValue.remove(p);
8353
8354            return retValue;
8355        } else {
8356            return Collections.emptyList();
8357        }
8358    }
8359
8360    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8361            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8362        if (!collectedNames.contains(p.packageName)) {
8363            collectedNames.add(p.packageName);
8364            collected.add(p);
8365
8366            if (p.usesLibraries != null) {
8367                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8368                        null, collected, collectedNames);
8369            }
8370            if (p.usesOptionalLibraries != null) {
8371                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8372                        null, collected, collectedNames);
8373            }
8374            if (p.usesStaticLibraries != null) {
8375                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8376                        p.usesStaticLibrariesVersions, collected, collectedNames);
8377            }
8378        }
8379    }
8380
8381    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8382            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8383        final int libNameCount = libs.size();
8384        for (int i = 0; i < libNameCount; i++) {
8385            String libName = libs.get(i);
8386            int version = (versions != null && versions.length == libNameCount)
8387                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8388            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8389            if (libPkg != null) {
8390                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8391            }
8392        }
8393    }
8394
8395    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8396        synchronized (mPackages) {
8397            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8398            if (libEntry != null) {
8399                return mPackages.get(libEntry.apk);
8400            }
8401            return null;
8402        }
8403    }
8404
8405    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8406        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8407        if (versionedLib == null) {
8408            return null;
8409        }
8410        return versionedLib.get(version);
8411    }
8412
8413    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8414        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8415                pkg.staticSharedLibName);
8416        if (versionedLib == null) {
8417            return null;
8418        }
8419        int previousLibVersion = -1;
8420        final int versionCount = versionedLib.size();
8421        for (int i = 0; i < versionCount; i++) {
8422            final int libVersion = versionedLib.keyAt(i);
8423            if (libVersion < pkg.staticSharedLibVersion) {
8424                previousLibVersion = Math.max(previousLibVersion, libVersion);
8425            }
8426        }
8427        if (previousLibVersion >= 0) {
8428            return versionedLib.get(previousLibVersion);
8429        }
8430        return null;
8431    }
8432
8433    public void shutdown() {
8434        mPackageUsage.writeNow(mPackages);
8435        mCompilerStats.writeNow();
8436    }
8437
8438    @Override
8439    public void dumpProfiles(String packageName) {
8440        PackageParser.Package pkg;
8441        synchronized (mPackages) {
8442            pkg = mPackages.get(packageName);
8443            if (pkg == null) {
8444                throw new IllegalArgumentException("Unknown package: " + packageName);
8445            }
8446        }
8447        /* Only the shell, root, or the app user should be able to dump profiles. */
8448        int callingUid = Binder.getCallingUid();
8449        if (callingUid != Process.SHELL_UID &&
8450            callingUid != Process.ROOT_UID &&
8451            callingUid != pkg.applicationInfo.uid) {
8452            throw new SecurityException("dumpProfiles");
8453        }
8454
8455        synchronized (mInstallLock) {
8456            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8457            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8458            try {
8459                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8460                String codePaths = TextUtils.join(";", allCodePaths);
8461                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8462            } catch (InstallerException e) {
8463                Slog.w(TAG, "Failed to dump profiles", e);
8464            }
8465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8466        }
8467    }
8468
8469    @Override
8470    public void forceDexOpt(String packageName) {
8471        enforceSystemOrRoot("forceDexOpt");
8472
8473        PackageParser.Package pkg;
8474        synchronized (mPackages) {
8475            pkg = mPackages.get(packageName);
8476            if (pkg == null) {
8477                throw new IllegalArgumentException("Unknown package: " + packageName);
8478            }
8479        }
8480
8481        synchronized (mInstallLock) {
8482            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8483
8484            // Whoever is calling forceDexOpt wants a fully compiled package.
8485            // Don't use profiles since that may cause compilation to be skipped.
8486            final int res = performDexOptInternalWithDependenciesLI(pkg,
8487                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8488                    true /* force */);
8489
8490            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8491            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8492                throw new IllegalStateException("Failed to dexopt: " + res);
8493            }
8494        }
8495    }
8496
8497    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8498        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8499            Slog.w(TAG, "Unable to update from " + oldPkg.name
8500                    + " to " + newPkg.packageName
8501                    + ": old package not in system partition");
8502            return false;
8503        } else if (mPackages.get(oldPkg.name) != null) {
8504            Slog.w(TAG, "Unable to update from " + oldPkg.name
8505                    + " to " + newPkg.packageName
8506                    + ": old package still exists");
8507            return false;
8508        }
8509        return true;
8510    }
8511
8512    void removeCodePathLI(File codePath) {
8513        if (codePath.isDirectory()) {
8514            try {
8515                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8516            } catch (InstallerException e) {
8517                Slog.w(TAG, "Failed to remove code path", e);
8518            }
8519        } else {
8520            codePath.delete();
8521        }
8522    }
8523
8524    private int[] resolveUserIds(int userId) {
8525        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8526    }
8527
8528    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8529        if (pkg == null) {
8530            Slog.wtf(TAG, "Package was null!", new Throwable());
8531            return;
8532        }
8533        clearAppDataLeafLIF(pkg, userId, flags);
8534        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8535        for (int i = 0; i < childCount; i++) {
8536            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8537        }
8538    }
8539
8540    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8541        final PackageSetting ps;
8542        synchronized (mPackages) {
8543            ps = mSettings.mPackages.get(pkg.packageName);
8544        }
8545        for (int realUserId : resolveUserIds(userId)) {
8546            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8547            try {
8548                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8549                        ceDataInode);
8550            } catch (InstallerException e) {
8551                Slog.w(TAG, String.valueOf(e));
8552            }
8553        }
8554    }
8555
8556    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8557        if (pkg == null) {
8558            Slog.wtf(TAG, "Package was null!", new Throwable());
8559            return;
8560        }
8561        destroyAppDataLeafLIF(pkg, userId, flags);
8562        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8563        for (int i = 0; i < childCount; i++) {
8564            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8565        }
8566    }
8567
8568    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8569        final PackageSetting ps;
8570        synchronized (mPackages) {
8571            ps = mSettings.mPackages.get(pkg.packageName);
8572        }
8573        for (int realUserId : resolveUserIds(userId)) {
8574            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8575            try {
8576                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8577                        ceDataInode);
8578            } catch (InstallerException e) {
8579                Slog.w(TAG, String.valueOf(e));
8580            }
8581        }
8582    }
8583
8584    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8585        if (pkg == null) {
8586            Slog.wtf(TAG, "Package was null!", new Throwable());
8587            return;
8588        }
8589        destroyAppProfilesLeafLIF(pkg);
8590        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8591        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8592        for (int i = 0; i < childCount; i++) {
8593            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8594            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8595                    true /* removeBaseMarker */);
8596        }
8597    }
8598
8599    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8600            boolean removeBaseMarker) {
8601        if (pkg.isForwardLocked()) {
8602            return;
8603        }
8604
8605        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8606            try {
8607                path = PackageManagerServiceUtils.realpath(new File(path));
8608            } catch (IOException e) {
8609                // TODO: Should we return early here ?
8610                Slog.w(TAG, "Failed to get canonical path", e);
8611                continue;
8612            }
8613
8614            final String useMarker = path.replace('/', '@');
8615            for (int realUserId : resolveUserIds(userId)) {
8616                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8617                if (removeBaseMarker) {
8618                    File foreignUseMark = new File(profileDir, useMarker);
8619                    if (foreignUseMark.exists()) {
8620                        if (!foreignUseMark.delete()) {
8621                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8622                                    + pkg.packageName);
8623                        }
8624                    }
8625                }
8626
8627                File[] markers = profileDir.listFiles();
8628                if (markers != null) {
8629                    final String searchString = "@" + pkg.packageName + "@";
8630                    // We also delete all markers that contain the package name we're
8631                    // uninstalling. These are associated with secondary dex-files belonging
8632                    // to the package. Reconstructing the path of these dex files is messy
8633                    // in general.
8634                    for (File marker : markers) {
8635                        if (marker.getName().indexOf(searchString) > 0) {
8636                            if (!marker.delete()) {
8637                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8638                                    + pkg.packageName);
8639                            }
8640                        }
8641                    }
8642                }
8643            }
8644        }
8645    }
8646
8647    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8648        try {
8649            mInstaller.destroyAppProfiles(pkg.packageName);
8650        } catch (InstallerException e) {
8651            Slog.w(TAG, String.valueOf(e));
8652        }
8653    }
8654
8655    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8656        if (pkg == null) {
8657            Slog.wtf(TAG, "Package was null!", new Throwable());
8658            return;
8659        }
8660        clearAppProfilesLeafLIF(pkg);
8661        // We don't remove the base foreign use marker when clearing profiles because
8662        // we will rename it when the app is updated. Unlike the actual profile contents,
8663        // the foreign use marker is good across installs.
8664        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8665        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8666        for (int i = 0; i < childCount; i++) {
8667            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8668        }
8669    }
8670
8671    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8672        try {
8673            mInstaller.clearAppProfiles(pkg.packageName);
8674        } catch (InstallerException e) {
8675            Slog.w(TAG, String.valueOf(e));
8676        }
8677    }
8678
8679    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8680            long lastUpdateTime) {
8681        // Set parent install/update time
8682        PackageSetting ps = (PackageSetting) pkg.mExtras;
8683        if (ps != null) {
8684            ps.firstInstallTime = firstInstallTime;
8685            ps.lastUpdateTime = lastUpdateTime;
8686        }
8687        // Set children install/update time
8688        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8689        for (int i = 0; i < childCount; i++) {
8690            PackageParser.Package childPkg = pkg.childPackages.get(i);
8691            ps = (PackageSetting) childPkg.mExtras;
8692            if (ps != null) {
8693                ps.firstInstallTime = firstInstallTime;
8694                ps.lastUpdateTime = lastUpdateTime;
8695            }
8696        }
8697    }
8698
8699    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8700            PackageParser.Package changingLib) {
8701        if (file.path != null) {
8702            usesLibraryFiles.add(file.path);
8703            return;
8704        }
8705        PackageParser.Package p = mPackages.get(file.apk);
8706        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8707            // If we are doing this while in the middle of updating a library apk,
8708            // then we need to make sure to use that new apk for determining the
8709            // dependencies here.  (We haven't yet finished committing the new apk
8710            // to the package manager state.)
8711            if (p == null || p.packageName.equals(changingLib.packageName)) {
8712                p = changingLib;
8713            }
8714        }
8715        if (p != null) {
8716            usesLibraryFiles.addAll(p.getAllCodePaths());
8717        }
8718    }
8719
8720    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8721            PackageParser.Package changingLib) throws PackageManagerException {
8722        if (pkg == null) {
8723            return;
8724        }
8725        ArraySet<String> usesLibraryFiles = null;
8726        if (pkg.usesLibraries != null) {
8727            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8728                    null, null, pkg.packageName, changingLib, true, null);
8729        }
8730        if (pkg.usesStaticLibraries != null) {
8731            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8732                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8733                    pkg.packageName, changingLib, true, usesLibraryFiles);
8734        }
8735        if (pkg.usesOptionalLibraries != null) {
8736            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8737                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8738        }
8739        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8740            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8741        } else {
8742            pkg.usesLibraryFiles = null;
8743        }
8744    }
8745
8746    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8747            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8748            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8749            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8750            throws PackageManagerException {
8751        final int libCount = requestedLibraries.size();
8752        for (int i = 0; i < libCount; i++) {
8753            final String libName = requestedLibraries.get(i);
8754            final int libVersion = requiredVersions != null ? requiredVersions[i]
8755                    : SharedLibraryInfo.VERSION_UNDEFINED;
8756            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8757            if (libEntry == null) {
8758                if (required) {
8759                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8760                            "Package " + packageName + " requires unavailable shared library "
8761                                    + libName + "; failing!");
8762                } else {
8763                    Slog.w(TAG, "Package " + packageName
8764                            + " desires unavailable shared library "
8765                            + libName + "; ignoring!");
8766                }
8767            } else {
8768                if (requiredVersions != null && requiredCertDigests != null) {
8769                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8770                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8771                            "Package " + packageName + " requires unavailable static shared"
8772                                    + " library " + libName + " version "
8773                                    + libEntry.info.getVersion() + "; failing!");
8774                    }
8775
8776                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8777                    if (libPkg == null) {
8778                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8779                                "Package " + packageName + " requires unavailable static shared"
8780                                        + " library; failing!");
8781                    }
8782
8783                    String expectedCertDigest = requiredCertDigests[i];
8784                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8785                                libPkg.mSignatures[0]);
8786                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8787                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8788                                "Package " + packageName + " requires differently signed" +
8789                                        " static shared library; failing!");
8790                    }
8791                }
8792
8793                if (outUsedLibraries == null) {
8794                    outUsedLibraries = new ArraySet<>();
8795                }
8796                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8797            }
8798        }
8799        return outUsedLibraries;
8800    }
8801
8802    private static boolean hasString(List<String> list, List<String> which) {
8803        if (list == null) {
8804            return false;
8805        }
8806        for (int i=list.size()-1; i>=0; i--) {
8807            for (int j=which.size()-1; j>=0; j--) {
8808                if (which.get(j).equals(list.get(i))) {
8809                    return true;
8810                }
8811            }
8812        }
8813        return false;
8814    }
8815
8816    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8817            PackageParser.Package changingPkg) {
8818        ArrayList<PackageParser.Package> res = null;
8819        for (PackageParser.Package pkg : mPackages.values()) {
8820            if (changingPkg != null
8821                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8822                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8823                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8824                            changingPkg.staticSharedLibName)) {
8825                return null;
8826            }
8827            if (res == null) {
8828                res = new ArrayList<>();
8829            }
8830            res.add(pkg);
8831            try {
8832                updateSharedLibrariesLPr(pkg, changingPkg);
8833            } catch (PackageManagerException e) {
8834                // If a system app update or an app and a required lib missing we
8835                // delete the package and for updated system apps keep the data as
8836                // it is better for the user to reinstall than to be in an limbo
8837                // state. Also libs disappearing under an app should never happen
8838                // - just in case.
8839                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8840                    final int flags = pkg.isUpdatedSystemApp()
8841                            ? PackageManager.DELETE_KEEP_DATA : 0;
8842                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8843                            flags , null, true, null);
8844                }
8845                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8846            }
8847        }
8848        return res;
8849    }
8850
8851    /**
8852     * Derive the value of the {@code cpuAbiOverride} based on the provided
8853     * value and an optional stored value from the package settings.
8854     */
8855    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8856        String cpuAbiOverride = null;
8857
8858        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8859            cpuAbiOverride = null;
8860        } else if (abiOverride != null) {
8861            cpuAbiOverride = abiOverride;
8862        } else if (settings != null) {
8863            cpuAbiOverride = settings.cpuAbiOverrideString;
8864        }
8865
8866        return cpuAbiOverride;
8867    }
8868
8869    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8870            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8871                    throws PackageManagerException {
8872        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8873        // If the package has children and this is the first dive in the function
8874        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8875        // whether all packages (parent and children) would be successfully scanned
8876        // before the actual scan since scanning mutates internal state and we want
8877        // to atomically install the package and its children.
8878        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8879            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8880                scanFlags |= SCAN_CHECK_ONLY;
8881            }
8882        } else {
8883            scanFlags &= ~SCAN_CHECK_ONLY;
8884        }
8885
8886        final PackageParser.Package scannedPkg;
8887        try {
8888            // Scan the parent
8889            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8890            // Scan the children
8891            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8892            for (int i = 0; i < childCount; i++) {
8893                PackageParser.Package childPkg = pkg.childPackages.get(i);
8894                scanPackageLI(childPkg, policyFlags,
8895                        scanFlags, currentTime, user);
8896            }
8897        } finally {
8898            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8899        }
8900
8901        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8902            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8903        }
8904
8905        return scannedPkg;
8906    }
8907
8908    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8909            int scanFlags, long currentTime, @Nullable UserHandle user)
8910                    throws PackageManagerException {
8911        boolean success = false;
8912        try {
8913            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8914                    currentTime, user);
8915            success = true;
8916            return res;
8917        } finally {
8918            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8919                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8920                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8921                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8922                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8923            }
8924        }
8925    }
8926
8927    /**
8928     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8929     */
8930    private static boolean apkHasCode(String fileName) {
8931        StrictJarFile jarFile = null;
8932        try {
8933            jarFile = new StrictJarFile(fileName,
8934                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8935            return jarFile.findEntry("classes.dex") != null;
8936        } catch (IOException ignore) {
8937        } finally {
8938            try {
8939                if (jarFile != null) {
8940                    jarFile.close();
8941                }
8942            } catch (IOException ignore) {}
8943        }
8944        return false;
8945    }
8946
8947    /**
8948     * Enforces code policy for the package. This ensures that if an APK has
8949     * declared hasCode="true" in its manifest that the APK actually contains
8950     * code.
8951     *
8952     * @throws PackageManagerException If bytecode could not be found when it should exist
8953     */
8954    private static void assertCodePolicy(PackageParser.Package pkg)
8955            throws PackageManagerException {
8956        final boolean shouldHaveCode =
8957                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8958        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8959            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8960                    "Package " + pkg.baseCodePath + " code is missing");
8961        }
8962
8963        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8964            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8965                final boolean splitShouldHaveCode =
8966                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8967                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8968                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8969                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8970                }
8971            }
8972        }
8973    }
8974
8975    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8976            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
8977                    throws PackageManagerException {
8978        if (DEBUG_PACKAGE_SCANNING) {
8979            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8980                Log.d(TAG, "Scanning package " + pkg.packageName);
8981        }
8982
8983        applyPolicy(pkg, policyFlags);
8984
8985        assertPackageIsValid(pkg, policyFlags, scanFlags);
8986
8987        // Initialize package source and resource directories
8988        final File scanFile = new File(pkg.codePath);
8989        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8990        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8991
8992        SharedUserSetting suid = null;
8993        PackageSetting pkgSetting = null;
8994
8995        // Getting the package setting may have a side-effect, so if we
8996        // are only checking if scan would succeed, stash a copy of the
8997        // old setting to restore at the end.
8998        PackageSetting nonMutatedPs = null;
8999
9000        // We keep references to the derived CPU Abis from settings in oder to reuse
9001        // them in the case where we're not upgrading or booting for the first time.
9002        String primaryCpuAbiFromSettings = null;
9003        String secondaryCpuAbiFromSettings = null;
9004
9005        // writer
9006        synchronized (mPackages) {
9007            if (pkg.mSharedUserId != null) {
9008                // SIDE EFFECTS; may potentially allocate a new shared user
9009                suid = mSettings.getSharedUserLPw(
9010                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9011                if (DEBUG_PACKAGE_SCANNING) {
9012                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9013                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9014                                + "): packages=" + suid.packages);
9015                }
9016            }
9017
9018            // Check if we are renaming from an original package name.
9019            PackageSetting origPackage = null;
9020            String realName = null;
9021            if (pkg.mOriginalPackages != null) {
9022                // This package may need to be renamed to a previously
9023                // installed name.  Let's check on that...
9024                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9025                if (pkg.mOriginalPackages.contains(renamed)) {
9026                    // This package had originally been installed as the
9027                    // original name, and we have already taken care of
9028                    // transitioning to the new one.  Just update the new
9029                    // one to continue using the old name.
9030                    realName = pkg.mRealPackage;
9031                    if (!pkg.packageName.equals(renamed)) {
9032                        // Callers into this function may have already taken
9033                        // care of renaming the package; only do it here if
9034                        // it is not already done.
9035                        pkg.setPackageName(renamed);
9036                    }
9037                } else {
9038                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9039                        if ((origPackage = mSettings.getPackageLPr(
9040                                pkg.mOriginalPackages.get(i))) != null) {
9041                            // We do have the package already installed under its
9042                            // original name...  should we use it?
9043                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9044                                // New package is not compatible with original.
9045                                origPackage = null;
9046                                continue;
9047                            } else if (origPackage.sharedUser != null) {
9048                                // Make sure uid is compatible between packages.
9049                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9050                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9051                                            + " to " + pkg.packageName + ": old uid "
9052                                            + origPackage.sharedUser.name
9053                                            + " differs from " + pkg.mSharedUserId);
9054                                    origPackage = null;
9055                                    continue;
9056                                }
9057                                // TODO: Add case when shared user id is added [b/28144775]
9058                            } else {
9059                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9060                                        + pkg.packageName + " to old name " + origPackage.name);
9061                            }
9062                            break;
9063                        }
9064                    }
9065                }
9066            }
9067
9068            if (mTransferedPackages.contains(pkg.packageName)) {
9069                Slog.w(TAG, "Package " + pkg.packageName
9070                        + " was transferred to another, but its .apk remains");
9071            }
9072
9073            // See comments in nonMutatedPs declaration
9074            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9075                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9076                if (foundPs != null) {
9077                    nonMutatedPs = new PackageSetting(foundPs);
9078                }
9079            }
9080
9081            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9082                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9083                if (foundPs != null) {
9084                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9085                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9086                }
9087            }
9088
9089            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9090            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9091                PackageManagerService.reportSettingsProblem(Log.WARN,
9092                        "Package " + pkg.packageName + " shared user changed from "
9093                                + (pkgSetting.sharedUser != null
9094                                        ? pkgSetting.sharedUser.name : "<nothing>")
9095                                + " to "
9096                                + (suid != null ? suid.name : "<nothing>")
9097                                + "; replacing with new");
9098                pkgSetting = null;
9099            }
9100            final PackageSetting oldPkgSetting =
9101                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9102            final PackageSetting disabledPkgSetting =
9103                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9104
9105            String[] usesStaticLibraries = null;
9106            if (pkg.usesStaticLibraries != null) {
9107                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9108                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9109            }
9110
9111            if (pkgSetting == null) {
9112                final String parentPackageName = (pkg.parentPackage != null)
9113                        ? pkg.parentPackage.packageName : null;
9114                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9115                // REMOVE SharedUserSetting from method; update in a separate call
9116                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9117                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9118                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9119                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9120                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9121                        true /*allowInstall*/, instantApp, parentPackageName,
9122                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9123                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9124                // SIDE EFFECTS; updates system state; move elsewhere
9125                if (origPackage != null) {
9126                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9127                }
9128                mSettings.addUserToSettingLPw(pkgSetting);
9129            } else {
9130                // REMOVE SharedUserSetting from method; update in a separate call.
9131                //
9132                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9133                // secondaryCpuAbi are not known at this point so we always update them
9134                // to null here, only to reset them at a later point.
9135                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9136                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9137                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9138                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9139                        UserManagerService.getInstance(), usesStaticLibraries,
9140                        pkg.usesStaticLibrariesVersions);
9141            }
9142            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9143            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9144
9145            // SIDE EFFECTS; modifies system state; move elsewhere
9146            if (pkgSetting.origPackage != null) {
9147                // If we are first transitioning from an original package,
9148                // fix up the new package's name now.  We need to do this after
9149                // looking up the package under its new name, so getPackageLP
9150                // can take care of fiddling things correctly.
9151                pkg.setPackageName(origPackage.name);
9152
9153                // File a report about this.
9154                String msg = "New package " + pkgSetting.realName
9155                        + " renamed to replace old package " + pkgSetting.name;
9156                reportSettingsProblem(Log.WARN, msg);
9157
9158                // Make a note of it.
9159                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9160                    mTransferedPackages.add(origPackage.name);
9161                }
9162
9163                // No longer need to retain this.
9164                pkgSetting.origPackage = null;
9165            }
9166
9167            // SIDE EFFECTS; modifies system state; move elsewhere
9168            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9169                // Make a note of it.
9170                mTransferedPackages.add(pkg.packageName);
9171            }
9172
9173            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9174                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9175            }
9176
9177            if ((scanFlags & SCAN_BOOTING) == 0
9178                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9179                // Check all shared libraries and map to their actual file path.
9180                // We only do this here for apps not on a system dir, because those
9181                // are the only ones that can fail an install due to this.  We
9182                // will take care of the system apps by updating all of their
9183                // library paths after the scan is done. Also during the initial
9184                // scan don't update any libs as we do this wholesale after all
9185                // apps are scanned to avoid dependency based scanning.
9186                updateSharedLibrariesLPr(pkg, null);
9187            }
9188
9189            if (mFoundPolicyFile) {
9190                SELinuxMMAC.assignSeInfoValue(pkg);
9191            }
9192            pkg.applicationInfo.uid = pkgSetting.appId;
9193            pkg.mExtras = pkgSetting;
9194
9195
9196            // Static shared libs have same package with different versions where
9197            // we internally use a synthetic package name to allow multiple versions
9198            // of the same package, therefore we need to compare signatures against
9199            // the package setting for the latest library version.
9200            PackageSetting signatureCheckPs = pkgSetting;
9201            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9202                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9203                if (libraryEntry != null) {
9204                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9205                }
9206            }
9207
9208            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9209                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9210                    // We just determined the app is signed correctly, so bring
9211                    // over the latest parsed certs.
9212                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9213                } else {
9214                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9215                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9216                                "Package " + pkg.packageName + " upgrade keys do not match the "
9217                                + "previously installed version");
9218                    } else {
9219                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9220                        String msg = "System package " + pkg.packageName
9221                                + " signature changed; retaining data.";
9222                        reportSettingsProblem(Log.WARN, msg);
9223                    }
9224                }
9225            } else {
9226                try {
9227                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9228                    verifySignaturesLP(signatureCheckPs, pkg);
9229                    // We just determined the app is signed correctly, so bring
9230                    // over the latest parsed certs.
9231                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9232                } catch (PackageManagerException e) {
9233                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9234                        throw e;
9235                    }
9236                    // The signature has changed, but this package is in the system
9237                    // image...  let's recover!
9238                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9239                    // However...  if this package is part of a shared user, but it
9240                    // doesn't match the signature of the shared user, let's fail.
9241                    // What this means is that you can't change the signatures
9242                    // associated with an overall shared user, which doesn't seem all
9243                    // that unreasonable.
9244                    if (signatureCheckPs.sharedUser != null) {
9245                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9246                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9247                            throw new PackageManagerException(
9248                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9249                                    "Signature mismatch for shared user: "
9250                                            + pkgSetting.sharedUser);
9251                        }
9252                    }
9253                    // File a report about this.
9254                    String msg = "System package " + pkg.packageName
9255                            + " signature changed; retaining data.";
9256                    reportSettingsProblem(Log.WARN, msg);
9257                }
9258            }
9259
9260            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9261                // This package wants to adopt ownership of permissions from
9262                // another package.
9263                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9264                    final String origName = pkg.mAdoptPermissions.get(i);
9265                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9266                    if (orig != null) {
9267                        if (verifyPackageUpdateLPr(orig, pkg)) {
9268                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9269                                    + pkg.packageName);
9270                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9271                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9272                        }
9273                    }
9274                }
9275            }
9276        }
9277
9278        pkg.applicationInfo.processName = fixProcessName(
9279                pkg.applicationInfo.packageName,
9280                pkg.applicationInfo.processName);
9281
9282        if (pkg != mPlatformPackage) {
9283            // Get all of our default paths setup
9284            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9285        }
9286
9287        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9288
9289        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9290            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9291                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9292                derivePackageAbi(
9293                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9294                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9295
9296                // Some system apps still use directory structure for native libraries
9297                // in which case we might end up not detecting abi solely based on apk
9298                // structure. Try to detect abi based on directory structure.
9299                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9300                        pkg.applicationInfo.primaryCpuAbi == null) {
9301                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9302                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9303                }
9304            } else {
9305                // This is not a first boot or an upgrade, don't bother deriving the
9306                // ABI during the scan. Instead, trust the value that was stored in the
9307                // package setting.
9308                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9309                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9310
9311                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9312
9313                if (DEBUG_ABI_SELECTION) {
9314                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9315                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9316                        pkg.applicationInfo.secondaryCpuAbi);
9317                }
9318            }
9319        } else {
9320            if ((scanFlags & SCAN_MOVE) != 0) {
9321                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9322                // but we already have this packages package info in the PackageSetting. We just
9323                // use that and derive the native library path based on the new codepath.
9324                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9325                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9326            }
9327
9328            // Set native library paths again. For moves, the path will be updated based on the
9329            // ABIs we've determined above. For non-moves, the path will be updated based on the
9330            // ABIs we determined during compilation, but the path will depend on the final
9331            // package path (after the rename away from the stage path).
9332            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9333        }
9334
9335        // This is a special case for the "system" package, where the ABI is
9336        // dictated by the zygote configuration (and init.rc). We should keep track
9337        // of this ABI so that we can deal with "normal" applications that run under
9338        // the same UID correctly.
9339        if (mPlatformPackage == pkg) {
9340            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9341                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9342        }
9343
9344        // If there's a mismatch between the abi-override in the package setting
9345        // and the abiOverride specified for the install. Warn about this because we
9346        // would've already compiled the app without taking the package setting into
9347        // account.
9348        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9349            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9350                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9351                        " for package " + pkg.packageName);
9352            }
9353        }
9354
9355        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9356        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9357        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9358
9359        // Copy the derived override back to the parsed package, so that we can
9360        // update the package settings accordingly.
9361        pkg.cpuAbiOverride = cpuAbiOverride;
9362
9363        if (DEBUG_ABI_SELECTION) {
9364            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9365                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9366                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9367        }
9368
9369        // Push the derived path down into PackageSettings so we know what to
9370        // clean up at uninstall time.
9371        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9372
9373        if (DEBUG_ABI_SELECTION) {
9374            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9375                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9376                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9377        }
9378
9379        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9380        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9381            // We don't do this here during boot because we can do it all
9382            // at once after scanning all existing packages.
9383            //
9384            // We also do this *before* we perform dexopt on this package, so that
9385            // we can avoid redundant dexopts, and also to make sure we've got the
9386            // code and package path correct.
9387            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9388        }
9389
9390        if (mFactoryTest && pkg.requestedPermissions.contains(
9391                android.Manifest.permission.FACTORY_TEST)) {
9392            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9393        }
9394
9395        if (isSystemApp(pkg)) {
9396            pkgSetting.isOrphaned = true;
9397        }
9398
9399        // Take care of first install / last update times.
9400        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9401        if (currentTime != 0) {
9402            if (pkgSetting.firstInstallTime == 0) {
9403                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9404            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9405                pkgSetting.lastUpdateTime = currentTime;
9406            }
9407        } else if (pkgSetting.firstInstallTime == 0) {
9408            // We need *something*.  Take time time stamp of the file.
9409            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9410        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9411            if (scanFileTime != pkgSetting.timeStamp) {
9412                // A package on the system image has changed; consider this
9413                // to be an update.
9414                pkgSetting.lastUpdateTime = scanFileTime;
9415            }
9416        }
9417        pkgSetting.setTimeStamp(scanFileTime);
9418
9419        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9420            if (nonMutatedPs != null) {
9421                synchronized (mPackages) {
9422                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9423                }
9424            }
9425        } else {
9426            final int userId = user == null ? 0 : user.getIdentifier();
9427            // Modify state for the given package setting
9428            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9429                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9430            if (pkgSetting.getInstantApp(userId)) {
9431                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9432            }
9433        }
9434        return pkg;
9435    }
9436
9437    /**
9438     * Applies policy to the parsed package based upon the given policy flags.
9439     * Ensures the package is in a good state.
9440     * <p>
9441     * Implementation detail: This method must NOT have any side effect. It would
9442     * ideally be static, but, it requires locks to read system state.
9443     */
9444    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9445        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9446            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9447            if (pkg.applicationInfo.isDirectBootAware()) {
9448                // we're direct boot aware; set for all components
9449                for (PackageParser.Service s : pkg.services) {
9450                    s.info.encryptionAware = s.info.directBootAware = true;
9451                }
9452                for (PackageParser.Provider p : pkg.providers) {
9453                    p.info.encryptionAware = p.info.directBootAware = true;
9454                }
9455                for (PackageParser.Activity a : pkg.activities) {
9456                    a.info.encryptionAware = a.info.directBootAware = true;
9457                }
9458                for (PackageParser.Activity r : pkg.receivers) {
9459                    r.info.encryptionAware = r.info.directBootAware = true;
9460                }
9461            }
9462        } else {
9463            // Only allow system apps to be flagged as core apps.
9464            pkg.coreApp = false;
9465            // clear flags not applicable to regular apps
9466            pkg.applicationInfo.privateFlags &=
9467                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9468            pkg.applicationInfo.privateFlags &=
9469                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9470        }
9471        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9472
9473        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9474            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9475        }
9476
9477        if (!isSystemApp(pkg)) {
9478            // Only system apps can use these features.
9479            pkg.mOriginalPackages = null;
9480            pkg.mRealPackage = null;
9481            pkg.mAdoptPermissions = null;
9482        }
9483    }
9484
9485    /**
9486     * Asserts the parsed package is valid according to the given policy. If the
9487     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9488     * <p>
9489     * Implementation detail: This method must NOT have any side effects. It would
9490     * ideally be static, but, it requires locks to read system state.
9491     *
9492     * @throws PackageManagerException If the package fails any of the validation checks
9493     */
9494    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9495            throws PackageManagerException {
9496        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9497            assertCodePolicy(pkg);
9498        }
9499
9500        if (pkg.applicationInfo.getCodePath() == null ||
9501                pkg.applicationInfo.getResourcePath() == null) {
9502            // Bail out. The resource and code paths haven't been set.
9503            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9504                    "Code and resource paths haven't been set correctly");
9505        }
9506
9507        // Make sure we're not adding any bogus keyset info
9508        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9509        ksms.assertScannedPackageValid(pkg);
9510
9511        synchronized (mPackages) {
9512            // The special "android" package can only be defined once
9513            if (pkg.packageName.equals("android")) {
9514                if (mAndroidApplication != null) {
9515                    Slog.w(TAG, "*************************************************");
9516                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9517                    Slog.w(TAG, " codePath=" + pkg.codePath);
9518                    Slog.w(TAG, "*************************************************");
9519                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9520                            "Core android package being redefined.  Skipping.");
9521                }
9522            }
9523
9524            // A package name must be unique; don't allow duplicates
9525            if (mPackages.containsKey(pkg.packageName)) {
9526                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9527                        "Application package " + pkg.packageName
9528                        + " already installed.  Skipping duplicate.");
9529            }
9530
9531            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9532                // Static libs have a synthetic package name containing the version
9533                // but we still want the base name to be unique.
9534                if (mPackages.containsKey(pkg.manifestPackageName)) {
9535                    throw new PackageManagerException(
9536                            "Duplicate static shared lib provider package");
9537                }
9538
9539                // Static shared libraries should have at least O target SDK
9540                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9541                    throw new PackageManagerException(
9542                            "Packages declaring static-shared libs must target O SDK or higher");
9543                }
9544
9545                // Package declaring static a shared lib cannot be instant apps
9546                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9547                    throw new PackageManagerException(
9548                            "Packages declaring static-shared libs cannot be instant apps");
9549                }
9550
9551                // Package declaring static a shared lib cannot be renamed since the package
9552                // name is synthetic and apps can't code around package manager internals.
9553                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9554                    throw new PackageManagerException(
9555                            "Packages declaring static-shared libs cannot be renamed");
9556                }
9557
9558                // Package declaring static a shared lib cannot declare child packages
9559                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9560                    throw new PackageManagerException(
9561                            "Packages declaring static-shared libs cannot have child packages");
9562                }
9563
9564                // Package declaring static a shared lib cannot declare dynamic libs
9565                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9566                    throw new PackageManagerException(
9567                            "Packages declaring static-shared libs cannot declare dynamic libs");
9568                }
9569
9570                // Package declaring static a shared lib cannot declare shared users
9571                if (pkg.mSharedUserId != null) {
9572                    throw new PackageManagerException(
9573                            "Packages declaring static-shared libs cannot declare shared users");
9574                }
9575
9576                // Static shared libs cannot declare activities
9577                if (!pkg.activities.isEmpty()) {
9578                    throw new PackageManagerException(
9579                            "Static shared libs cannot declare activities");
9580                }
9581
9582                // Static shared libs cannot declare services
9583                if (!pkg.services.isEmpty()) {
9584                    throw new PackageManagerException(
9585                            "Static shared libs cannot declare services");
9586                }
9587
9588                // Static shared libs cannot declare providers
9589                if (!pkg.providers.isEmpty()) {
9590                    throw new PackageManagerException(
9591                            "Static shared libs cannot declare content providers");
9592                }
9593
9594                // Static shared libs cannot declare receivers
9595                if (!pkg.receivers.isEmpty()) {
9596                    throw new PackageManagerException(
9597                            "Static shared libs cannot declare broadcast receivers");
9598                }
9599
9600                // Static shared libs cannot declare permission groups
9601                if (!pkg.permissionGroups.isEmpty()) {
9602                    throw new PackageManagerException(
9603                            "Static shared libs cannot declare permission groups");
9604                }
9605
9606                // Static shared libs cannot declare permissions
9607                if (!pkg.permissions.isEmpty()) {
9608                    throw new PackageManagerException(
9609                            "Static shared libs cannot declare permissions");
9610                }
9611
9612                // Static shared libs cannot declare protected broadcasts
9613                if (pkg.protectedBroadcasts != null) {
9614                    throw new PackageManagerException(
9615                            "Static shared libs cannot declare protected broadcasts");
9616                }
9617
9618                // Static shared libs cannot be overlay targets
9619                if (pkg.mOverlayTarget != null) {
9620                    throw new PackageManagerException(
9621                            "Static shared libs cannot be overlay targets");
9622                }
9623
9624                // The version codes must be ordered as lib versions
9625                int minVersionCode = Integer.MIN_VALUE;
9626                int maxVersionCode = Integer.MAX_VALUE;
9627
9628                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9629                        pkg.staticSharedLibName);
9630                if (versionedLib != null) {
9631                    final int versionCount = versionedLib.size();
9632                    for (int i = 0; i < versionCount; i++) {
9633                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9634                        // TODO: We will change version code to long, so in the new API it is long
9635                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9636                                .getVersionCode();
9637                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9638                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9639                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9640                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9641                        } else {
9642                            minVersionCode = maxVersionCode = libVersionCode;
9643                            break;
9644                        }
9645                    }
9646                }
9647                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9648                    throw new PackageManagerException("Static shared"
9649                            + " lib version codes must be ordered as lib versions");
9650                }
9651            }
9652
9653            // Only privileged apps and updated privileged apps can add child packages.
9654            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9655                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9656                    throw new PackageManagerException("Only privileged apps can add child "
9657                            + "packages. Ignoring package " + pkg.packageName);
9658                }
9659                final int childCount = pkg.childPackages.size();
9660                for (int i = 0; i < childCount; i++) {
9661                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9662                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9663                            childPkg.packageName)) {
9664                        throw new PackageManagerException("Can't override child of "
9665                                + "another disabled app. Ignoring package " + pkg.packageName);
9666                    }
9667                }
9668            }
9669
9670            // If we're only installing presumed-existing packages, require that the
9671            // scanned APK is both already known and at the path previously established
9672            // for it.  Previously unknown packages we pick up normally, but if we have an
9673            // a priori expectation about this package's install presence, enforce it.
9674            // With a singular exception for new system packages. When an OTA contains
9675            // a new system package, we allow the codepath to change from a system location
9676            // to the user-installed location. If we don't allow this change, any newer,
9677            // user-installed version of the application will be ignored.
9678            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9679                if (mExpectingBetter.containsKey(pkg.packageName)) {
9680                    logCriticalInfo(Log.WARN,
9681                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9682                } else {
9683                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9684                    if (known != null) {
9685                        if (DEBUG_PACKAGE_SCANNING) {
9686                            Log.d(TAG, "Examining " + pkg.codePath
9687                                    + " and requiring known paths " + known.codePathString
9688                                    + " & " + known.resourcePathString);
9689                        }
9690                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9691                                || !pkg.applicationInfo.getResourcePath().equals(
9692                                        known.resourcePathString)) {
9693                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9694                                    "Application package " + pkg.packageName
9695                                    + " found at " + pkg.applicationInfo.getCodePath()
9696                                    + " but expected at " + known.codePathString
9697                                    + "; ignoring.");
9698                        }
9699                    }
9700                }
9701            }
9702
9703            // Verify that this new package doesn't have any content providers
9704            // that conflict with existing packages.  Only do this if the
9705            // package isn't already installed, since we don't want to break
9706            // things that are installed.
9707            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9708                final int N = pkg.providers.size();
9709                int i;
9710                for (i=0; i<N; i++) {
9711                    PackageParser.Provider p = pkg.providers.get(i);
9712                    if (p.info.authority != null) {
9713                        String names[] = p.info.authority.split(";");
9714                        for (int j = 0; j < names.length; j++) {
9715                            if (mProvidersByAuthority.containsKey(names[j])) {
9716                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9717                                final String otherPackageName =
9718                                        ((other != null && other.getComponentName() != null) ?
9719                                                other.getComponentName().getPackageName() : "?");
9720                                throw new PackageManagerException(
9721                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9722                                        "Can't install because provider name " + names[j]
9723                                                + " (in package " + pkg.applicationInfo.packageName
9724                                                + ") is already used by " + otherPackageName);
9725                            }
9726                        }
9727                    }
9728                }
9729            }
9730        }
9731    }
9732
9733    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9734            int type, String declaringPackageName, int declaringVersionCode) {
9735        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9736        if (versionedLib == null) {
9737            versionedLib = new SparseArray<>();
9738            mSharedLibraries.put(name, versionedLib);
9739            if (type == SharedLibraryInfo.TYPE_STATIC) {
9740                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9741            }
9742        } else if (versionedLib.indexOfKey(version) >= 0) {
9743            return false;
9744        }
9745        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9746                version, type, declaringPackageName, declaringVersionCode);
9747        versionedLib.put(version, libEntry);
9748        return true;
9749    }
9750
9751    private boolean removeSharedLibraryLPw(String name, int version) {
9752        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9753        if (versionedLib == null) {
9754            return false;
9755        }
9756        final int libIdx = versionedLib.indexOfKey(version);
9757        if (libIdx < 0) {
9758            return false;
9759        }
9760        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9761        versionedLib.remove(version);
9762        if (versionedLib.size() <= 0) {
9763            mSharedLibraries.remove(name);
9764            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9765                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9766                        .getPackageName());
9767            }
9768        }
9769        return true;
9770    }
9771
9772    /**
9773     * Adds a scanned package to the system. When this method is finished, the package will
9774     * be available for query, resolution, etc...
9775     */
9776    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9777            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9778        final String pkgName = pkg.packageName;
9779        if (mCustomResolverComponentName != null &&
9780                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9781            setUpCustomResolverActivity(pkg);
9782        }
9783
9784        if (pkg.packageName.equals("android")) {
9785            synchronized (mPackages) {
9786                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9787                    // Set up information for our fall-back user intent resolution activity.
9788                    mPlatformPackage = pkg;
9789                    pkg.mVersionCode = mSdkVersion;
9790                    mAndroidApplication = pkg.applicationInfo;
9791                    if (!mResolverReplaced) {
9792                        mResolveActivity.applicationInfo = mAndroidApplication;
9793                        mResolveActivity.name = ResolverActivity.class.getName();
9794                        mResolveActivity.packageName = mAndroidApplication.packageName;
9795                        mResolveActivity.processName = "system:ui";
9796                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9797                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9798                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9799                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9800                        mResolveActivity.exported = true;
9801                        mResolveActivity.enabled = true;
9802                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9803                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9804                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9805                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9806                                | ActivityInfo.CONFIG_ORIENTATION
9807                                | ActivityInfo.CONFIG_KEYBOARD
9808                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9809                        mResolveInfo.activityInfo = mResolveActivity;
9810                        mResolveInfo.priority = 0;
9811                        mResolveInfo.preferredOrder = 0;
9812                        mResolveInfo.match = 0;
9813                        mResolveComponentName = new ComponentName(
9814                                mAndroidApplication.packageName, mResolveActivity.name);
9815                    }
9816                }
9817            }
9818        }
9819
9820        ArrayList<PackageParser.Package> clientLibPkgs = null;
9821        // writer
9822        synchronized (mPackages) {
9823            boolean hasStaticSharedLibs = false;
9824
9825            // Any app can add new static shared libraries
9826            if (pkg.staticSharedLibName != null) {
9827                // Static shared libs don't allow renaming as they have synthetic package
9828                // names to allow install of multiple versions, so use name from manifest.
9829                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9830                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9831                        pkg.manifestPackageName, pkg.mVersionCode)) {
9832                    hasStaticSharedLibs = true;
9833                } else {
9834                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9835                                + pkg.staticSharedLibName + " already exists; skipping");
9836                }
9837                // Static shared libs cannot be updated once installed since they
9838                // use synthetic package name which includes the version code, so
9839                // not need to update other packages's shared lib dependencies.
9840            }
9841
9842            if (!hasStaticSharedLibs
9843                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9844                // Only system apps can add new dynamic shared libraries.
9845                if (pkg.libraryNames != null) {
9846                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9847                        String name = pkg.libraryNames.get(i);
9848                        boolean allowed = false;
9849                        if (pkg.isUpdatedSystemApp()) {
9850                            // New library entries can only be added through the
9851                            // system image.  This is important to get rid of a lot
9852                            // of nasty edge cases: for example if we allowed a non-
9853                            // system update of the app to add a library, then uninstalling
9854                            // the update would make the library go away, and assumptions
9855                            // we made such as through app install filtering would now
9856                            // have allowed apps on the device which aren't compatible
9857                            // with it.  Better to just have the restriction here, be
9858                            // conservative, and create many fewer cases that can negatively
9859                            // impact the user experience.
9860                            final PackageSetting sysPs = mSettings
9861                                    .getDisabledSystemPkgLPr(pkg.packageName);
9862                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9863                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9864                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9865                                        allowed = true;
9866                                        break;
9867                                    }
9868                                }
9869                            }
9870                        } else {
9871                            allowed = true;
9872                        }
9873                        if (allowed) {
9874                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9875                                    SharedLibraryInfo.VERSION_UNDEFINED,
9876                                    SharedLibraryInfo.TYPE_DYNAMIC,
9877                                    pkg.packageName, pkg.mVersionCode)) {
9878                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9879                                        + name + " already exists; skipping");
9880                            }
9881                        } else {
9882                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9883                                    + name + " that is not declared on system image; skipping");
9884                        }
9885                    }
9886
9887                    if ((scanFlags & SCAN_BOOTING) == 0) {
9888                        // If we are not booting, we need to update any applications
9889                        // that are clients of our shared library.  If we are booting,
9890                        // this will all be done once the scan is complete.
9891                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9892                    }
9893                }
9894            }
9895        }
9896
9897        if ((scanFlags & SCAN_BOOTING) != 0) {
9898            // No apps can run during boot scan, so they don't need to be frozen
9899        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9900            // Caller asked to not kill app, so it's probably not frozen
9901        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9902            // Caller asked us to ignore frozen check for some reason; they
9903            // probably didn't know the package name
9904        } else {
9905            // We're doing major surgery on this package, so it better be frozen
9906            // right now to keep it from launching
9907            checkPackageFrozen(pkgName);
9908        }
9909
9910        // Also need to kill any apps that are dependent on the library.
9911        if (clientLibPkgs != null) {
9912            for (int i=0; i<clientLibPkgs.size(); i++) {
9913                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9914                killApplication(clientPkg.applicationInfo.packageName,
9915                        clientPkg.applicationInfo.uid, "update lib");
9916            }
9917        }
9918
9919        // writer
9920        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9921
9922        boolean createIdmapFailed = false;
9923        synchronized (mPackages) {
9924            // We don't expect installation to fail beyond this point
9925
9926            if (pkgSetting.pkg != null) {
9927                // Note that |user| might be null during the initial boot scan. If a codePath
9928                // for an app has changed during a boot scan, it's due to an app update that's
9929                // part of the system partition and marker changes must be applied to all users.
9930                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9931                final int[] userIds = resolveUserIds(userId);
9932                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9933            }
9934
9935            // Add the new setting to mSettings
9936            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9937            // Add the new setting to mPackages
9938            mPackages.put(pkg.applicationInfo.packageName, pkg);
9939            // Make sure we don't accidentally delete its data.
9940            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9941            while (iter.hasNext()) {
9942                PackageCleanItem item = iter.next();
9943                if (pkgName.equals(item.packageName)) {
9944                    iter.remove();
9945                }
9946            }
9947
9948            // Add the package's KeySets to the global KeySetManagerService
9949            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9950            ksms.addScannedPackageLPw(pkg);
9951
9952            int N = pkg.providers.size();
9953            StringBuilder r = null;
9954            int i;
9955            for (i=0; i<N; i++) {
9956                PackageParser.Provider p = pkg.providers.get(i);
9957                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9958                        p.info.processName);
9959                mProviders.addProvider(p);
9960                p.syncable = p.info.isSyncable;
9961                if (p.info.authority != null) {
9962                    String names[] = p.info.authority.split(";");
9963                    p.info.authority = null;
9964                    for (int j = 0; j < names.length; j++) {
9965                        if (j == 1 && p.syncable) {
9966                            // We only want the first authority for a provider to possibly be
9967                            // syncable, so if we already added this provider using a different
9968                            // authority clear the syncable flag. We copy the provider before
9969                            // changing it because the mProviders object contains a reference
9970                            // to a provider that we don't want to change.
9971                            // Only do this for the second authority since the resulting provider
9972                            // object can be the same for all future authorities for this provider.
9973                            p = new PackageParser.Provider(p);
9974                            p.syncable = false;
9975                        }
9976                        if (!mProvidersByAuthority.containsKey(names[j])) {
9977                            mProvidersByAuthority.put(names[j], p);
9978                            if (p.info.authority == null) {
9979                                p.info.authority = names[j];
9980                            } else {
9981                                p.info.authority = p.info.authority + ";" + names[j];
9982                            }
9983                            if (DEBUG_PACKAGE_SCANNING) {
9984                                if (chatty)
9985                                    Log.d(TAG, "Registered content provider: " + names[j]
9986                                            + ", className = " + p.info.name + ", isSyncable = "
9987                                            + p.info.isSyncable);
9988                            }
9989                        } else {
9990                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9991                            Slog.w(TAG, "Skipping provider name " + names[j] +
9992                                    " (in package " + pkg.applicationInfo.packageName +
9993                                    "): name already used by "
9994                                    + ((other != null && other.getComponentName() != null)
9995                                            ? other.getComponentName().getPackageName() : "?"));
9996                        }
9997                    }
9998                }
9999                if (chatty) {
10000                    if (r == null) {
10001                        r = new StringBuilder(256);
10002                    } else {
10003                        r.append(' ');
10004                    }
10005                    r.append(p.info.name);
10006                }
10007            }
10008            if (r != null) {
10009                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10010            }
10011
10012            N = pkg.services.size();
10013            r = null;
10014            for (i=0; i<N; i++) {
10015                PackageParser.Service s = pkg.services.get(i);
10016                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10017                        s.info.processName);
10018                mServices.addService(s);
10019                if (chatty) {
10020                    if (r == null) {
10021                        r = new StringBuilder(256);
10022                    } else {
10023                        r.append(' ');
10024                    }
10025                    r.append(s.info.name);
10026                }
10027            }
10028            if (r != null) {
10029                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10030            }
10031
10032            N = pkg.receivers.size();
10033            r = null;
10034            for (i=0; i<N; i++) {
10035                PackageParser.Activity a = pkg.receivers.get(i);
10036                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10037                        a.info.processName);
10038                mReceivers.addActivity(a, "receiver");
10039                if (chatty) {
10040                    if (r == null) {
10041                        r = new StringBuilder(256);
10042                    } else {
10043                        r.append(' ');
10044                    }
10045                    r.append(a.info.name);
10046                }
10047            }
10048            if (r != null) {
10049                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10050            }
10051
10052            N = pkg.activities.size();
10053            r = null;
10054            for (i=0; i<N; i++) {
10055                PackageParser.Activity a = pkg.activities.get(i);
10056                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10057                        a.info.processName);
10058                mActivities.addActivity(a, "activity");
10059                if (chatty) {
10060                    if (r == null) {
10061                        r = new StringBuilder(256);
10062                    } else {
10063                        r.append(' ');
10064                    }
10065                    r.append(a.info.name);
10066                }
10067            }
10068            if (r != null) {
10069                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10070            }
10071
10072            N = pkg.permissionGroups.size();
10073            r = null;
10074            for (i=0; i<N; i++) {
10075                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10076                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10077                final String curPackageName = cur == null ? null : cur.info.packageName;
10078                // Dont allow ephemeral apps to define new permission groups.
10079                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10080                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10081                            + pg.info.packageName
10082                            + " ignored: instant apps cannot define new permission groups.");
10083                    continue;
10084                }
10085                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10086                if (cur == null || isPackageUpdate) {
10087                    mPermissionGroups.put(pg.info.name, pg);
10088                    if (chatty) {
10089                        if (r == null) {
10090                            r = new StringBuilder(256);
10091                        } else {
10092                            r.append(' ');
10093                        }
10094                        if (isPackageUpdate) {
10095                            r.append("UPD:");
10096                        }
10097                        r.append(pg.info.name);
10098                    }
10099                } else {
10100                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10101                            + pg.info.packageName + " ignored: original from "
10102                            + cur.info.packageName);
10103                    if (chatty) {
10104                        if (r == null) {
10105                            r = new StringBuilder(256);
10106                        } else {
10107                            r.append(' ');
10108                        }
10109                        r.append("DUP:");
10110                        r.append(pg.info.name);
10111                    }
10112                }
10113            }
10114            if (r != null) {
10115                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10116            }
10117
10118            N = pkg.permissions.size();
10119            r = null;
10120            for (i=0; i<N; i++) {
10121                PackageParser.Permission p = pkg.permissions.get(i);
10122
10123                // Dont allow ephemeral apps to define new permissions.
10124                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10125                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10126                            + p.info.packageName
10127                            + " ignored: instant apps cannot define new permissions.");
10128                    continue;
10129                }
10130
10131                // Assume by default that we did not install this permission into the system.
10132                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10133
10134                // Now that permission groups have a special meaning, we ignore permission
10135                // groups for legacy apps to prevent unexpected behavior. In particular,
10136                // permissions for one app being granted to someone just becase they happen
10137                // to be in a group defined by another app (before this had no implications).
10138                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10139                    p.group = mPermissionGroups.get(p.info.group);
10140                    // Warn for a permission in an unknown group.
10141                    if (p.info.group != null && p.group == null) {
10142                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10143                                + p.info.packageName + " in an unknown group " + p.info.group);
10144                    }
10145                }
10146
10147                ArrayMap<String, BasePermission> permissionMap =
10148                        p.tree ? mSettings.mPermissionTrees
10149                                : mSettings.mPermissions;
10150                BasePermission bp = permissionMap.get(p.info.name);
10151
10152                // Allow system apps to redefine non-system permissions
10153                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10154                    final boolean currentOwnerIsSystem = (bp.perm != null
10155                            && isSystemApp(bp.perm.owner));
10156                    if (isSystemApp(p.owner)) {
10157                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10158                            // It's a built-in permission and no owner, take ownership now
10159                            bp.packageSetting = pkgSetting;
10160                            bp.perm = p;
10161                            bp.uid = pkg.applicationInfo.uid;
10162                            bp.sourcePackage = p.info.packageName;
10163                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10164                        } else if (!currentOwnerIsSystem) {
10165                            String msg = "New decl " + p.owner + " of permission  "
10166                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10167                            reportSettingsProblem(Log.WARN, msg);
10168                            bp = null;
10169                        }
10170                    }
10171                }
10172
10173                if (bp == null) {
10174                    bp = new BasePermission(p.info.name, p.info.packageName,
10175                            BasePermission.TYPE_NORMAL);
10176                    permissionMap.put(p.info.name, bp);
10177                }
10178
10179                if (bp.perm == null) {
10180                    if (bp.sourcePackage == null
10181                            || bp.sourcePackage.equals(p.info.packageName)) {
10182                        BasePermission tree = findPermissionTreeLP(p.info.name);
10183                        if (tree == null
10184                                || tree.sourcePackage.equals(p.info.packageName)) {
10185                            bp.packageSetting = pkgSetting;
10186                            bp.perm = p;
10187                            bp.uid = pkg.applicationInfo.uid;
10188                            bp.sourcePackage = p.info.packageName;
10189                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10190                            if (chatty) {
10191                                if (r == null) {
10192                                    r = new StringBuilder(256);
10193                                } else {
10194                                    r.append(' ');
10195                                }
10196                                r.append(p.info.name);
10197                            }
10198                        } else {
10199                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10200                                    + p.info.packageName + " ignored: base tree "
10201                                    + tree.name + " is from package "
10202                                    + tree.sourcePackage);
10203                        }
10204                    } else {
10205                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10206                                + p.info.packageName + " ignored: original from "
10207                                + bp.sourcePackage);
10208                    }
10209                } else if (chatty) {
10210                    if (r == null) {
10211                        r = new StringBuilder(256);
10212                    } else {
10213                        r.append(' ');
10214                    }
10215                    r.append("DUP:");
10216                    r.append(p.info.name);
10217                }
10218                if (bp.perm == p) {
10219                    bp.protectionLevel = p.info.protectionLevel;
10220                }
10221            }
10222
10223            if (r != null) {
10224                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10225            }
10226
10227            N = pkg.instrumentation.size();
10228            r = null;
10229            for (i=0; i<N; i++) {
10230                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10231                a.info.packageName = pkg.applicationInfo.packageName;
10232                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10233                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10234                a.info.splitNames = pkg.splitNames;
10235                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10236                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10237                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10238                a.info.dataDir = pkg.applicationInfo.dataDir;
10239                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10240                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10241                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10242                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10243                mInstrumentation.put(a.getComponentName(), a);
10244                if (chatty) {
10245                    if (r == null) {
10246                        r = new StringBuilder(256);
10247                    } else {
10248                        r.append(' ');
10249                    }
10250                    r.append(a.info.name);
10251                }
10252            }
10253            if (r != null) {
10254                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10255            }
10256
10257            if (pkg.protectedBroadcasts != null) {
10258                N = pkg.protectedBroadcasts.size();
10259                for (i=0; i<N; i++) {
10260                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10261                }
10262            }
10263
10264            // Create idmap files for pairs of (packages, overlay packages).
10265            // Note: "android", ie framework-res.apk, is handled by native layers.
10266            if (pkg.mOverlayTarget != null) {
10267                // This is an overlay package.
10268                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10269                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10270                        mOverlays.put(pkg.mOverlayTarget,
10271                                new ArrayMap<String, PackageParser.Package>());
10272                    }
10273                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10274                    map.put(pkg.packageName, pkg);
10275                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10276                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10277                        createIdmapFailed = true;
10278                    }
10279                }
10280            } else if (mOverlays.containsKey(pkg.packageName) &&
10281                    !pkg.packageName.equals("android")) {
10282                // This is a regular package, with one or more known overlay packages.
10283                createIdmapsForPackageLI(pkg);
10284            }
10285        }
10286
10287        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10288
10289        if (createIdmapFailed) {
10290            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10291                    "scanPackageLI failed to createIdmap");
10292        }
10293    }
10294
10295    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10296            PackageParser.Package update, int[] userIds) {
10297        if (existing.applicationInfo == null || update.applicationInfo == null) {
10298            // This isn't due to an app installation.
10299            return;
10300        }
10301
10302        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10303        final File newCodePath = new File(update.applicationInfo.getCodePath());
10304
10305        // The codePath hasn't changed, so there's nothing for us to do.
10306        if (Objects.equals(oldCodePath, newCodePath)) {
10307            return;
10308        }
10309
10310        File canonicalNewCodePath;
10311        try {
10312            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10313        } catch (IOException e) {
10314            Slog.w(TAG, "Failed to get canonical path.", e);
10315            return;
10316        }
10317
10318        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10319        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10320        // that the last component of the path (i.e, the name) doesn't need canonicalization
10321        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10322        // but may change in the future. Hopefully this function won't exist at that point.
10323        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10324                oldCodePath.getName());
10325
10326        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10327        // with "@".
10328        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10329        if (!oldMarkerPrefix.endsWith("@")) {
10330            oldMarkerPrefix += "@";
10331        }
10332        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10333        if (!newMarkerPrefix.endsWith("@")) {
10334            newMarkerPrefix += "@";
10335        }
10336
10337        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10338        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10339        for (String updatedPath : updatedPaths) {
10340            String updatedPathName = new File(updatedPath).getName();
10341            markerSuffixes.add(updatedPathName.replace('/', '@'));
10342        }
10343
10344        for (int userId : userIds) {
10345            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10346
10347            for (String markerSuffix : markerSuffixes) {
10348                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10349                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10350                if (oldForeignUseMark.exists()) {
10351                    try {
10352                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10353                                newForeignUseMark.getAbsolutePath());
10354                    } catch (ErrnoException e) {
10355                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10356                        oldForeignUseMark.delete();
10357                    }
10358                }
10359            }
10360        }
10361    }
10362
10363    /**
10364     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10365     * is derived purely on the basis of the contents of {@code scanFile} and
10366     * {@code cpuAbiOverride}.
10367     *
10368     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10369     */
10370    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10371                                 String cpuAbiOverride, boolean extractLibs,
10372                                 File appLib32InstallDir)
10373            throws PackageManagerException {
10374        // Give ourselves some initial paths; we'll come back for another
10375        // pass once we've determined ABI below.
10376        setNativeLibraryPaths(pkg, appLib32InstallDir);
10377
10378        // We would never need to extract libs for forward-locked and external packages,
10379        // since the container service will do it for us. We shouldn't attempt to
10380        // extract libs from system app when it was not updated.
10381        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10382                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10383            extractLibs = false;
10384        }
10385
10386        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10387        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10388
10389        NativeLibraryHelper.Handle handle = null;
10390        try {
10391            handle = NativeLibraryHelper.Handle.create(pkg);
10392            // TODO(multiArch): This can be null for apps that didn't go through the
10393            // usual installation process. We can calculate it again, like we
10394            // do during install time.
10395            //
10396            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10397            // unnecessary.
10398            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10399
10400            // Null out the abis so that they can be recalculated.
10401            pkg.applicationInfo.primaryCpuAbi = null;
10402            pkg.applicationInfo.secondaryCpuAbi = null;
10403            if (isMultiArch(pkg.applicationInfo)) {
10404                // Warn if we've set an abiOverride for multi-lib packages..
10405                // By definition, we need to copy both 32 and 64 bit libraries for
10406                // such packages.
10407                if (pkg.cpuAbiOverride != null
10408                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10409                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10410                }
10411
10412                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10413                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10414                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10415                    if (extractLibs) {
10416                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10417                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10418                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10419                                useIsaSpecificSubdirs);
10420                    } else {
10421                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10422                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10423                    }
10424                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10425                }
10426
10427                maybeThrowExceptionForMultiArchCopy(
10428                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10429
10430                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10431                    if (extractLibs) {
10432                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10433                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10434                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10435                                useIsaSpecificSubdirs);
10436                    } else {
10437                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10438                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10439                    }
10440                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10441                }
10442
10443                maybeThrowExceptionForMultiArchCopy(
10444                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10445
10446                if (abi64 >= 0) {
10447                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10448                }
10449
10450                if (abi32 >= 0) {
10451                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10452                    if (abi64 >= 0) {
10453                        if (pkg.use32bitAbi) {
10454                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10455                            pkg.applicationInfo.primaryCpuAbi = abi;
10456                        } else {
10457                            pkg.applicationInfo.secondaryCpuAbi = abi;
10458                        }
10459                    } else {
10460                        pkg.applicationInfo.primaryCpuAbi = abi;
10461                    }
10462                }
10463
10464            } else {
10465                String[] abiList = (cpuAbiOverride != null) ?
10466                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10467
10468                // Enable gross and lame hacks for apps that are built with old
10469                // SDK tools. We must scan their APKs for renderscript bitcode and
10470                // not launch them if it's present. Don't bother checking on devices
10471                // that don't have 64 bit support.
10472                boolean needsRenderScriptOverride = false;
10473                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10474                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10475                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10476                    needsRenderScriptOverride = true;
10477                }
10478
10479                final int copyRet;
10480                if (extractLibs) {
10481                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10482                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10483                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10484                } else {
10485                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10486                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10487                }
10488                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10489
10490                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10491                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10492                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10493                }
10494
10495                if (copyRet >= 0) {
10496                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10497                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10498                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10499                } else if (needsRenderScriptOverride) {
10500                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10501                }
10502            }
10503        } catch (IOException ioe) {
10504            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10505        } finally {
10506            IoUtils.closeQuietly(handle);
10507        }
10508
10509        // Now that we've calculated the ABIs and determined if it's an internal app,
10510        // we will go ahead and populate the nativeLibraryPath.
10511        setNativeLibraryPaths(pkg, appLib32InstallDir);
10512    }
10513
10514    /**
10515     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10516     * i.e, so that all packages can be run inside a single process if required.
10517     *
10518     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10519     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10520     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10521     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10522     * updating a package that belongs to a shared user.
10523     *
10524     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10525     * adds unnecessary complexity.
10526     */
10527    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10528            PackageParser.Package scannedPackage) {
10529        String requiredInstructionSet = null;
10530        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10531            requiredInstructionSet = VMRuntime.getInstructionSet(
10532                     scannedPackage.applicationInfo.primaryCpuAbi);
10533        }
10534
10535        PackageSetting requirer = null;
10536        for (PackageSetting ps : packagesForUser) {
10537            // If packagesForUser contains scannedPackage, we skip it. This will happen
10538            // when scannedPackage is an update of an existing package. Without this check,
10539            // we will never be able to change the ABI of any package belonging to a shared
10540            // user, even if it's compatible with other packages.
10541            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10542                if (ps.primaryCpuAbiString == null) {
10543                    continue;
10544                }
10545
10546                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10547                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10548                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10549                    // this but there's not much we can do.
10550                    String errorMessage = "Instruction set mismatch, "
10551                            + ((requirer == null) ? "[caller]" : requirer)
10552                            + " requires " + requiredInstructionSet + " whereas " + ps
10553                            + " requires " + instructionSet;
10554                    Slog.w(TAG, errorMessage);
10555                }
10556
10557                if (requiredInstructionSet == null) {
10558                    requiredInstructionSet = instructionSet;
10559                    requirer = ps;
10560                }
10561            }
10562        }
10563
10564        if (requiredInstructionSet != null) {
10565            String adjustedAbi;
10566            if (requirer != null) {
10567                // requirer != null implies that either scannedPackage was null or that scannedPackage
10568                // did not require an ABI, in which case we have to adjust scannedPackage to match
10569                // the ABI of the set (which is the same as requirer's ABI)
10570                adjustedAbi = requirer.primaryCpuAbiString;
10571                if (scannedPackage != null) {
10572                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10573                }
10574            } else {
10575                // requirer == null implies that we're updating all ABIs in the set to
10576                // match scannedPackage.
10577                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10578            }
10579
10580            for (PackageSetting ps : packagesForUser) {
10581                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10582                    if (ps.primaryCpuAbiString != null) {
10583                        continue;
10584                    }
10585
10586                    ps.primaryCpuAbiString = adjustedAbi;
10587                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10588                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10589                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10590                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10591                                + " (requirer="
10592                                + (requirer == null ? "null" : requirer.pkg.packageName)
10593                                + ", scannedPackage="
10594                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10595                                + ")");
10596                        try {
10597                            mInstaller.rmdex(ps.codePathString,
10598                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10599                        } catch (InstallerException ignored) {
10600                        }
10601                    }
10602                }
10603            }
10604        }
10605    }
10606
10607    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10608        synchronized (mPackages) {
10609            mResolverReplaced = true;
10610            // Set up information for custom user intent resolution activity.
10611            mResolveActivity.applicationInfo = pkg.applicationInfo;
10612            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10613            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10614            mResolveActivity.processName = pkg.applicationInfo.packageName;
10615            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10616            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10617                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10618            mResolveActivity.theme = 0;
10619            mResolveActivity.exported = true;
10620            mResolveActivity.enabled = true;
10621            mResolveInfo.activityInfo = mResolveActivity;
10622            mResolveInfo.priority = 0;
10623            mResolveInfo.preferredOrder = 0;
10624            mResolveInfo.match = 0;
10625            mResolveComponentName = mCustomResolverComponentName;
10626            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10627                    mResolveComponentName);
10628        }
10629    }
10630
10631    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10632        if (installerComponent == null) {
10633            if (DEBUG_EPHEMERAL) {
10634                Slog.d(TAG, "Clear ephemeral installer activity");
10635            }
10636            mEphemeralInstallerActivity.applicationInfo = null;
10637            return;
10638        }
10639
10640        if (DEBUG_EPHEMERAL) {
10641            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10642        }
10643        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10644        // Set up information for ephemeral installer activity
10645        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10646        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10647        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10648        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10649        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10650        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10651                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10652        mEphemeralInstallerActivity.theme = 0;
10653        mEphemeralInstallerActivity.exported = true;
10654        mEphemeralInstallerActivity.enabled = true;
10655        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10656        mEphemeralInstallerInfo.priority = 0;
10657        mEphemeralInstallerInfo.preferredOrder = 1;
10658        mEphemeralInstallerInfo.isDefault = true;
10659        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10660                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10661    }
10662
10663    private static String calculateBundledApkRoot(final String codePathString) {
10664        final File codePath = new File(codePathString);
10665        final File codeRoot;
10666        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10667            codeRoot = Environment.getRootDirectory();
10668        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10669            codeRoot = Environment.getOemDirectory();
10670        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10671            codeRoot = Environment.getVendorDirectory();
10672        } else {
10673            // Unrecognized code path; take its top real segment as the apk root:
10674            // e.g. /something/app/blah.apk => /something
10675            try {
10676                File f = codePath.getCanonicalFile();
10677                File parent = f.getParentFile();    // non-null because codePath is a file
10678                File tmp;
10679                while ((tmp = parent.getParentFile()) != null) {
10680                    f = parent;
10681                    parent = tmp;
10682                }
10683                codeRoot = f;
10684                Slog.w(TAG, "Unrecognized code path "
10685                        + codePath + " - using " + codeRoot);
10686            } catch (IOException e) {
10687                // Can't canonicalize the code path -- shenanigans?
10688                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10689                return Environment.getRootDirectory().getPath();
10690            }
10691        }
10692        return codeRoot.getPath();
10693    }
10694
10695    /**
10696     * Derive and set the location of native libraries for the given package,
10697     * which varies depending on where and how the package was installed.
10698     */
10699    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10700        final ApplicationInfo info = pkg.applicationInfo;
10701        final String codePath = pkg.codePath;
10702        final File codeFile = new File(codePath);
10703        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10704        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10705
10706        info.nativeLibraryRootDir = null;
10707        info.nativeLibraryRootRequiresIsa = false;
10708        info.nativeLibraryDir = null;
10709        info.secondaryNativeLibraryDir = null;
10710
10711        if (isApkFile(codeFile)) {
10712            // Monolithic install
10713            if (bundledApp) {
10714                // If "/system/lib64/apkname" exists, assume that is the per-package
10715                // native library directory to use; otherwise use "/system/lib/apkname".
10716                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10717                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10718                        getPrimaryInstructionSet(info));
10719
10720                // This is a bundled system app so choose the path based on the ABI.
10721                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10722                // is just the default path.
10723                final String apkName = deriveCodePathName(codePath);
10724                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10725                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10726                        apkName).getAbsolutePath();
10727
10728                if (info.secondaryCpuAbi != null) {
10729                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10730                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10731                            secondaryLibDir, apkName).getAbsolutePath();
10732                }
10733            } else if (asecApp) {
10734                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10735                        .getAbsolutePath();
10736            } else {
10737                final String apkName = deriveCodePathName(codePath);
10738                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10739                        .getAbsolutePath();
10740            }
10741
10742            info.nativeLibraryRootRequiresIsa = false;
10743            info.nativeLibraryDir = info.nativeLibraryRootDir;
10744        } else {
10745            // Cluster install
10746            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10747            info.nativeLibraryRootRequiresIsa = true;
10748
10749            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10750                    getPrimaryInstructionSet(info)).getAbsolutePath();
10751
10752            if (info.secondaryCpuAbi != null) {
10753                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10754                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10755            }
10756        }
10757    }
10758
10759    /**
10760     * Calculate the abis and roots for a bundled app. These can uniquely
10761     * be determined from the contents of the system partition, i.e whether
10762     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10763     * of this information, and instead assume that the system was built
10764     * sensibly.
10765     */
10766    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10767                                           PackageSetting pkgSetting) {
10768        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10769
10770        // If "/system/lib64/apkname" exists, assume that is the per-package
10771        // native library directory to use; otherwise use "/system/lib/apkname".
10772        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10773        setBundledAppAbi(pkg, apkRoot, apkName);
10774        // pkgSetting might be null during rescan following uninstall of updates
10775        // to a bundled app, so accommodate that possibility.  The settings in
10776        // that case will be established later from the parsed package.
10777        //
10778        // If the settings aren't null, sync them up with what we've just derived.
10779        // note that apkRoot isn't stored in the package settings.
10780        if (pkgSetting != null) {
10781            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10782            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10783        }
10784    }
10785
10786    /**
10787     * Deduces the ABI of a bundled app and sets the relevant fields on the
10788     * parsed pkg object.
10789     *
10790     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10791     *        under which system libraries are installed.
10792     * @param apkName the name of the installed package.
10793     */
10794    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10795        final File codeFile = new File(pkg.codePath);
10796
10797        final boolean has64BitLibs;
10798        final boolean has32BitLibs;
10799        if (isApkFile(codeFile)) {
10800            // Monolithic install
10801            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10802            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10803        } else {
10804            // Cluster install
10805            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10806            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10807                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10808                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10809                has64BitLibs = (new File(rootDir, isa)).exists();
10810            } else {
10811                has64BitLibs = false;
10812            }
10813            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10814                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10815                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10816                has32BitLibs = (new File(rootDir, isa)).exists();
10817            } else {
10818                has32BitLibs = false;
10819            }
10820        }
10821
10822        if (has64BitLibs && !has32BitLibs) {
10823            // The package has 64 bit libs, but not 32 bit libs. Its primary
10824            // ABI should be 64 bit. We can safely assume here that the bundled
10825            // native libraries correspond to the most preferred ABI in the list.
10826
10827            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10828            pkg.applicationInfo.secondaryCpuAbi = null;
10829        } else if (has32BitLibs && !has64BitLibs) {
10830            // The package has 32 bit libs but not 64 bit libs. Its primary
10831            // ABI should be 32 bit.
10832
10833            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10834            pkg.applicationInfo.secondaryCpuAbi = null;
10835        } else if (has32BitLibs && has64BitLibs) {
10836            // The application has both 64 and 32 bit bundled libraries. We check
10837            // here that the app declares multiArch support, and warn if it doesn't.
10838            //
10839            // We will be lenient here and record both ABIs. The primary will be the
10840            // ABI that's higher on the list, i.e, a device that's configured to prefer
10841            // 64 bit apps will see a 64 bit primary ABI,
10842
10843            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10844                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10845            }
10846
10847            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10848                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10849                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10850            } else {
10851                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10852                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10853            }
10854        } else {
10855            pkg.applicationInfo.primaryCpuAbi = null;
10856            pkg.applicationInfo.secondaryCpuAbi = null;
10857        }
10858    }
10859
10860    private void killApplication(String pkgName, int appId, String reason) {
10861        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10862    }
10863
10864    private void killApplication(String pkgName, int appId, int userId, String reason) {
10865        // Request the ActivityManager to kill the process(only for existing packages)
10866        // so that we do not end up in a confused state while the user is still using the older
10867        // version of the application while the new one gets installed.
10868        final long token = Binder.clearCallingIdentity();
10869        try {
10870            IActivityManager am = ActivityManager.getService();
10871            if (am != null) {
10872                try {
10873                    am.killApplication(pkgName, appId, userId, reason);
10874                } catch (RemoteException e) {
10875                }
10876            }
10877        } finally {
10878            Binder.restoreCallingIdentity(token);
10879        }
10880    }
10881
10882    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10883        // Remove the parent package setting
10884        PackageSetting ps = (PackageSetting) pkg.mExtras;
10885        if (ps != null) {
10886            removePackageLI(ps, chatty);
10887        }
10888        // Remove the child package setting
10889        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10890        for (int i = 0; i < childCount; i++) {
10891            PackageParser.Package childPkg = pkg.childPackages.get(i);
10892            ps = (PackageSetting) childPkg.mExtras;
10893            if (ps != null) {
10894                removePackageLI(ps, chatty);
10895            }
10896        }
10897    }
10898
10899    void removePackageLI(PackageSetting ps, boolean chatty) {
10900        if (DEBUG_INSTALL) {
10901            if (chatty)
10902                Log.d(TAG, "Removing package " + ps.name);
10903        }
10904
10905        // writer
10906        synchronized (mPackages) {
10907            mPackages.remove(ps.name);
10908            final PackageParser.Package pkg = ps.pkg;
10909            if (pkg != null) {
10910                cleanPackageDataStructuresLILPw(pkg, chatty);
10911            }
10912        }
10913    }
10914
10915    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10916        if (DEBUG_INSTALL) {
10917            if (chatty)
10918                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10919        }
10920
10921        // writer
10922        synchronized (mPackages) {
10923            // Remove the parent package
10924            mPackages.remove(pkg.applicationInfo.packageName);
10925            cleanPackageDataStructuresLILPw(pkg, chatty);
10926
10927            // Remove the child packages
10928            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10929            for (int i = 0; i < childCount; i++) {
10930                PackageParser.Package childPkg = pkg.childPackages.get(i);
10931                mPackages.remove(childPkg.applicationInfo.packageName);
10932                cleanPackageDataStructuresLILPw(childPkg, chatty);
10933            }
10934        }
10935    }
10936
10937    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10938        int N = pkg.providers.size();
10939        StringBuilder r = null;
10940        int i;
10941        for (i=0; i<N; i++) {
10942            PackageParser.Provider p = pkg.providers.get(i);
10943            mProviders.removeProvider(p);
10944            if (p.info.authority == null) {
10945
10946                /* There was another ContentProvider with this authority when
10947                 * this app was installed so this authority is null,
10948                 * Ignore it as we don't have to unregister the provider.
10949                 */
10950                continue;
10951            }
10952            String names[] = p.info.authority.split(";");
10953            for (int j = 0; j < names.length; j++) {
10954                if (mProvidersByAuthority.get(names[j]) == p) {
10955                    mProvidersByAuthority.remove(names[j]);
10956                    if (DEBUG_REMOVE) {
10957                        if (chatty)
10958                            Log.d(TAG, "Unregistered content provider: " + names[j]
10959                                    + ", className = " + p.info.name + ", isSyncable = "
10960                                    + p.info.isSyncable);
10961                    }
10962                }
10963            }
10964            if (DEBUG_REMOVE && chatty) {
10965                if (r == null) {
10966                    r = new StringBuilder(256);
10967                } else {
10968                    r.append(' ');
10969                }
10970                r.append(p.info.name);
10971            }
10972        }
10973        if (r != null) {
10974            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10975        }
10976
10977        N = pkg.services.size();
10978        r = null;
10979        for (i=0; i<N; i++) {
10980            PackageParser.Service s = pkg.services.get(i);
10981            mServices.removeService(s);
10982            if (chatty) {
10983                if (r == null) {
10984                    r = new StringBuilder(256);
10985                } else {
10986                    r.append(' ');
10987                }
10988                r.append(s.info.name);
10989            }
10990        }
10991        if (r != null) {
10992            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10993        }
10994
10995        N = pkg.receivers.size();
10996        r = null;
10997        for (i=0; i<N; i++) {
10998            PackageParser.Activity a = pkg.receivers.get(i);
10999            mReceivers.removeActivity(a, "receiver");
11000            if (DEBUG_REMOVE && chatty) {
11001                if (r == null) {
11002                    r = new StringBuilder(256);
11003                } else {
11004                    r.append(' ');
11005                }
11006                r.append(a.info.name);
11007            }
11008        }
11009        if (r != null) {
11010            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11011        }
11012
11013        N = pkg.activities.size();
11014        r = null;
11015        for (i=0; i<N; i++) {
11016            PackageParser.Activity a = pkg.activities.get(i);
11017            mActivities.removeActivity(a, "activity");
11018            if (DEBUG_REMOVE && chatty) {
11019                if (r == null) {
11020                    r = new StringBuilder(256);
11021                } else {
11022                    r.append(' ');
11023                }
11024                r.append(a.info.name);
11025            }
11026        }
11027        if (r != null) {
11028            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11029        }
11030
11031        N = pkg.permissions.size();
11032        r = null;
11033        for (i=0; i<N; i++) {
11034            PackageParser.Permission p = pkg.permissions.get(i);
11035            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11036            if (bp == null) {
11037                bp = mSettings.mPermissionTrees.get(p.info.name);
11038            }
11039            if (bp != null && bp.perm == p) {
11040                bp.perm = null;
11041                if (DEBUG_REMOVE && chatty) {
11042                    if (r == null) {
11043                        r = new StringBuilder(256);
11044                    } else {
11045                        r.append(' ');
11046                    }
11047                    r.append(p.info.name);
11048                }
11049            }
11050            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11051                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11052                if (appOpPkgs != null) {
11053                    appOpPkgs.remove(pkg.packageName);
11054                }
11055            }
11056        }
11057        if (r != null) {
11058            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11059        }
11060
11061        N = pkg.requestedPermissions.size();
11062        r = null;
11063        for (i=0; i<N; i++) {
11064            String perm = pkg.requestedPermissions.get(i);
11065            BasePermission bp = mSettings.mPermissions.get(perm);
11066            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11067                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11068                if (appOpPkgs != null) {
11069                    appOpPkgs.remove(pkg.packageName);
11070                    if (appOpPkgs.isEmpty()) {
11071                        mAppOpPermissionPackages.remove(perm);
11072                    }
11073                }
11074            }
11075        }
11076        if (r != null) {
11077            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11078        }
11079
11080        N = pkg.instrumentation.size();
11081        r = null;
11082        for (i=0; i<N; i++) {
11083            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11084            mInstrumentation.remove(a.getComponentName());
11085            if (DEBUG_REMOVE && chatty) {
11086                if (r == null) {
11087                    r = new StringBuilder(256);
11088                } else {
11089                    r.append(' ');
11090                }
11091                r.append(a.info.name);
11092            }
11093        }
11094        if (r != null) {
11095            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11096        }
11097
11098        r = null;
11099        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11100            // Only system apps can hold shared libraries.
11101            if (pkg.libraryNames != null) {
11102                for (i = 0; i < pkg.libraryNames.size(); i++) {
11103                    String name = pkg.libraryNames.get(i);
11104                    if (removeSharedLibraryLPw(name, 0)) {
11105                        if (DEBUG_REMOVE && chatty) {
11106                            if (r == null) {
11107                                r = new StringBuilder(256);
11108                            } else {
11109                                r.append(' ');
11110                            }
11111                            r.append(name);
11112                        }
11113                    }
11114                }
11115            }
11116        }
11117
11118        r = null;
11119
11120        // Any package can hold static shared libraries.
11121        if (pkg.staticSharedLibName != null) {
11122            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11123                if (DEBUG_REMOVE && chatty) {
11124                    if (r == null) {
11125                        r = new StringBuilder(256);
11126                    } else {
11127                        r.append(' ');
11128                    }
11129                    r.append(pkg.staticSharedLibName);
11130                }
11131            }
11132        }
11133
11134        if (r != null) {
11135            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11136        }
11137    }
11138
11139    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11140        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11141            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11142                return true;
11143            }
11144        }
11145        return false;
11146    }
11147
11148    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11149    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11150    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11151
11152    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11153        // Update the parent permissions
11154        updatePermissionsLPw(pkg.packageName, pkg, flags);
11155        // Update the child permissions
11156        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11157        for (int i = 0; i < childCount; i++) {
11158            PackageParser.Package childPkg = pkg.childPackages.get(i);
11159            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11160        }
11161    }
11162
11163    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11164            int flags) {
11165        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11166        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11167    }
11168
11169    private void updatePermissionsLPw(String changingPkg,
11170            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11171        // Make sure there are no dangling permission trees.
11172        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11173        while (it.hasNext()) {
11174            final BasePermission bp = it.next();
11175            if (bp.packageSetting == null) {
11176                // We may not yet have parsed the package, so just see if
11177                // we still know about its settings.
11178                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11179            }
11180            if (bp.packageSetting == null) {
11181                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11182                        + " from package " + bp.sourcePackage);
11183                it.remove();
11184            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11185                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11186                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11187                            + " from package " + bp.sourcePackage);
11188                    flags |= UPDATE_PERMISSIONS_ALL;
11189                    it.remove();
11190                }
11191            }
11192        }
11193
11194        // Make sure all dynamic permissions have been assigned to a package,
11195        // and make sure there are no dangling permissions.
11196        it = mSettings.mPermissions.values().iterator();
11197        while (it.hasNext()) {
11198            final BasePermission bp = it.next();
11199            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11200                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11201                        + bp.name + " pkg=" + bp.sourcePackage
11202                        + " info=" + bp.pendingInfo);
11203                if (bp.packageSetting == null && bp.pendingInfo != null) {
11204                    final BasePermission tree = findPermissionTreeLP(bp.name);
11205                    if (tree != null && tree.perm != null) {
11206                        bp.packageSetting = tree.packageSetting;
11207                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11208                                new PermissionInfo(bp.pendingInfo));
11209                        bp.perm.info.packageName = tree.perm.info.packageName;
11210                        bp.perm.info.name = bp.name;
11211                        bp.uid = tree.uid;
11212                    }
11213                }
11214            }
11215            if (bp.packageSetting == null) {
11216                // We may not yet have parsed the package, so just see if
11217                // we still know about its settings.
11218                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11219            }
11220            if (bp.packageSetting == null) {
11221                Slog.w(TAG, "Removing dangling permission: " + bp.name
11222                        + " from package " + bp.sourcePackage);
11223                it.remove();
11224            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11225                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11226                    Slog.i(TAG, "Removing old permission: " + bp.name
11227                            + " from package " + bp.sourcePackage);
11228                    flags |= UPDATE_PERMISSIONS_ALL;
11229                    it.remove();
11230                }
11231            }
11232        }
11233
11234        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11235        // Now update the permissions for all packages, in particular
11236        // replace the granted permissions of the system packages.
11237        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11238            for (PackageParser.Package pkg : mPackages.values()) {
11239                if (pkg != pkgInfo) {
11240                    // Only replace for packages on requested volume
11241                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11242                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11243                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11244                    grantPermissionsLPw(pkg, replace, changingPkg);
11245                }
11246            }
11247        }
11248
11249        if (pkgInfo != null) {
11250            // Only replace for packages on requested volume
11251            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11252            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11253                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11254            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11255        }
11256        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11257    }
11258
11259    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11260            String packageOfInterest) {
11261        // IMPORTANT: There are two types of permissions: install and runtime.
11262        // Install time permissions are granted when the app is installed to
11263        // all device users and users added in the future. Runtime permissions
11264        // are granted at runtime explicitly to specific users. Normal and signature
11265        // protected permissions are install time permissions. Dangerous permissions
11266        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11267        // otherwise they are runtime permissions. This function does not manage
11268        // runtime permissions except for the case an app targeting Lollipop MR1
11269        // being upgraded to target a newer SDK, in which case dangerous permissions
11270        // are transformed from install time to runtime ones.
11271
11272        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11273        if (ps == null) {
11274            return;
11275        }
11276
11277        PermissionsState permissionsState = ps.getPermissionsState();
11278        PermissionsState origPermissions = permissionsState;
11279
11280        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11281
11282        boolean runtimePermissionsRevoked = false;
11283        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11284
11285        boolean changedInstallPermission = false;
11286
11287        if (replace) {
11288            ps.installPermissionsFixed = false;
11289            if (!ps.isSharedUser()) {
11290                origPermissions = new PermissionsState(permissionsState);
11291                permissionsState.reset();
11292            } else {
11293                // We need to know only about runtime permission changes since the
11294                // calling code always writes the install permissions state but
11295                // the runtime ones are written only if changed. The only cases of
11296                // changed runtime permissions here are promotion of an install to
11297                // runtime and revocation of a runtime from a shared user.
11298                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11299                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11300                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11301                    runtimePermissionsRevoked = true;
11302                }
11303            }
11304        }
11305
11306        permissionsState.setGlobalGids(mGlobalGids);
11307
11308        final int N = pkg.requestedPermissions.size();
11309        for (int i=0; i<N; i++) {
11310            final String name = pkg.requestedPermissions.get(i);
11311            final BasePermission bp = mSettings.mPermissions.get(name);
11312
11313            if (DEBUG_INSTALL) {
11314                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11315            }
11316
11317            if (bp == null || bp.packageSetting == null) {
11318                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11319                    Slog.w(TAG, "Unknown permission " + name
11320                            + " in package " + pkg.packageName);
11321                }
11322                continue;
11323            }
11324
11325
11326            // Limit ephemeral apps to ephemeral allowed permissions.
11327            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11328                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11329                        + pkg.packageName);
11330                continue;
11331            }
11332
11333            final String perm = bp.name;
11334            boolean allowedSig = false;
11335            int grant = GRANT_DENIED;
11336
11337            // Keep track of app op permissions.
11338            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11339                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11340                if (pkgs == null) {
11341                    pkgs = new ArraySet<>();
11342                    mAppOpPermissionPackages.put(bp.name, pkgs);
11343                }
11344                pkgs.add(pkg.packageName);
11345            }
11346
11347            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11348            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11349                    >= Build.VERSION_CODES.M;
11350            switch (level) {
11351                case PermissionInfo.PROTECTION_NORMAL: {
11352                    // For all apps normal permissions are install time ones.
11353                    grant = GRANT_INSTALL;
11354                } break;
11355
11356                case PermissionInfo.PROTECTION_DANGEROUS: {
11357                    // If a permission review is required for legacy apps we represent
11358                    // their permissions as always granted runtime ones since we need
11359                    // to keep the review required permission flag per user while an
11360                    // install permission's state is shared across all users.
11361                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11362                        // For legacy apps dangerous permissions are install time ones.
11363                        grant = GRANT_INSTALL;
11364                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11365                        // For legacy apps that became modern, install becomes runtime.
11366                        grant = GRANT_UPGRADE;
11367                    } else if (mPromoteSystemApps
11368                            && isSystemApp(ps)
11369                            && mExistingSystemPackages.contains(ps.name)) {
11370                        // For legacy system apps, install becomes runtime.
11371                        // We cannot check hasInstallPermission() for system apps since those
11372                        // permissions were granted implicitly and not persisted pre-M.
11373                        grant = GRANT_UPGRADE;
11374                    } else {
11375                        // For modern apps keep runtime permissions unchanged.
11376                        grant = GRANT_RUNTIME;
11377                    }
11378                } break;
11379
11380                case PermissionInfo.PROTECTION_SIGNATURE: {
11381                    // For all apps signature permissions are install time ones.
11382                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11383                    if (allowedSig) {
11384                        grant = GRANT_INSTALL;
11385                    }
11386                } break;
11387            }
11388
11389            if (DEBUG_INSTALL) {
11390                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11391            }
11392
11393            if (grant != GRANT_DENIED) {
11394                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11395                    // If this is an existing, non-system package, then
11396                    // we can't add any new permissions to it.
11397                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11398                        // Except...  if this is a permission that was added
11399                        // to the platform (note: need to only do this when
11400                        // updating the platform).
11401                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11402                            grant = GRANT_DENIED;
11403                        }
11404                    }
11405                }
11406
11407                switch (grant) {
11408                    case GRANT_INSTALL: {
11409                        // Revoke this as runtime permission to handle the case of
11410                        // a runtime permission being downgraded to an install one.
11411                        // Also in permission review mode we keep dangerous permissions
11412                        // for legacy apps
11413                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11414                            if (origPermissions.getRuntimePermissionState(
11415                                    bp.name, userId) != null) {
11416                                // Revoke the runtime permission and clear the flags.
11417                                origPermissions.revokeRuntimePermission(bp, userId);
11418                                origPermissions.updatePermissionFlags(bp, userId,
11419                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11420                                // If we revoked a permission permission, we have to write.
11421                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11422                                        changedRuntimePermissionUserIds, userId);
11423                            }
11424                        }
11425                        // Grant an install permission.
11426                        if (permissionsState.grantInstallPermission(bp) !=
11427                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11428                            changedInstallPermission = true;
11429                        }
11430                    } break;
11431
11432                    case GRANT_RUNTIME: {
11433                        // Grant previously granted runtime permissions.
11434                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11435                            PermissionState permissionState = origPermissions
11436                                    .getRuntimePermissionState(bp.name, userId);
11437                            int flags = permissionState != null
11438                                    ? permissionState.getFlags() : 0;
11439                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11440                                // Don't propagate the permission in a permission review mode if
11441                                // the former was revoked, i.e. marked to not propagate on upgrade.
11442                                // Note that in a permission review mode install permissions are
11443                                // represented as constantly granted runtime ones since we need to
11444                                // keep a per user state associated with the permission. Also the
11445                                // revoke on upgrade flag is no longer applicable and is reset.
11446                                final boolean revokeOnUpgrade = (flags & PackageManager
11447                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11448                                if (revokeOnUpgrade) {
11449                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11450                                    // Since we changed the flags, we have to write.
11451                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11452                                            changedRuntimePermissionUserIds, userId);
11453                                }
11454                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11455                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11456                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11457                                        // If we cannot put the permission as it was,
11458                                        // we have to write.
11459                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11460                                                changedRuntimePermissionUserIds, userId);
11461                                    }
11462                                }
11463
11464                                // If the app supports runtime permissions no need for a review.
11465                                if (mPermissionReviewRequired
11466                                        && appSupportsRuntimePermissions
11467                                        && (flags & PackageManager
11468                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11469                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11470                                    // Since we changed the flags, we have to write.
11471                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11472                                            changedRuntimePermissionUserIds, userId);
11473                                }
11474                            } else if (mPermissionReviewRequired
11475                                    && !appSupportsRuntimePermissions) {
11476                                // For legacy apps that need a permission review, every new
11477                                // runtime permission is granted but it is pending a review.
11478                                // We also need to review only platform defined runtime
11479                                // permissions as these are the only ones the platform knows
11480                                // how to disable the API to simulate revocation as legacy
11481                                // apps don't expect to run with revoked permissions.
11482                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11483                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11484                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11485                                        // We changed the flags, hence have to write.
11486                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11487                                                changedRuntimePermissionUserIds, userId);
11488                                    }
11489                                }
11490                                if (permissionsState.grantRuntimePermission(bp, userId)
11491                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11492                                    // We changed the permission, hence have to write.
11493                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11494                                            changedRuntimePermissionUserIds, userId);
11495                                }
11496                            }
11497                            // Propagate the permission flags.
11498                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11499                        }
11500                    } break;
11501
11502                    case GRANT_UPGRADE: {
11503                        // Grant runtime permissions for a previously held install permission.
11504                        PermissionState permissionState = origPermissions
11505                                .getInstallPermissionState(bp.name);
11506                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11507
11508                        if (origPermissions.revokeInstallPermission(bp)
11509                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11510                            // We will be transferring the permission flags, so clear them.
11511                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11512                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11513                            changedInstallPermission = true;
11514                        }
11515
11516                        // If the permission is not to be promoted to runtime we ignore it and
11517                        // also its other flags as they are not applicable to install permissions.
11518                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11519                            for (int userId : currentUserIds) {
11520                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11521                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11522                                    // Transfer the permission flags.
11523                                    permissionsState.updatePermissionFlags(bp, userId,
11524                                            flags, flags);
11525                                    // If we granted the permission, we have to write.
11526                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11527                                            changedRuntimePermissionUserIds, userId);
11528                                }
11529                            }
11530                        }
11531                    } break;
11532
11533                    default: {
11534                        if (packageOfInterest == null
11535                                || packageOfInterest.equals(pkg.packageName)) {
11536                            Slog.w(TAG, "Not granting permission " + perm
11537                                    + " to package " + pkg.packageName
11538                                    + " because it was previously installed without");
11539                        }
11540                    } break;
11541                }
11542            } else {
11543                if (permissionsState.revokeInstallPermission(bp) !=
11544                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11545                    // Also drop the permission flags.
11546                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11547                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11548                    changedInstallPermission = true;
11549                    Slog.i(TAG, "Un-granting permission " + perm
11550                            + " from package " + pkg.packageName
11551                            + " (protectionLevel=" + bp.protectionLevel
11552                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11553                            + ")");
11554                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11555                    // Don't print warning for app op permissions, since it is fine for them
11556                    // not to be granted, there is a UI for the user to decide.
11557                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11558                        Slog.w(TAG, "Not granting permission " + perm
11559                                + " to package " + pkg.packageName
11560                                + " (protectionLevel=" + bp.protectionLevel
11561                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11562                                + ")");
11563                    }
11564                }
11565            }
11566        }
11567
11568        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11569                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11570            // This is the first that we have heard about this package, so the
11571            // permissions we have now selected are fixed until explicitly
11572            // changed.
11573            ps.installPermissionsFixed = true;
11574        }
11575
11576        // Persist the runtime permissions state for users with changes. If permissions
11577        // were revoked because no app in the shared user declares them we have to
11578        // write synchronously to avoid losing runtime permissions state.
11579        for (int userId : changedRuntimePermissionUserIds) {
11580            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11581        }
11582    }
11583
11584    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11585        boolean allowed = false;
11586        final int NP = PackageParser.NEW_PERMISSIONS.length;
11587        for (int ip=0; ip<NP; ip++) {
11588            final PackageParser.NewPermissionInfo npi
11589                    = PackageParser.NEW_PERMISSIONS[ip];
11590            if (npi.name.equals(perm)
11591                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11592                allowed = true;
11593                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11594                        + pkg.packageName);
11595                break;
11596            }
11597        }
11598        return allowed;
11599    }
11600
11601    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11602            BasePermission bp, PermissionsState origPermissions) {
11603        boolean privilegedPermission = (bp.protectionLevel
11604                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11605        boolean privappPermissionsDisable =
11606                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11607        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11608        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11609        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11610                && !platformPackage && platformPermission) {
11611            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11612                    .getPrivAppPermissions(pkg.packageName);
11613            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11614            if (!whitelisted) {
11615                Slog.w(TAG, "Privileged permission " + perm + " for package "
11616                        + pkg.packageName + " - not in privapp-permissions whitelist");
11617                if (!mSystemReady) {
11618                    if (mPrivappPermissionsViolations == null) {
11619                        mPrivappPermissionsViolations = new ArraySet<>();
11620                    }
11621                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11622                }
11623                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11624                    return false;
11625                }
11626            }
11627        }
11628        boolean allowed = (compareSignatures(
11629                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11630                        == PackageManager.SIGNATURE_MATCH)
11631                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11632                        == PackageManager.SIGNATURE_MATCH);
11633        if (!allowed && privilegedPermission) {
11634            if (isSystemApp(pkg)) {
11635                // For updated system applications, a system permission
11636                // is granted only if it had been defined by the original application.
11637                if (pkg.isUpdatedSystemApp()) {
11638                    final PackageSetting sysPs = mSettings
11639                            .getDisabledSystemPkgLPr(pkg.packageName);
11640                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11641                        // If the original was granted this permission, we take
11642                        // that grant decision as read and propagate it to the
11643                        // update.
11644                        if (sysPs.isPrivileged()) {
11645                            allowed = true;
11646                        }
11647                    } else {
11648                        // The system apk may have been updated with an older
11649                        // version of the one on the data partition, but which
11650                        // granted a new system permission that it didn't have
11651                        // before.  In this case we do want to allow the app to
11652                        // now get the new permission if the ancestral apk is
11653                        // privileged to get it.
11654                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11655                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11656                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11657                                    allowed = true;
11658                                    break;
11659                                }
11660                            }
11661                        }
11662                        // Also if a privileged parent package on the system image or any of
11663                        // its children requested a privileged permission, the updated child
11664                        // packages can also get the permission.
11665                        if (pkg.parentPackage != null) {
11666                            final PackageSetting disabledSysParentPs = mSettings
11667                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11668                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11669                                    && disabledSysParentPs.isPrivileged()) {
11670                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11671                                    allowed = true;
11672                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11673                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11674                                    for (int i = 0; i < count; i++) {
11675                                        PackageParser.Package disabledSysChildPkg =
11676                                                disabledSysParentPs.pkg.childPackages.get(i);
11677                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11678                                                perm)) {
11679                                            allowed = true;
11680                                            break;
11681                                        }
11682                                    }
11683                                }
11684                            }
11685                        }
11686                    }
11687                } else {
11688                    allowed = isPrivilegedApp(pkg);
11689                }
11690            }
11691        }
11692        if (!allowed) {
11693            if (!allowed && (bp.protectionLevel
11694                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11695                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11696                // If this was a previously normal/dangerous permission that got moved
11697                // to a system permission as part of the runtime permission redesign, then
11698                // we still want to blindly grant it to old apps.
11699                allowed = true;
11700            }
11701            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11702                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11703                // If this permission is to be granted to the system installer and
11704                // this app is an installer, then it gets the permission.
11705                allowed = true;
11706            }
11707            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11708                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11709                // If this permission is to be granted to the system verifier and
11710                // this app is a verifier, then it gets the permission.
11711                allowed = true;
11712            }
11713            if (!allowed && (bp.protectionLevel
11714                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11715                    && isSystemApp(pkg)) {
11716                // Any pre-installed system app is allowed to get this permission.
11717                allowed = true;
11718            }
11719            if (!allowed && (bp.protectionLevel
11720                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11721                // For development permissions, a development permission
11722                // is granted only if it was already granted.
11723                allowed = origPermissions.hasInstallPermission(perm);
11724            }
11725            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11726                    && pkg.packageName.equals(mSetupWizardPackage)) {
11727                // If this permission is to be granted to the system setup wizard and
11728                // this app is a setup wizard, then it gets the permission.
11729                allowed = true;
11730            }
11731        }
11732        return allowed;
11733    }
11734
11735    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11736        final int permCount = pkg.requestedPermissions.size();
11737        for (int j = 0; j < permCount; j++) {
11738            String requestedPermission = pkg.requestedPermissions.get(j);
11739            if (permission.equals(requestedPermission)) {
11740                return true;
11741            }
11742        }
11743        return false;
11744    }
11745
11746    final class ActivityIntentResolver
11747            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11748        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11749                boolean defaultOnly, int userId) {
11750            if (!sUserManager.exists(userId)) return null;
11751            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11752            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11753        }
11754
11755        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11756                int userId) {
11757            if (!sUserManager.exists(userId)) return null;
11758            mFlags = flags;
11759            return super.queryIntent(intent, resolvedType,
11760                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11761                    userId);
11762        }
11763
11764        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11765                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11766            if (!sUserManager.exists(userId)) return null;
11767            if (packageActivities == null) {
11768                return null;
11769            }
11770            mFlags = flags;
11771            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11772            final int N = packageActivities.size();
11773            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11774                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11775
11776            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11777            for (int i = 0; i < N; ++i) {
11778                intentFilters = packageActivities.get(i).intents;
11779                if (intentFilters != null && intentFilters.size() > 0) {
11780                    PackageParser.ActivityIntentInfo[] array =
11781                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11782                    intentFilters.toArray(array);
11783                    listCut.add(array);
11784                }
11785            }
11786            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11787        }
11788
11789        /**
11790         * Finds a privileged activity that matches the specified activity names.
11791         */
11792        private PackageParser.Activity findMatchingActivity(
11793                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11794            for (PackageParser.Activity sysActivity : activityList) {
11795                if (sysActivity.info.name.equals(activityInfo.name)) {
11796                    return sysActivity;
11797                }
11798                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11799                    return sysActivity;
11800                }
11801                if (sysActivity.info.targetActivity != null) {
11802                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11803                        return sysActivity;
11804                    }
11805                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11806                        return sysActivity;
11807                    }
11808                }
11809            }
11810            return null;
11811        }
11812
11813        public class IterGenerator<E> {
11814            public Iterator<E> generate(ActivityIntentInfo info) {
11815                return null;
11816            }
11817        }
11818
11819        public class ActionIterGenerator extends IterGenerator<String> {
11820            @Override
11821            public Iterator<String> generate(ActivityIntentInfo info) {
11822                return info.actionsIterator();
11823            }
11824        }
11825
11826        public class CategoriesIterGenerator extends IterGenerator<String> {
11827            @Override
11828            public Iterator<String> generate(ActivityIntentInfo info) {
11829                return info.categoriesIterator();
11830            }
11831        }
11832
11833        public class SchemesIterGenerator extends IterGenerator<String> {
11834            @Override
11835            public Iterator<String> generate(ActivityIntentInfo info) {
11836                return info.schemesIterator();
11837            }
11838        }
11839
11840        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11841            @Override
11842            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11843                return info.authoritiesIterator();
11844            }
11845        }
11846
11847        /**
11848         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11849         * MODIFIED. Do not pass in a list that should not be changed.
11850         */
11851        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11852                IterGenerator<T> generator, Iterator<T> searchIterator) {
11853            // loop through the set of actions; every one must be found in the intent filter
11854            while (searchIterator.hasNext()) {
11855                // we must have at least one filter in the list to consider a match
11856                if (intentList.size() == 0) {
11857                    break;
11858                }
11859
11860                final T searchAction = searchIterator.next();
11861
11862                // loop through the set of intent filters
11863                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11864                while (intentIter.hasNext()) {
11865                    final ActivityIntentInfo intentInfo = intentIter.next();
11866                    boolean selectionFound = false;
11867
11868                    // loop through the intent filter's selection criteria; at least one
11869                    // of them must match the searched criteria
11870                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11871                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11872                        final T intentSelection = intentSelectionIter.next();
11873                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11874                            selectionFound = true;
11875                            break;
11876                        }
11877                    }
11878
11879                    // the selection criteria wasn't found in this filter's set; this filter
11880                    // is not a potential match
11881                    if (!selectionFound) {
11882                        intentIter.remove();
11883                    }
11884                }
11885            }
11886        }
11887
11888        private boolean isProtectedAction(ActivityIntentInfo filter) {
11889            final Iterator<String> actionsIter = filter.actionsIterator();
11890            while (actionsIter != null && actionsIter.hasNext()) {
11891                final String filterAction = actionsIter.next();
11892                if (PROTECTED_ACTIONS.contains(filterAction)) {
11893                    return true;
11894                }
11895            }
11896            return false;
11897        }
11898
11899        /**
11900         * Adjusts the priority of the given intent filter according to policy.
11901         * <p>
11902         * <ul>
11903         * <li>The priority for non privileged applications is capped to '0'</li>
11904         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11905         * <li>The priority for unbundled updates to privileged applications is capped to the
11906         *      priority defined on the system partition</li>
11907         * </ul>
11908         * <p>
11909         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11910         * allowed to obtain any priority on any action.
11911         */
11912        private void adjustPriority(
11913                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11914            // nothing to do; priority is fine as-is
11915            if (intent.getPriority() <= 0) {
11916                return;
11917            }
11918
11919            final ActivityInfo activityInfo = intent.activity.info;
11920            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11921
11922            final boolean privilegedApp =
11923                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11924            if (!privilegedApp) {
11925                // non-privileged applications can never define a priority >0
11926                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11927                        + " package: " + applicationInfo.packageName
11928                        + " activity: " + intent.activity.className
11929                        + " origPrio: " + intent.getPriority());
11930                intent.setPriority(0);
11931                return;
11932            }
11933
11934            if (systemActivities == null) {
11935                // the system package is not disabled; we're parsing the system partition
11936                if (isProtectedAction(intent)) {
11937                    if (mDeferProtectedFilters) {
11938                        // We can't deal with these just yet. No component should ever obtain a
11939                        // >0 priority for a protected actions, with ONE exception -- the setup
11940                        // wizard. The setup wizard, however, cannot be known until we're able to
11941                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11942                        // until all intent filters have been processed. Chicken, meet egg.
11943                        // Let the filter temporarily have a high priority and rectify the
11944                        // priorities after all system packages have been scanned.
11945                        mProtectedFilters.add(intent);
11946                        if (DEBUG_FILTERS) {
11947                            Slog.i(TAG, "Protected action; save for later;"
11948                                    + " package: " + applicationInfo.packageName
11949                                    + " activity: " + intent.activity.className
11950                                    + " origPrio: " + intent.getPriority());
11951                        }
11952                        return;
11953                    } else {
11954                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11955                            Slog.i(TAG, "No setup wizard;"
11956                                + " All protected intents capped to priority 0");
11957                        }
11958                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11959                            if (DEBUG_FILTERS) {
11960                                Slog.i(TAG, "Found setup wizard;"
11961                                    + " allow priority " + intent.getPriority() + ";"
11962                                    + " package: " + intent.activity.info.packageName
11963                                    + " activity: " + intent.activity.className
11964                                    + " priority: " + intent.getPriority());
11965                            }
11966                            // setup wizard gets whatever it wants
11967                            return;
11968                        }
11969                        Slog.w(TAG, "Protected action; cap priority to 0;"
11970                                + " package: " + intent.activity.info.packageName
11971                                + " activity: " + intent.activity.className
11972                                + " origPrio: " + intent.getPriority());
11973                        intent.setPriority(0);
11974                        return;
11975                    }
11976                }
11977                // privileged apps on the system image get whatever priority they request
11978                return;
11979            }
11980
11981            // privileged app unbundled update ... try to find the same activity
11982            final PackageParser.Activity foundActivity =
11983                    findMatchingActivity(systemActivities, activityInfo);
11984            if (foundActivity == null) {
11985                // this is a new activity; it cannot obtain >0 priority
11986                if (DEBUG_FILTERS) {
11987                    Slog.i(TAG, "New activity; cap priority to 0;"
11988                            + " package: " + applicationInfo.packageName
11989                            + " activity: " + intent.activity.className
11990                            + " origPrio: " + intent.getPriority());
11991                }
11992                intent.setPriority(0);
11993                return;
11994            }
11995
11996            // found activity, now check for filter equivalence
11997
11998            // a shallow copy is enough; we modify the list, not its contents
11999            final List<ActivityIntentInfo> intentListCopy =
12000                    new ArrayList<>(foundActivity.intents);
12001            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12002
12003            // find matching action subsets
12004            final Iterator<String> actionsIterator = intent.actionsIterator();
12005            if (actionsIterator != null) {
12006                getIntentListSubset(
12007                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12008                if (intentListCopy.size() == 0) {
12009                    // no more intents to match; we're not equivalent
12010                    if (DEBUG_FILTERS) {
12011                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12012                                + " package: " + applicationInfo.packageName
12013                                + " activity: " + intent.activity.className
12014                                + " origPrio: " + intent.getPriority());
12015                    }
12016                    intent.setPriority(0);
12017                    return;
12018                }
12019            }
12020
12021            // find matching category subsets
12022            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12023            if (categoriesIterator != null) {
12024                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12025                        categoriesIterator);
12026                if (intentListCopy.size() == 0) {
12027                    // no more intents to match; we're not equivalent
12028                    if (DEBUG_FILTERS) {
12029                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12030                                + " package: " + applicationInfo.packageName
12031                                + " activity: " + intent.activity.className
12032                                + " origPrio: " + intent.getPriority());
12033                    }
12034                    intent.setPriority(0);
12035                    return;
12036                }
12037            }
12038
12039            // find matching schemes subsets
12040            final Iterator<String> schemesIterator = intent.schemesIterator();
12041            if (schemesIterator != null) {
12042                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12043                        schemesIterator);
12044                if (intentListCopy.size() == 0) {
12045                    // no more intents to match; we're not equivalent
12046                    if (DEBUG_FILTERS) {
12047                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12048                                + " package: " + applicationInfo.packageName
12049                                + " activity: " + intent.activity.className
12050                                + " origPrio: " + intent.getPriority());
12051                    }
12052                    intent.setPriority(0);
12053                    return;
12054                }
12055            }
12056
12057            // find matching authorities subsets
12058            final Iterator<IntentFilter.AuthorityEntry>
12059                    authoritiesIterator = intent.authoritiesIterator();
12060            if (authoritiesIterator != null) {
12061                getIntentListSubset(intentListCopy,
12062                        new AuthoritiesIterGenerator(),
12063                        authoritiesIterator);
12064                if (intentListCopy.size() == 0) {
12065                    // no more intents to match; we're not equivalent
12066                    if (DEBUG_FILTERS) {
12067                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12068                                + " package: " + applicationInfo.packageName
12069                                + " activity: " + intent.activity.className
12070                                + " origPrio: " + intent.getPriority());
12071                    }
12072                    intent.setPriority(0);
12073                    return;
12074                }
12075            }
12076
12077            // we found matching filter(s); app gets the max priority of all intents
12078            int cappedPriority = 0;
12079            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12080                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12081            }
12082            if (intent.getPriority() > cappedPriority) {
12083                if (DEBUG_FILTERS) {
12084                    Slog.i(TAG, "Found matching filter(s);"
12085                            + " cap priority to " + cappedPriority + ";"
12086                            + " package: " + applicationInfo.packageName
12087                            + " activity: " + intent.activity.className
12088                            + " origPrio: " + intent.getPriority());
12089                }
12090                intent.setPriority(cappedPriority);
12091                return;
12092            }
12093            // all this for nothing; the requested priority was <= what was on the system
12094        }
12095
12096        public final void addActivity(PackageParser.Activity a, String type) {
12097            mActivities.put(a.getComponentName(), a);
12098            if (DEBUG_SHOW_INFO)
12099                Log.v(
12100                TAG, "  " + type + " " +
12101                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12102            if (DEBUG_SHOW_INFO)
12103                Log.v(TAG, "    Class=" + a.info.name);
12104            final int NI = a.intents.size();
12105            for (int j=0; j<NI; j++) {
12106                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12107                if ("activity".equals(type)) {
12108                    final PackageSetting ps =
12109                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12110                    final List<PackageParser.Activity> systemActivities =
12111                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12112                    adjustPriority(systemActivities, intent);
12113                }
12114                if (DEBUG_SHOW_INFO) {
12115                    Log.v(TAG, "    IntentFilter:");
12116                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12117                }
12118                if (!intent.debugCheck()) {
12119                    Log.w(TAG, "==> For Activity " + a.info.name);
12120                }
12121                addFilter(intent);
12122            }
12123        }
12124
12125        public final void removeActivity(PackageParser.Activity a, String type) {
12126            mActivities.remove(a.getComponentName());
12127            if (DEBUG_SHOW_INFO) {
12128                Log.v(TAG, "  " + type + " "
12129                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12130                                : a.info.name) + ":");
12131                Log.v(TAG, "    Class=" + a.info.name);
12132            }
12133            final int NI = a.intents.size();
12134            for (int j=0; j<NI; j++) {
12135                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12136                if (DEBUG_SHOW_INFO) {
12137                    Log.v(TAG, "    IntentFilter:");
12138                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12139                }
12140                removeFilter(intent);
12141            }
12142        }
12143
12144        @Override
12145        protected boolean allowFilterResult(
12146                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12147            ActivityInfo filterAi = filter.activity.info;
12148            for (int i=dest.size()-1; i>=0; i--) {
12149                ActivityInfo destAi = dest.get(i).activityInfo;
12150                if (destAi.name == filterAi.name
12151                        && destAi.packageName == filterAi.packageName) {
12152                    return false;
12153                }
12154            }
12155            return true;
12156        }
12157
12158        @Override
12159        protected ActivityIntentInfo[] newArray(int size) {
12160            return new ActivityIntentInfo[size];
12161        }
12162
12163        @Override
12164        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12165            if (!sUserManager.exists(userId)) return true;
12166            PackageParser.Package p = filter.activity.owner;
12167            if (p != null) {
12168                PackageSetting ps = (PackageSetting)p.mExtras;
12169                if (ps != null) {
12170                    // System apps are never considered stopped for purposes of
12171                    // filtering, because there may be no way for the user to
12172                    // actually re-launch them.
12173                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12174                            && ps.getStopped(userId);
12175                }
12176            }
12177            return false;
12178        }
12179
12180        @Override
12181        protected boolean isPackageForFilter(String packageName,
12182                PackageParser.ActivityIntentInfo info) {
12183            return packageName.equals(info.activity.owner.packageName);
12184        }
12185
12186        @Override
12187        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12188                int match, int userId) {
12189            if (!sUserManager.exists(userId)) return null;
12190            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12191                return null;
12192            }
12193            final PackageParser.Activity activity = info.activity;
12194            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12195            if (ps == null) {
12196                return null;
12197            }
12198            final PackageUserState userState = ps.readUserState(userId);
12199            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12200                    userState, userId);
12201            if (ai == null) {
12202                return null;
12203            }
12204            final boolean matchVisibleToInstantApp =
12205                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12206            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12207            // throw out filters that aren't visible to ephemeral apps
12208            if (matchVisibleToInstantApp
12209                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12210                return null;
12211            }
12212            // throw out ephemeral filters if we're not explicitly requesting them
12213            if (!isInstantApp && userState.instantApp) {
12214                return null;
12215            }
12216            final ResolveInfo res = new ResolveInfo();
12217            res.activityInfo = ai;
12218            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12219                res.filter = info;
12220            }
12221            if (info != null) {
12222                res.handleAllWebDataURI = info.handleAllWebDataURI();
12223            }
12224            res.priority = info.getPriority();
12225            res.preferredOrder = activity.owner.mPreferredOrder;
12226            //System.out.println("Result: " + res.activityInfo.className +
12227            //                   " = " + res.priority);
12228            res.match = match;
12229            res.isDefault = info.hasDefault;
12230            res.labelRes = info.labelRes;
12231            res.nonLocalizedLabel = info.nonLocalizedLabel;
12232            if (userNeedsBadging(userId)) {
12233                res.noResourceId = true;
12234            } else {
12235                res.icon = info.icon;
12236            }
12237            res.iconResourceId = info.icon;
12238            res.system = res.activityInfo.applicationInfo.isSystemApp();
12239            return res;
12240        }
12241
12242        @Override
12243        protected void sortResults(List<ResolveInfo> results) {
12244            Collections.sort(results, mResolvePrioritySorter);
12245        }
12246
12247        @Override
12248        protected void dumpFilter(PrintWriter out, String prefix,
12249                PackageParser.ActivityIntentInfo filter) {
12250            out.print(prefix); out.print(
12251                    Integer.toHexString(System.identityHashCode(filter.activity)));
12252                    out.print(' ');
12253                    filter.activity.printComponentShortName(out);
12254                    out.print(" filter ");
12255                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12256        }
12257
12258        @Override
12259        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12260            return filter.activity;
12261        }
12262
12263        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12264            PackageParser.Activity activity = (PackageParser.Activity)label;
12265            out.print(prefix); out.print(
12266                    Integer.toHexString(System.identityHashCode(activity)));
12267                    out.print(' ');
12268                    activity.printComponentShortName(out);
12269            if (count > 1) {
12270                out.print(" ("); out.print(count); out.print(" filters)");
12271            }
12272            out.println();
12273        }
12274
12275        // Keys are String (activity class name), values are Activity.
12276        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12277                = new ArrayMap<ComponentName, PackageParser.Activity>();
12278        private int mFlags;
12279    }
12280
12281    private final class ServiceIntentResolver
12282            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12283        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12284                boolean defaultOnly, int userId) {
12285            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12286            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12287        }
12288
12289        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12290                int userId) {
12291            if (!sUserManager.exists(userId)) return null;
12292            mFlags = flags;
12293            return super.queryIntent(intent, resolvedType,
12294                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12295                    userId);
12296        }
12297
12298        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12299                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12300            if (!sUserManager.exists(userId)) return null;
12301            if (packageServices == null) {
12302                return null;
12303            }
12304            mFlags = flags;
12305            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12306            final int N = packageServices.size();
12307            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12308                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12309
12310            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12311            for (int i = 0; i < N; ++i) {
12312                intentFilters = packageServices.get(i).intents;
12313                if (intentFilters != null && intentFilters.size() > 0) {
12314                    PackageParser.ServiceIntentInfo[] array =
12315                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12316                    intentFilters.toArray(array);
12317                    listCut.add(array);
12318                }
12319            }
12320            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12321        }
12322
12323        public final void addService(PackageParser.Service s) {
12324            mServices.put(s.getComponentName(), s);
12325            if (DEBUG_SHOW_INFO) {
12326                Log.v(TAG, "  "
12327                        + (s.info.nonLocalizedLabel != null
12328                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12329                Log.v(TAG, "    Class=" + s.info.name);
12330            }
12331            final int NI = s.intents.size();
12332            int j;
12333            for (j=0; j<NI; j++) {
12334                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12335                if (DEBUG_SHOW_INFO) {
12336                    Log.v(TAG, "    IntentFilter:");
12337                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12338                }
12339                if (!intent.debugCheck()) {
12340                    Log.w(TAG, "==> For Service " + s.info.name);
12341                }
12342                addFilter(intent);
12343            }
12344        }
12345
12346        public final void removeService(PackageParser.Service s) {
12347            mServices.remove(s.getComponentName());
12348            if (DEBUG_SHOW_INFO) {
12349                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12350                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12351                Log.v(TAG, "    Class=" + s.info.name);
12352            }
12353            final int NI = s.intents.size();
12354            int j;
12355            for (j=0; j<NI; j++) {
12356                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12357                if (DEBUG_SHOW_INFO) {
12358                    Log.v(TAG, "    IntentFilter:");
12359                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12360                }
12361                removeFilter(intent);
12362            }
12363        }
12364
12365        @Override
12366        protected boolean allowFilterResult(
12367                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12368            ServiceInfo filterSi = filter.service.info;
12369            for (int i=dest.size()-1; i>=0; i--) {
12370                ServiceInfo destAi = dest.get(i).serviceInfo;
12371                if (destAi.name == filterSi.name
12372                        && destAi.packageName == filterSi.packageName) {
12373                    return false;
12374                }
12375            }
12376            return true;
12377        }
12378
12379        @Override
12380        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12381            return new PackageParser.ServiceIntentInfo[size];
12382        }
12383
12384        @Override
12385        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12386            if (!sUserManager.exists(userId)) return true;
12387            PackageParser.Package p = filter.service.owner;
12388            if (p != null) {
12389                PackageSetting ps = (PackageSetting)p.mExtras;
12390                if (ps != null) {
12391                    // System apps are never considered stopped for purposes of
12392                    // filtering, because there may be no way for the user to
12393                    // actually re-launch them.
12394                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12395                            && ps.getStopped(userId);
12396                }
12397            }
12398            return false;
12399        }
12400
12401        @Override
12402        protected boolean isPackageForFilter(String packageName,
12403                PackageParser.ServiceIntentInfo info) {
12404            return packageName.equals(info.service.owner.packageName);
12405        }
12406
12407        @Override
12408        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12409                int match, int userId) {
12410            if (!sUserManager.exists(userId)) return null;
12411            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12412            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12413                return null;
12414            }
12415            final PackageParser.Service service = info.service;
12416            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12417            if (ps == null) {
12418                return null;
12419            }
12420            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12421                    ps.readUserState(userId), userId);
12422            if (si == null) {
12423                return null;
12424            }
12425            final ResolveInfo res = new ResolveInfo();
12426            res.serviceInfo = si;
12427            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12428                res.filter = filter;
12429            }
12430            res.priority = info.getPriority();
12431            res.preferredOrder = service.owner.mPreferredOrder;
12432            res.match = match;
12433            res.isDefault = info.hasDefault;
12434            res.labelRes = info.labelRes;
12435            res.nonLocalizedLabel = info.nonLocalizedLabel;
12436            res.icon = info.icon;
12437            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12438            return res;
12439        }
12440
12441        @Override
12442        protected void sortResults(List<ResolveInfo> results) {
12443            Collections.sort(results, mResolvePrioritySorter);
12444        }
12445
12446        @Override
12447        protected void dumpFilter(PrintWriter out, String prefix,
12448                PackageParser.ServiceIntentInfo filter) {
12449            out.print(prefix); out.print(
12450                    Integer.toHexString(System.identityHashCode(filter.service)));
12451                    out.print(' ');
12452                    filter.service.printComponentShortName(out);
12453                    out.print(" filter ");
12454                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12455        }
12456
12457        @Override
12458        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12459            return filter.service;
12460        }
12461
12462        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12463            PackageParser.Service service = (PackageParser.Service)label;
12464            out.print(prefix); out.print(
12465                    Integer.toHexString(System.identityHashCode(service)));
12466                    out.print(' ');
12467                    service.printComponentShortName(out);
12468            if (count > 1) {
12469                out.print(" ("); out.print(count); out.print(" filters)");
12470            }
12471            out.println();
12472        }
12473
12474//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12475//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12476//            final List<ResolveInfo> retList = Lists.newArrayList();
12477//            while (i.hasNext()) {
12478//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12479//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12480//                    retList.add(resolveInfo);
12481//                }
12482//            }
12483//            return retList;
12484//        }
12485
12486        // Keys are String (activity class name), values are Activity.
12487        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12488                = new ArrayMap<ComponentName, PackageParser.Service>();
12489        private int mFlags;
12490    }
12491
12492    private final class ProviderIntentResolver
12493            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12494        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12495                boolean defaultOnly, int userId) {
12496            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12497            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12498        }
12499
12500        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12501                int userId) {
12502            if (!sUserManager.exists(userId))
12503                return null;
12504            mFlags = flags;
12505            return super.queryIntent(intent, resolvedType,
12506                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12507                    userId);
12508        }
12509
12510        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12511                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12512            if (!sUserManager.exists(userId))
12513                return null;
12514            if (packageProviders == null) {
12515                return null;
12516            }
12517            mFlags = flags;
12518            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12519            final int N = packageProviders.size();
12520            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12521                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12522
12523            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12524            for (int i = 0; i < N; ++i) {
12525                intentFilters = packageProviders.get(i).intents;
12526                if (intentFilters != null && intentFilters.size() > 0) {
12527                    PackageParser.ProviderIntentInfo[] array =
12528                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12529                    intentFilters.toArray(array);
12530                    listCut.add(array);
12531                }
12532            }
12533            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12534        }
12535
12536        public final void addProvider(PackageParser.Provider p) {
12537            if (mProviders.containsKey(p.getComponentName())) {
12538                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12539                return;
12540            }
12541
12542            mProviders.put(p.getComponentName(), p);
12543            if (DEBUG_SHOW_INFO) {
12544                Log.v(TAG, "  "
12545                        + (p.info.nonLocalizedLabel != null
12546                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12547                Log.v(TAG, "    Class=" + p.info.name);
12548            }
12549            final int NI = p.intents.size();
12550            int j;
12551            for (j = 0; j < NI; j++) {
12552                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12553                if (DEBUG_SHOW_INFO) {
12554                    Log.v(TAG, "    IntentFilter:");
12555                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12556                }
12557                if (!intent.debugCheck()) {
12558                    Log.w(TAG, "==> For Provider " + p.info.name);
12559                }
12560                addFilter(intent);
12561            }
12562        }
12563
12564        public final void removeProvider(PackageParser.Provider p) {
12565            mProviders.remove(p.getComponentName());
12566            if (DEBUG_SHOW_INFO) {
12567                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12568                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12569                Log.v(TAG, "    Class=" + p.info.name);
12570            }
12571            final int NI = p.intents.size();
12572            int j;
12573            for (j = 0; j < NI; j++) {
12574                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12575                if (DEBUG_SHOW_INFO) {
12576                    Log.v(TAG, "    IntentFilter:");
12577                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12578                }
12579                removeFilter(intent);
12580            }
12581        }
12582
12583        @Override
12584        protected boolean allowFilterResult(
12585                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12586            ProviderInfo filterPi = filter.provider.info;
12587            for (int i = dest.size() - 1; i >= 0; i--) {
12588                ProviderInfo destPi = dest.get(i).providerInfo;
12589                if (destPi.name == filterPi.name
12590                        && destPi.packageName == filterPi.packageName) {
12591                    return false;
12592                }
12593            }
12594            return true;
12595        }
12596
12597        @Override
12598        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12599            return new PackageParser.ProviderIntentInfo[size];
12600        }
12601
12602        @Override
12603        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12604            if (!sUserManager.exists(userId))
12605                return true;
12606            PackageParser.Package p = filter.provider.owner;
12607            if (p != null) {
12608                PackageSetting ps = (PackageSetting) p.mExtras;
12609                if (ps != null) {
12610                    // System apps are never considered stopped for purposes of
12611                    // filtering, because there may be no way for the user to
12612                    // actually re-launch them.
12613                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12614                            && ps.getStopped(userId);
12615                }
12616            }
12617            return false;
12618        }
12619
12620        @Override
12621        protected boolean isPackageForFilter(String packageName,
12622                PackageParser.ProviderIntentInfo info) {
12623            return packageName.equals(info.provider.owner.packageName);
12624        }
12625
12626        @Override
12627        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12628                int match, int userId) {
12629            if (!sUserManager.exists(userId))
12630                return null;
12631            final PackageParser.ProviderIntentInfo info = filter;
12632            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12633                return null;
12634            }
12635            final PackageParser.Provider provider = info.provider;
12636            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12637            if (ps == null) {
12638                return null;
12639            }
12640            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12641                    ps.readUserState(userId), userId);
12642            if (pi == null) {
12643                return null;
12644            }
12645            final ResolveInfo res = new ResolveInfo();
12646            res.providerInfo = pi;
12647            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12648                res.filter = filter;
12649            }
12650            res.priority = info.getPriority();
12651            res.preferredOrder = provider.owner.mPreferredOrder;
12652            res.match = match;
12653            res.isDefault = info.hasDefault;
12654            res.labelRes = info.labelRes;
12655            res.nonLocalizedLabel = info.nonLocalizedLabel;
12656            res.icon = info.icon;
12657            res.system = res.providerInfo.applicationInfo.isSystemApp();
12658            return res;
12659        }
12660
12661        @Override
12662        protected void sortResults(List<ResolveInfo> results) {
12663            Collections.sort(results, mResolvePrioritySorter);
12664        }
12665
12666        @Override
12667        protected void dumpFilter(PrintWriter out, String prefix,
12668                PackageParser.ProviderIntentInfo filter) {
12669            out.print(prefix);
12670            out.print(
12671                    Integer.toHexString(System.identityHashCode(filter.provider)));
12672            out.print(' ');
12673            filter.provider.printComponentShortName(out);
12674            out.print(" filter ");
12675            out.println(Integer.toHexString(System.identityHashCode(filter)));
12676        }
12677
12678        @Override
12679        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12680            return filter.provider;
12681        }
12682
12683        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12684            PackageParser.Provider provider = (PackageParser.Provider)label;
12685            out.print(prefix); out.print(
12686                    Integer.toHexString(System.identityHashCode(provider)));
12687                    out.print(' ');
12688                    provider.printComponentShortName(out);
12689            if (count > 1) {
12690                out.print(" ("); out.print(count); out.print(" filters)");
12691            }
12692            out.println();
12693        }
12694
12695        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12696                = new ArrayMap<ComponentName, PackageParser.Provider>();
12697        private int mFlags;
12698    }
12699
12700    static final class EphemeralIntentResolver
12701            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12702        /**
12703         * The result that has the highest defined order. Ordering applies on a
12704         * per-package basis. Mapping is from package name to Pair of order and
12705         * EphemeralResolveInfo.
12706         * <p>
12707         * NOTE: This is implemented as a field variable for convenience and efficiency.
12708         * By having a field variable, we're able to track filter ordering as soon as
12709         * a non-zero order is defined. Otherwise, multiple loops across the result set
12710         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12711         * this needs to be contained entirely within {@link #filterResults()}.
12712         */
12713        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12714
12715        @Override
12716        protected EphemeralResponse[] newArray(int size) {
12717            return new EphemeralResponse[size];
12718        }
12719
12720        @Override
12721        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12722            return true;
12723        }
12724
12725        @Override
12726        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12727                int userId) {
12728            if (!sUserManager.exists(userId)) {
12729                return null;
12730            }
12731            final String packageName = responseObj.resolveInfo.getPackageName();
12732            final Integer order = responseObj.getOrder();
12733            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12734                    mOrderResult.get(packageName);
12735            // ordering is enabled and this item's order isn't high enough
12736            if (lastOrderResult != null && lastOrderResult.first >= order) {
12737                return null;
12738            }
12739            final EphemeralResolveInfo res = responseObj.resolveInfo;
12740            if (order > 0) {
12741                // non-zero order, enable ordering
12742                mOrderResult.put(packageName, new Pair<>(order, res));
12743            }
12744            return responseObj;
12745        }
12746
12747        @Override
12748        protected void filterResults(List<EphemeralResponse> results) {
12749            // only do work if ordering is enabled [most of the time it won't be]
12750            if (mOrderResult.size() == 0) {
12751                return;
12752            }
12753            int resultSize = results.size();
12754            for (int i = 0; i < resultSize; i++) {
12755                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12756                final String packageName = info.getPackageName();
12757                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12758                if (savedInfo == null) {
12759                    // package doesn't having ordering
12760                    continue;
12761                }
12762                if (savedInfo.second == info) {
12763                    // circled back to the highest ordered item; remove from order list
12764                    mOrderResult.remove(savedInfo);
12765                    if (mOrderResult.size() == 0) {
12766                        // no more ordered items
12767                        break;
12768                    }
12769                    continue;
12770                }
12771                // item has a worse order, remove it from the result list
12772                results.remove(i);
12773                resultSize--;
12774                i--;
12775            }
12776        }
12777    }
12778
12779    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12780            new Comparator<ResolveInfo>() {
12781        public int compare(ResolveInfo r1, ResolveInfo r2) {
12782            int v1 = r1.priority;
12783            int v2 = r2.priority;
12784            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12785            if (v1 != v2) {
12786                return (v1 > v2) ? -1 : 1;
12787            }
12788            v1 = r1.preferredOrder;
12789            v2 = r2.preferredOrder;
12790            if (v1 != v2) {
12791                return (v1 > v2) ? -1 : 1;
12792            }
12793            if (r1.isDefault != r2.isDefault) {
12794                return r1.isDefault ? -1 : 1;
12795            }
12796            v1 = r1.match;
12797            v2 = r2.match;
12798            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12799            if (v1 != v2) {
12800                return (v1 > v2) ? -1 : 1;
12801            }
12802            if (r1.system != r2.system) {
12803                return r1.system ? -1 : 1;
12804            }
12805            if (r1.activityInfo != null) {
12806                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12807            }
12808            if (r1.serviceInfo != null) {
12809                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12810            }
12811            if (r1.providerInfo != null) {
12812                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12813            }
12814            return 0;
12815        }
12816    };
12817
12818    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12819            new Comparator<ProviderInfo>() {
12820        public int compare(ProviderInfo p1, ProviderInfo p2) {
12821            final int v1 = p1.initOrder;
12822            final int v2 = p2.initOrder;
12823            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12824        }
12825    };
12826
12827    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12828            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12829            final int[] userIds) {
12830        mHandler.post(new Runnable() {
12831            @Override
12832            public void run() {
12833                try {
12834                    final IActivityManager am = ActivityManager.getService();
12835                    if (am == null) return;
12836                    final int[] resolvedUserIds;
12837                    if (userIds == null) {
12838                        resolvedUserIds = am.getRunningUserIds();
12839                    } else {
12840                        resolvedUserIds = userIds;
12841                    }
12842                    for (int id : resolvedUserIds) {
12843                        final Intent intent = new Intent(action,
12844                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12845                        if (extras != null) {
12846                            intent.putExtras(extras);
12847                        }
12848                        if (targetPkg != null) {
12849                            intent.setPackage(targetPkg);
12850                        }
12851                        // Modify the UID when posting to other users
12852                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12853                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12854                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12855                            intent.putExtra(Intent.EXTRA_UID, uid);
12856                        }
12857                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12858                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12859                        if (DEBUG_BROADCASTS) {
12860                            RuntimeException here = new RuntimeException("here");
12861                            here.fillInStackTrace();
12862                            Slog.d(TAG, "Sending to user " + id + ": "
12863                                    + intent.toShortString(false, true, false, false)
12864                                    + " " + intent.getExtras(), here);
12865                        }
12866                        am.broadcastIntent(null, intent, null, finishedReceiver,
12867                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12868                                null, finishedReceiver != null, false, id);
12869                    }
12870                } catch (RemoteException ex) {
12871                }
12872            }
12873        });
12874    }
12875
12876    /**
12877     * Check if the external storage media is available. This is true if there
12878     * is a mounted external storage medium or if the external storage is
12879     * emulated.
12880     */
12881    private boolean isExternalMediaAvailable() {
12882        return mMediaMounted || Environment.isExternalStorageEmulated();
12883    }
12884
12885    @Override
12886    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12887        // writer
12888        synchronized (mPackages) {
12889            if (!isExternalMediaAvailable()) {
12890                // If the external storage is no longer mounted at this point,
12891                // the caller may not have been able to delete all of this
12892                // packages files and can not delete any more.  Bail.
12893                return null;
12894            }
12895            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12896            if (lastPackage != null) {
12897                pkgs.remove(lastPackage);
12898            }
12899            if (pkgs.size() > 0) {
12900                return pkgs.get(0);
12901            }
12902        }
12903        return null;
12904    }
12905
12906    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12907        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12908                userId, andCode ? 1 : 0, packageName);
12909        if (mSystemReady) {
12910            msg.sendToTarget();
12911        } else {
12912            if (mPostSystemReadyMessages == null) {
12913                mPostSystemReadyMessages = new ArrayList<>();
12914            }
12915            mPostSystemReadyMessages.add(msg);
12916        }
12917    }
12918
12919    void startCleaningPackages() {
12920        // reader
12921        if (!isExternalMediaAvailable()) {
12922            return;
12923        }
12924        synchronized (mPackages) {
12925            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12926                return;
12927            }
12928        }
12929        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12930        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12931        IActivityManager am = ActivityManager.getService();
12932        if (am != null) {
12933            try {
12934                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12935                        UserHandle.USER_SYSTEM);
12936            } catch (RemoteException e) {
12937            }
12938        }
12939    }
12940
12941    @Override
12942    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12943            int installFlags, String installerPackageName, int userId) {
12944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12945
12946        final int callingUid = Binder.getCallingUid();
12947        enforceCrossUserPermission(callingUid, userId,
12948                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12949
12950        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12951            try {
12952                if (observer != null) {
12953                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12954                }
12955            } catch (RemoteException re) {
12956            }
12957            return;
12958        }
12959
12960        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12961            installFlags |= PackageManager.INSTALL_FROM_ADB;
12962
12963        } else {
12964            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12965            // about installerPackageName.
12966
12967            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12968            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12969        }
12970
12971        UserHandle user;
12972        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12973            user = UserHandle.ALL;
12974        } else {
12975            user = new UserHandle(userId);
12976        }
12977
12978        // Only system components can circumvent runtime permissions when installing.
12979        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12980                && mContext.checkCallingOrSelfPermission(Manifest.permission
12981                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12982            throw new SecurityException("You need the "
12983                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12984                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12985        }
12986
12987        final File originFile = new File(originPath);
12988        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12989
12990        final Message msg = mHandler.obtainMessage(INIT_COPY);
12991        final VerificationInfo verificationInfo = new VerificationInfo(
12992                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12993        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12994                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12995                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12996                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12997        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12998        msg.obj = params;
12999
13000        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13001                System.identityHashCode(msg.obj));
13002        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13003                System.identityHashCode(msg.obj));
13004
13005        mHandler.sendMessage(msg);
13006    }
13007
13008
13009    /**
13010     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13011     * it is acting on behalf on an enterprise or the user).
13012     *
13013     * Note that the ordering of the conditionals in this method is important. The checks we perform
13014     * are as follows, in this order:
13015     *
13016     * 1) If the install is being performed by a system app, we can trust the app to have set the
13017     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13018     *    what it is.
13019     * 2) If the install is being performed by a device or profile owner app, the install reason
13020     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13021     *    set the install reason correctly. If the app targets an older SDK version where install
13022     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13023     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13024     * 3) In all other cases, the install is being performed by a regular app that is neither part
13025     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13026     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13027     *    set to enterprise policy and if so, change it to unknown instead.
13028     */
13029    private int fixUpInstallReason(String installerPackageName, int installerUid,
13030            int installReason) {
13031        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13032                == PERMISSION_GRANTED) {
13033            // If the install is being performed by a system app, we trust that app to have set the
13034            // install reason correctly.
13035            return installReason;
13036        }
13037
13038        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13039            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13040        if (dpm != null) {
13041            ComponentName owner = null;
13042            try {
13043                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13044                if (owner == null) {
13045                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13046                }
13047            } catch (RemoteException e) {
13048            }
13049            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13050                // If the install is being performed by a device or profile owner, the install
13051                // reason should be enterprise policy.
13052                return PackageManager.INSTALL_REASON_POLICY;
13053            }
13054        }
13055
13056        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13057            // If the install is being performed by a regular app (i.e. neither system app nor
13058            // device or profile owner), we have no reason to believe that the app is acting on
13059            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13060            // change it to unknown instead.
13061            return PackageManager.INSTALL_REASON_UNKNOWN;
13062        }
13063
13064        // If the install is being performed by a regular app and the install reason was set to any
13065        // value but enterprise policy, leave the install reason unchanged.
13066        return installReason;
13067    }
13068
13069    void installStage(String packageName, File stagedDir, String stagedCid,
13070            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13071            String installerPackageName, int installerUid, UserHandle user,
13072            Certificate[][] certificates) {
13073        if (DEBUG_EPHEMERAL) {
13074            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13075                Slog.d(TAG, "Ephemeral install of " + packageName);
13076            }
13077        }
13078        final VerificationInfo verificationInfo = new VerificationInfo(
13079                sessionParams.originatingUri, sessionParams.referrerUri,
13080                sessionParams.originatingUid, installerUid);
13081
13082        final OriginInfo origin;
13083        if (stagedDir != null) {
13084            origin = OriginInfo.fromStagedFile(stagedDir);
13085        } else {
13086            origin = OriginInfo.fromStagedContainer(stagedCid);
13087        }
13088
13089        final Message msg = mHandler.obtainMessage(INIT_COPY);
13090        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13091                sessionParams.installReason);
13092        final InstallParams params = new InstallParams(origin, null, observer,
13093                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13094                verificationInfo, user, sessionParams.abiOverride,
13095                sessionParams.grantedRuntimePermissions, certificates, installReason);
13096        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13097        msg.obj = params;
13098
13099        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13100                System.identityHashCode(msg.obj));
13101        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13102                System.identityHashCode(msg.obj));
13103
13104        mHandler.sendMessage(msg);
13105    }
13106
13107    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13108            int userId) {
13109        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13110        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13111    }
13112
13113    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13114            int appId, int... userIds) {
13115        if (ArrayUtils.isEmpty(userIds)) {
13116            return;
13117        }
13118        Bundle extras = new Bundle(1);
13119        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13120        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13121
13122        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13123                packageName, extras, 0, null, null, userIds);
13124        if (isSystem) {
13125            mHandler.post(() -> {
13126                        for (int userId : userIds) {
13127                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13128                        }
13129                    }
13130            );
13131        }
13132    }
13133
13134    /**
13135     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13136     * automatically without needing an explicit launch.
13137     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13138     */
13139    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13140        // If user is not running, the app didn't miss any broadcast
13141        if (!mUserManagerInternal.isUserRunning(userId)) {
13142            return;
13143        }
13144        final IActivityManager am = ActivityManager.getService();
13145        try {
13146            // Deliver LOCKED_BOOT_COMPLETED first
13147            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13148                    .setPackage(packageName);
13149            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13150            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13151                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13152
13153            // Deliver BOOT_COMPLETED only if user is unlocked
13154            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13155                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13156                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13157                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13158            }
13159        } catch (RemoteException e) {
13160            throw e.rethrowFromSystemServer();
13161        }
13162    }
13163
13164    @Override
13165    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13166            int userId) {
13167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13168        PackageSetting pkgSetting;
13169        final int uid = Binder.getCallingUid();
13170        enforceCrossUserPermission(uid, userId,
13171                true /* requireFullPermission */, true /* checkShell */,
13172                "setApplicationHiddenSetting for user " + userId);
13173
13174        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13175            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13176            return false;
13177        }
13178
13179        long callingId = Binder.clearCallingIdentity();
13180        try {
13181            boolean sendAdded = false;
13182            boolean sendRemoved = false;
13183            // writer
13184            synchronized (mPackages) {
13185                pkgSetting = mSettings.mPackages.get(packageName);
13186                if (pkgSetting == null) {
13187                    return false;
13188                }
13189                // Do not allow "android" is being disabled
13190                if ("android".equals(packageName)) {
13191                    Slog.w(TAG, "Cannot hide package: android");
13192                    return false;
13193                }
13194                // Cannot hide static shared libs as they are considered
13195                // a part of the using app (emulating static linking). Also
13196                // static libs are installed always on internal storage.
13197                PackageParser.Package pkg = mPackages.get(packageName);
13198                if (pkg != null && pkg.staticSharedLibName != null) {
13199                    Slog.w(TAG, "Cannot hide package: " + packageName
13200                            + " providing static shared library: "
13201                            + pkg.staticSharedLibName);
13202                    return false;
13203                }
13204                // Only allow protected packages to hide themselves.
13205                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13206                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13207                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13208                    return false;
13209                }
13210
13211                if (pkgSetting.getHidden(userId) != hidden) {
13212                    pkgSetting.setHidden(hidden, userId);
13213                    mSettings.writePackageRestrictionsLPr(userId);
13214                    if (hidden) {
13215                        sendRemoved = true;
13216                    } else {
13217                        sendAdded = true;
13218                    }
13219                }
13220            }
13221            if (sendAdded) {
13222                sendPackageAddedForUser(packageName, pkgSetting, userId);
13223                return true;
13224            }
13225            if (sendRemoved) {
13226                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13227                        "hiding pkg");
13228                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13229                return true;
13230            }
13231        } finally {
13232            Binder.restoreCallingIdentity(callingId);
13233        }
13234        return false;
13235    }
13236
13237    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13238            int userId) {
13239        final PackageRemovedInfo info = new PackageRemovedInfo();
13240        info.removedPackage = packageName;
13241        info.removedUsers = new int[] {userId};
13242        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13243        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13244    }
13245
13246    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13247        if (pkgList.length > 0) {
13248            Bundle extras = new Bundle(1);
13249            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13250
13251            sendPackageBroadcast(
13252                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13253                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13254                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13255                    new int[] {userId});
13256        }
13257    }
13258
13259    /**
13260     * Returns true if application is not found or there was an error. Otherwise it returns
13261     * the hidden state of the package for the given user.
13262     */
13263    @Override
13264    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13265        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13267                true /* requireFullPermission */, false /* checkShell */,
13268                "getApplicationHidden for user " + userId);
13269        PackageSetting pkgSetting;
13270        long callingId = Binder.clearCallingIdentity();
13271        try {
13272            // writer
13273            synchronized (mPackages) {
13274                pkgSetting = mSettings.mPackages.get(packageName);
13275                if (pkgSetting == null) {
13276                    return true;
13277                }
13278                return pkgSetting.getHidden(userId);
13279            }
13280        } finally {
13281            Binder.restoreCallingIdentity(callingId);
13282        }
13283    }
13284
13285    /**
13286     * @hide
13287     */
13288    @Override
13289    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13290            int installReason) {
13291        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13292                null);
13293        PackageSetting pkgSetting;
13294        final int uid = Binder.getCallingUid();
13295        enforceCrossUserPermission(uid, userId,
13296                true /* requireFullPermission */, true /* checkShell */,
13297                "installExistingPackage for user " + userId);
13298        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13299            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13300        }
13301
13302        long callingId = Binder.clearCallingIdentity();
13303        try {
13304            boolean installed = false;
13305            final boolean instantApp =
13306                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13307            final boolean fullApp =
13308                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13309
13310            // writer
13311            synchronized (mPackages) {
13312                pkgSetting = mSettings.mPackages.get(packageName);
13313                if (pkgSetting == null) {
13314                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13315                }
13316                if (!pkgSetting.getInstalled(userId)) {
13317                    pkgSetting.setInstalled(true, userId);
13318                    pkgSetting.setHidden(false, userId);
13319                    pkgSetting.setInstallReason(installReason, userId);
13320                    mSettings.writePackageRestrictionsLPr(userId);
13321                    mSettings.writeKernelMappingLPr(pkgSetting);
13322                    installed = true;
13323                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13324                    // upgrade app from instant to full; we don't allow app downgrade
13325                    installed = true;
13326                }
13327                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13328            }
13329
13330            if (installed) {
13331                if (pkgSetting.pkg != null) {
13332                    synchronized (mInstallLock) {
13333                        // We don't need to freeze for a brand new install
13334                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13335                    }
13336                }
13337                sendPackageAddedForUser(packageName, pkgSetting, userId);
13338                synchronized (mPackages) {
13339                    updateSequenceNumberLP(packageName, new int[]{ userId });
13340                }
13341            }
13342        } finally {
13343            Binder.restoreCallingIdentity(callingId);
13344        }
13345
13346        return PackageManager.INSTALL_SUCCEEDED;
13347    }
13348
13349    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13350            boolean instantApp, boolean fullApp) {
13351        // no state specified; do nothing
13352        if (!instantApp && !fullApp) {
13353            return;
13354        }
13355        if (userId != UserHandle.USER_ALL) {
13356            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13357                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13358            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13359                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13360            }
13361        } else {
13362            for (int currentUserId : sUserManager.getUserIds()) {
13363                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13364                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13365                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13366                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13367                }
13368            }
13369        }
13370    }
13371
13372    boolean isUserRestricted(int userId, String restrictionKey) {
13373        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13374        if (restrictions.getBoolean(restrictionKey, false)) {
13375            Log.w(TAG, "User is restricted: " + restrictionKey);
13376            return true;
13377        }
13378        return false;
13379    }
13380
13381    @Override
13382    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13383            int userId) {
13384        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13386                true /* requireFullPermission */, true /* checkShell */,
13387                "setPackagesSuspended for user " + userId);
13388
13389        if (ArrayUtils.isEmpty(packageNames)) {
13390            return packageNames;
13391        }
13392
13393        // List of package names for whom the suspended state has changed.
13394        List<String> changedPackages = new ArrayList<>(packageNames.length);
13395        // List of package names for whom the suspended state is not set as requested in this
13396        // method.
13397        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13398        long callingId = Binder.clearCallingIdentity();
13399        try {
13400            for (int i = 0; i < packageNames.length; i++) {
13401                String packageName = packageNames[i];
13402                boolean changed = false;
13403                final int appId;
13404                synchronized (mPackages) {
13405                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13406                    if (pkgSetting == null) {
13407                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13408                                + "\". Skipping suspending/un-suspending.");
13409                        unactionedPackages.add(packageName);
13410                        continue;
13411                    }
13412                    appId = pkgSetting.appId;
13413                    if (pkgSetting.getSuspended(userId) != suspended) {
13414                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13415                            unactionedPackages.add(packageName);
13416                            continue;
13417                        }
13418                        pkgSetting.setSuspended(suspended, userId);
13419                        mSettings.writePackageRestrictionsLPr(userId);
13420                        changed = true;
13421                        changedPackages.add(packageName);
13422                    }
13423                }
13424
13425                if (changed && suspended) {
13426                    killApplication(packageName, UserHandle.getUid(userId, appId),
13427                            "suspending package");
13428                }
13429            }
13430        } finally {
13431            Binder.restoreCallingIdentity(callingId);
13432        }
13433
13434        if (!changedPackages.isEmpty()) {
13435            sendPackagesSuspendedForUser(changedPackages.toArray(
13436                    new String[changedPackages.size()]), userId, suspended);
13437        }
13438
13439        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13440    }
13441
13442    @Override
13443    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13445                true /* requireFullPermission */, false /* checkShell */,
13446                "isPackageSuspendedForUser for user " + userId);
13447        synchronized (mPackages) {
13448            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13449            if (pkgSetting == null) {
13450                throw new IllegalArgumentException("Unknown target package: " + packageName);
13451            }
13452            return pkgSetting.getSuspended(userId);
13453        }
13454    }
13455
13456    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13457        if (isPackageDeviceAdmin(packageName, userId)) {
13458            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13459                    + "\": has an active device admin");
13460            return false;
13461        }
13462
13463        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13464        if (packageName.equals(activeLauncherPackageName)) {
13465            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13466                    + "\": contains the active launcher");
13467            return false;
13468        }
13469
13470        if (packageName.equals(mRequiredInstallerPackage)) {
13471            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13472                    + "\": required for package installation");
13473            return false;
13474        }
13475
13476        if (packageName.equals(mRequiredUninstallerPackage)) {
13477            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13478                    + "\": required for package uninstallation");
13479            return false;
13480        }
13481
13482        if (packageName.equals(mRequiredVerifierPackage)) {
13483            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13484                    + "\": required for package verification");
13485            return false;
13486        }
13487
13488        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13489            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13490                    + "\": is the default dialer");
13491            return false;
13492        }
13493
13494        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13495            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13496                    + "\": protected package");
13497            return false;
13498        }
13499
13500        // Cannot suspend static shared libs as they are considered
13501        // a part of the using app (emulating static linking). Also
13502        // static libs are installed always on internal storage.
13503        PackageParser.Package pkg = mPackages.get(packageName);
13504        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13505            Slog.w(TAG, "Cannot suspend package: " + packageName
13506                    + " providing static shared library: "
13507                    + pkg.staticSharedLibName);
13508            return false;
13509        }
13510
13511        return true;
13512    }
13513
13514    private String getActiveLauncherPackageName(int userId) {
13515        Intent intent = new Intent(Intent.ACTION_MAIN);
13516        intent.addCategory(Intent.CATEGORY_HOME);
13517        ResolveInfo resolveInfo = resolveIntent(
13518                intent,
13519                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13520                PackageManager.MATCH_DEFAULT_ONLY,
13521                userId);
13522
13523        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13524    }
13525
13526    private String getDefaultDialerPackageName(int userId) {
13527        synchronized (mPackages) {
13528            return mSettings.getDefaultDialerPackageNameLPw(userId);
13529        }
13530    }
13531
13532    @Override
13533    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13534        mContext.enforceCallingOrSelfPermission(
13535                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13536                "Only package verification agents can verify applications");
13537
13538        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13539        final PackageVerificationResponse response = new PackageVerificationResponse(
13540                verificationCode, Binder.getCallingUid());
13541        msg.arg1 = id;
13542        msg.obj = response;
13543        mHandler.sendMessage(msg);
13544    }
13545
13546    @Override
13547    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13548            long millisecondsToDelay) {
13549        mContext.enforceCallingOrSelfPermission(
13550                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13551                "Only package verification agents can extend verification timeouts");
13552
13553        final PackageVerificationState state = mPendingVerification.get(id);
13554        final PackageVerificationResponse response = new PackageVerificationResponse(
13555                verificationCodeAtTimeout, Binder.getCallingUid());
13556
13557        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13558            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13559        }
13560        if (millisecondsToDelay < 0) {
13561            millisecondsToDelay = 0;
13562        }
13563        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13564                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13565            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13566        }
13567
13568        if ((state != null) && !state.timeoutExtended()) {
13569            state.extendTimeout();
13570
13571            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13572            msg.arg1 = id;
13573            msg.obj = response;
13574            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13575        }
13576    }
13577
13578    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13579            int verificationCode, UserHandle user) {
13580        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13581        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13582        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13583        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13584        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13585
13586        mContext.sendBroadcastAsUser(intent, user,
13587                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13588    }
13589
13590    private ComponentName matchComponentForVerifier(String packageName,
13591            List<ResolveInfo> receivers) {
13592        ActivityInfo targetReceiver = null;
13593
13594        final int NR = receivers.size();
13595        for (int i = 0; i < NR; i++) {
13596            final ResolveInfo info = receivers.get(i);
13597            if (info.activityInfo == null) {
13598                continue;
13599            }
13600
13601            if (packageName.equals(info.activityInfo.packageName)) {
13602                targetReceiver = info.activityInfo;
13603                break;
13604            }
13605        }
13606
13607        if (targetReceiver == null) {
13608            return null;
13609        }
13610
13611        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13612    }
13613
13614    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13615            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13616        if (pkgInfo.verifiers.length == 0) {
13617            return null;
13618        }
13619
13620        final int N = pkgInfo.verifiers.length;
13621        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13622        for (int i = 0; i < N; i++) {
13623            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13624
13625            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13626                    receivers);
13627            if (comp == null) {
13628                continue;
13629            }
13630
13631            final int verifierUid = getUidForVerifier(verifierInfo);
13632            if (verifierUid == -1) {
13633                continue;
13634            }
13635
13636            if (DEBUG_VERIFY) {
13637                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13638                        + " with the correct signature");
13639            }
13640            sufficientVerifiers.add(comp);
13641            verificationState.addSufficientVerifier(verifierUid);
13642        }
13643
13644        return sufficientVerifiers;
13645    }
13646
13647    private int getUidForVerifier(VerifierInfo verifierInfo) {
13648        synchronized (mPackages) {
13649            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13650            if (pkg == null) {
13651                return -1;
13652            } else if (pkg.mSignatures.length != 1) {
13653                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13654                        + " has more than one signature; ignoring");
13655                return -1;
13656            }
13657
13658            /*
13659             * If the public key of the package's signature does not match
13660             * our expected public key, then this is a different package and
13661             * we should skip.
13662             */
13663
13664            final byte[] expectedPublicKey;
13665            try {
13666                final Signature verifierSig = pkg.mSignatures[0];
13667                final PublicKey publicKey = verifierSig.getPublicKey();
13668                expectedPublicKey = publicKey.getEncoded();
13669            } catch (CertificateException e) {
13670                return -1;
13671            }
13672
13673            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13674
13675            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13676                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13677                        + " does not have the expected public key; ignoring");
13678                return -1;
13679            }
13680
13681            return pkg.applicationInfo.uid;
13682        }
13683    }
13684
13685    @Override
13686    public void finishPackageInstall(int token, boolean didLaunch) {
13687        enforceSystemOrRoot("Only the system is allowed to finish installs");
13688
13689        if (DEBUG_INSTALL) {
13690            Slog.v(TAG, "BM finishing package install for " + token);
13691        }
13692        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13693
13694        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13695        mHandler.sendMessage(msg);
13696    }
13697
13698    /**
13699     * Get the verification agent timeout.
13700     *
13701     * @return verification timeout in milliseconds
13702     */
13703    private long getVerificationTimeout() {
13704        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13705                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13706                DEFAULT_VERIFICATION_TIMEOUT);
13707    }
13708
13709    /**
13710     * Get the default verification agent response code.
13711     *
13712     * @return default verification response code
13713     */
13714    private int getDefaultVerificationResponse() {
13715        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13716                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13717                DEFAULT_VERIFICATION_RESPONSE);
13718    }
13719
13720    /**
13721     * Check whether or not package verification has been enabled.
13722     *
13723     * @return true if verification should be performed
13724     */
13725    private boolean isVerificationEnabled(int userId, int installFlags) {
13726        if (!DEFAULT_VERIFY_ENABLE) {
13727            return false;
13728        }
13729        // Ephemeral apps don't get the full verification treatment
13730        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13731            if (DEBUG_EPHEMERAL) {
13732                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13733            }
13734            return false;
13735        }
13736
13737        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13738
13739        // Check if installing from ADB
13740        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13741            // Do not run verification in a test harness environment
13742            if (ActivityManager.isRunningInTestHarness()) {
13743                return false;
13744            }
13745            if (ensureVerifyAppsEnabled) {
13746                return true;
13747            }
13748            // Check if the developer does not want package verification for ADB installs
13749            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13750                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13751                return false;
13752            }
13753        }
13754
13755        if (ensureVerifyAppsEnabled) {
13756            return true;
13757        }
13758
13759        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13760                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13761    }
13762
13763    @Override
13764    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13765            throws RemoteException {
13766        mContext.enforceCallingOrSelfPermission(
13767                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13768                "Only intentfilter verification agents can verify applications");
13769
13770        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13771        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13772                Binder.getCallingUid(), verificationCode, failedDomains);
13773        msg.arg1 = id;
13774        msg.obj = response;
13775        mHandler.sendMessage(msg);
13776    }
13777
13778    @Override
13779    public int getIntentVerificationStatus(String packageName, int userId) {
13780        synchronized (mPackages) {
13781            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13782        }
13783    }
13784
13785    @Override
13786    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13787        mContext.enforceCallingOrSelfPermission(
13788                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13789
13790        boolean result = false;
13791        synchronized (mPackages) {
13792            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13793        }
13794        if (result) {
13795            scheduleWritePackageRestrictionsLocked(userId);
13796        }
13797        return result;
13798    }
13799
13800    @Override
13801    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13802            String packageName) {
13803        synchronized (mPackages) {
13804            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13805        }
13806    }
13807
13808    @Override
13809    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13810        if (TextUtils.isEmpty(packageName)) {
13811            return ParceledListSlice.emptyList();
13812        }
13813        synchronized (mPackages) {
13814            PackageParser.Package pkg = mPackages.get(packageName);
13815            if (pkg == null || pkg.activities == null) {
13816                return ParceledListSlice.emptyList();
13817            }
13818            final int count = pkg.activities.size();
13819            ArrayList<IntentFilter> result = new ArrayList<>();
13820            for (int n=0; n<count; n++) {
13821                PackageParser.Activity activity = pkg.activities.get(n);
13822                if (activity.intents != null && activity.intents.size() > 0) {
13823                    result.addAll(activity.intents);
13824                }
13825            }
13826            return new ParceledListSlice<>(result);
13827        }
13828    }
13829
13830    @Override
13831    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13832        mContext.enforceCallingOrSelfPermission(
13833                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13834
13835        synchronized (mPackages) {
13836            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13837            if (packageName != null) {
13838                result |= updateIntentVerificationStatus(packageName,
13839                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13840                        userId);
13841                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13842                        packageName, userId);
13843            }
13844            return result;
13845        }
13846    }
13847
13848    @Override
13849    public String getDefaultBrowserPackageName(int userId) {
13850        synchronized (mPackages) {
13851            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13852        }
13853    }
13854
13855    /**
13856     * Get the "allow unknown sources" setting.
13857     *
13858     * @return the current "allow unknown sources" setting
13859     */
13860    private int getUnknownSourcesSettings() {
13861        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13862                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13863                -1);
13864    }
13865
13866    @Override
13867    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13868        final int uid = Binder.getCallingUid();
13869        // writer
13870        synchronized (mPackages) {
13871            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13872            if (targetPackageSetting == null) {
13873                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13874            }
13875
13876            PackageSetting installerPackageSetting;
13877            if (installerPackageName != null) {
13878                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13879                if (installerPackageSetting == null) {
13880                    throw new IllegalArgumentException("Unknown installer package: "
13881                            + installerPackageName);
13882                }
13883            } else {
13884                installerPackageSetting = null;
13885            }
13886
13887            Signature[] callerSignature;
13888            Object obj = mSettings.getUserIdLPr(uid);
13889            if (obj != null) {
13890                if (obj instanceof SharedUserSetting) {
13891                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13892                } else if (obj instanceof PackageSetting) {
13893                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13894                } else {
13895                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13896                }
13897            } else {
13898                throw new SecurityException("Unknown calling UID: " + uid);
13899            }
13900
13901            // Verify: can't set installerPackageName to a package that is
13902            // not signed with the same cert as the caller.
13903            if (installerPackageSetting != null) {
13904                if (compareSignatures(callerSignature,
13905                        installerPackageSetting.signatures.mSignatures)
13906                        != PackageManager.SIGNATURE_MATCH) {
13907                    throw new SecurityException(
13908                            "Caller does not have same cert as new installer package "
13909                            + installerPackageName);
13910                }
13911            }
13912
13913            // Verify: if target already has an installer package, it must
13914            // be signed with the same cert as the caller.
13915            if (targetPackageSetting.installerPackageName != null) {
13916                PackageSetting setting = mSettings.mPackages.get(
13917                        targetPackageSetting.installerPackageName);
13918                // If the currently set package isn't valid, then it's always
13919                // okay to change it.
13920                if (setting != null) {
13921                    if (compareSignatures(callerSignature,
13922                            setting.signatures.mSignatures)
13923                            != PackageManager.SIGNATURE_MATCH) {
13924                        throw new SecurityException(
13925                                "Caller does not have same cert as old installer package "
13926                                + targetPackageSetting.installerPackageName);
13927                    }
13928                }
13929            }
13930
13931            // Okay!
13932            targetPackageSetting.installerPackageName = installerPackageName;
13933            if (installerPackageName != null) {
13934                mSettings.mInstallerPackages.add(installerPackageName);
13935            }
13936            scheduleWriteSettingsLocked();
13937        }
13938    }
13939
13940    @Override
13941    public void setApplicationCategoryHint(String packageName, int categoryHint,
13942            String callerPackageName) {
13943        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13944                callerPackageName);
13945        synchronized (mPackages) {
13946            PackageSetting ps = mSettings.mPackages.get(packageName);
13947            if (ps == null) {
13948                throw new IllegalArgumentException("Unknown target package " + packageName);
13949            }
13950
13951            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13952                throw new IllegalArgumentException("Calling package " + callerPackageName
13953                        + " is not installer for " + packageName);
13954            }
13955
13956            if (ps.categoryHint != categoryHint) {
13957                ps.categoryHint = categoryHint;
13958                scheduleWriteSettingsLocked();
13959            }
13960        }
13961    }
13962
13963    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13964        // Queue up an async operation since the package installation may take a little while.
13965        mHandler.post(new Runnable() {
13966            public void run() {
13967                mHandler.removeCallbacks(this);
13968                 // Result object to be returned
13969                PackageInstalledInfo res = new PackageInstalledInfo();
13970                res.setReturnCode(currentStatus);
13971                res.uid = -1;
13972                res.pkg = null;
13973                res.removedInfo = null;
13974                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13975                    args.doPreInstall(res.returnCode);
13976                    synchronized (mInstallLock) {
13977                        installPackageTracedLI(args, res);
13978                    }
13979                    args.doPostInstall(res.returnCode, res.uid);
13980                }
13981
13982                // A restore should be performed at this point if (a) the install
13983                // succeeded, (b) the operation is not an update, and (c) the new
13984                // package has not opted out of backup participation.
13985                final boolean update = res.removedInfo != null
13986                        && res.removedInfo.removedPackage != null;
13987                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13988                boolean doRestore = !update
13989                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13990
13991                // Set up the post-install work request bookkeeping.  This will be used
13992                // and cleaned up by the post-install event handling regardless of whether
13993                // there's a restore pass performed.  Token values are >= 1.
13994                int token;
13995                if (mNextInstallToken < 0) mNextInstallToken = 1;
13996                token = mNextInstallToken++;
13997
13998                PostInstallData data = new PostInstallData(args, res);
13999                mRunningInstalls.put(token, data);
14000                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14001
14002                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14003                    // Pass responsibility to the Backup Manager.  It will perform a
14004                    // restore if appropriate, then pass responsibility back to the
14005                    // Package Manager to run the post-install observer callbacks
14006                    // and broadcasts.
14007                    IBackupManager bm = IBackupManager.Stub.asInterface(
14008                            ServiceManager.getService(Context.BACKUP_SERVICE));
14009                    if (bm != null) {
14010                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14011                                + " to BM for possible restore");
14012                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14013                        try {
14014                            // TODO: http://b/22388012
14015                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14016                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14017                            } else {
14018                                doRestore = false;
14019                            }
14020                        } catch (RemoteException e) {
14021                            // can't happen; the backup manager is local
14022                        } catch (Exception e) {
14023                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14024                            doRestore = false;
14025                        }
14026                    } else {
14027                        Slog.e(TAG, "Backup Manager not found!");
14028                        doRestore = false;
14029                    }
14030                }
14031
14032                if (!doRestore) {
14033                    // No restore possible, or the Backup Manager was mysteriously not
14034                    // available -- just fire the post-install work request directly.
14035                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14036
14037                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14038
14039                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14040                    mHandler.sendMessage(msg);
14041                }
14042            }
14043        });
14044    }
14045
14046    /**
14047     * Callback from PackageSettings whenever an app is first transitioned out of the
14048     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14049     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14050     * here whether the app is the target of an ongoing install, and only send the
14051     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14052     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14053     * handling.
14054     */
14055    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14056        // Serialize this with the rest of the install-process message chain.  In the
14057        // restore-at-install case, this Runnable will necessarily run before the
14058        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14059        // are coherent.  In the non-restore case, the app has already completed install
14060        // and been launched through some other means, so it is not in a problematic
14061        // state for observers to see the FIRST_LAUNCH signal.
14062        mHandler.post(new Runnable() {
14063            @Override
14064            public void run() {
14065                for (int i = 0; i < mRunningInstalls.size(); i++) {
14066                    final PostInstallData data = mRunningInstalls.valueAt(i);
14067                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14068                        continue;
14069                    }
14070                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14071                        // right package; but is it for the right user?
14072                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14073                            if (userId == data.res.newUsers[uIndex]) {
14074                                if (DEBUG_BACKUP) {
14075                                    Slog.i(TAG, "Package " + pkgName
14076                                            + " being restored so deferring FIRST_LAUNCH");
14077                                }
14078                                return;
14079                            }
14080                        }
14081                    }
14082                }
14083                // didn't find it, so not being restored
14084                if (DEBUG_BACKUP) {
14085                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14086                }
14087                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14088            }
14089        });
14090    }
14091
14092    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14093        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14094                installerPkg, null, userIds);
14095    }
14096
14097    private abstract class HandlerParams {
14098        private static final int MAX_RETRIES = 4;
14099
14100        /**
14101         * Number of times startCopy() has been attempted and had a non-fatal
14102         * error.
14103         */
14104        private int mRetries = 0;
14105
14106        /** User handle for the user requesting the information or installation. */
14107        private final UserHandle mUser;
14108        String traceMethod;
14109        int traceCookie;
14110
14111        HandlerParams(UserHandle user) {
14112            mUser = user;
14113        }
14114
14115        UserHandle getUser() {
14116            return mUser;
14117        }
14118
14119        HandlerParams setTraceMethod(String traceMethod) {
14120            this.traceMethod = traceMethod;
14121            return this;
14122        }
14123
14124        HandlerParams setTraceCookie(int traceCookie) {
14125            this.traceCookie = traceCookie;
14126            return this;
14127        }
14128
14129        final boolean startCopy() {
14130            boolean res;
14131            try {
14132                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14133
14134                if (++mRetries > MAX_RETRIES) {
14135                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14136                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14137                    handleServiceError();
14138                    return false;
14139                } else {
14140                    handleStartCopy();
14141                    res = true;
14142                }
14143            } catch (RemoteException e) {
14144                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14145                mHandler.sendEmptyMessage(MCS_RECONNECT);
14146                res = false;
14147            }
14148            handleReturnCode();
14149            return res;
14150        }
14151
14152        final void serviceError() {
14153            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14154            handleServiceError();
14155            handleReturnCode();
14156        }
14157
14158        abstract void handleStartCopy() throws RemoteException;
14159        abstract void handleServiceError();
14160        abstract void handleReturnCode();
14161    }
14162
14163    class MeasureParams extends HandlerParams {
14164        private final PackageStats mStats;
14165        private boolean mSuccess;
14166
14167        private final IPackageStatsObserver mObserver;
14168
14169        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14170            super(new UserHandle(stats.userHandle));
14171            mObserver = observer;
14172            mStats = stats;
14173        }
14174
14175        @Override
14176        public String toString() {
14177            return "MeasureParams{"
14178                + Integer.toHexString(System.identityHashCode(this))
14179                + " " + mStats.packageName + "}";
14180        }
14181
14182        @Override
14183        void handleStartCopy() throws RemoteException {
14184            synchronized (mInstallLock) {
14185                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14186            }
14187
14188            if (mSuccess) {
14189                boolean mounted = false;
14190                try {
14191                    final String status = Environment.getExternalStorageState();
14192                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14193                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14194                } catch (Exception e) {
14195                }
14196
14197                if (mounted) {
14198                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14199
14200                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14201                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14202
14203                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14204                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14205
14206                    // Always subtract cache size, since it's a subdirectory
14207                    mStats.externalDataSize -= mStats.externalCacheSize;
14208
14209                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14210                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14211
14212                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14213                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14214                }
14215            }
14216        }
14217
14218        @Override
14219        void handleReturnCode() {
14220            if (mObserver != null) {
14221                try {
14222                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14223                } catch (RemoteException e) {
14224                    Slog.i(TAG, "Observer no longer exists.");
14225                }
14226            }
14227        }
14228
14229        @Override
14230        void handleServiceError() {
14231            Slog.e(TAG, "Could not measure application " + mStats.packageName
14232                            + " external storage");
14233        }
14234    }
14235
14236    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14237            throws RemoteException {
14238        long result = 0;
14239        for (File path : paths) {
14240            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14241        }
14242        return result;
14243    }
14244
14245    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14246        for (File path : paths) {
14247            try {
14248                mcs.clearDirectory(path.getAbsolutePath());
14249            } catch (RemoteException e) {
14250            }
14251        }
14252    }
14253
14254    static class OriginInfo {
14255        /**
14256         * Location where install is coming from, before it has been
14257         * copied/renamed into place. This could be a single monolithic APK
14258         * file, or a cluster directory. This location may be untrusted.
14259         */
14260        final File file;
14261        final String cid;
14262
14263        /**
14264         * Flag indicating that {@link #file} or {@link #cid} has already been
14265         * staged, meaning downstream users don't need to defensively copy the
14266         * contents.
14267         */
14268        final boolean staged;
14269
14270        /**
14271         * Flag indicating that {@link #file} or {@link #cid} is an already
14272         * installed app that is being moved.
14273         */
14274        final boolean existing;
14275
14276        final String resolvedPath;
14277        final File resolvedFile;
14278
14279        static OriginInfo fromNothing() {
14280            return new OriginInfo(null, null, false, false);
14281        }
14282
14283        static OriginInfo fromUntrustedFile(File file) {
14284            return new OriginInfo(file, null, false, false);
14285        }
14286
14287        static OriginInfo fromExistingFile(File file) {
14288            return new OriginInfo(file, null, false, true);
14289        }
14290
14291        static OriginInfo fromStagedFile(File file) {
14292            return new OriginInfo(file, null, true, false);
14293        }
14294
14295        static OriginInfo fromStagedContainer(String cid) {
14296            return new OriginInfo(null, cid, true, false);
14297        }
14298
14299        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14300            this.file = file;
14301            this.cid = cid;
14302            this.staged = staged;
14303            this.existing = existing;
14304
14305            if (cid != null) {
14306                resolvedPath = PackageHelper.getSdDir(cid);
14307                resolvedFile = new File(resolvedPath);
14308            } else if (file != null) {
14309                resolvedPath = file.getAbsolutePath();
14310                resolvedFile = file;
14311            } else {
14312                resolvedPath = null;
14313                resolvedFile = null;
14314            }
14315        }
14316    }
14317
14318    static class MoveInfo {
14319        final int moveId;
14320        final String fromUuid;
14321        final String toUuid;
14322        final String packageName;
14323        final String dataAppName;
14324        final int appId;
14325        final String seinfo;
14326        final int targetSdkVersion;
14327
14328        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14329                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14330            this.moveId = moveId;
14331            this.fromUuid = fromUuid;
14332            this.toUuid = toUuid;
14333            this.packageName = packageName;
14334            this.dataAppName = dataAppName;
14335            this.appId = appId;
14336            this.seinfo = seinfo;
14337            this.targetSdkVersion = targetSdkVersion;
14338        }
14339    }
14340
14341    static class VerificationInfo {
14342        /** A constant used to indicate that a uid value is not present. */
14343        public static final int NO_UID = -1;
14344
14345        /** URI referencing where the package was downloaded from. */
14346        final Uri originatingUri;
14347
14348        /** HTTP referrer URI associated with the originatingURI. */
14349        final Uri referrer;
14350
14351        /** UID of the application that the install request originated from. */
14352        final int originatingUid;
14353
14354        /** UID of application requesting the install */
14355        final int installerUid;
14356
14357        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14358            this.originatingUri = originatingUri;
14359            this.referrer = referrer;
14360            this.originatingUid = originatingUid;
14361            this.installerUid = installerUid;
14362        }
14363    }
14364
14365    class InstallParams extends HandlerParams {
14366        final OriginInfo origin;
14367        final MoveInfo move;
14368        final IPackageInstallObserver2 observer;
14369        int installFlags;
14370        final String installerPackageName;
14371        final String volumeUuid;
14372        private InstallArgs mArgs;
14373        private int mRet;
14374        final String packageAbiOverride;
14375        final String[] grantedRuntimePermissions;
14376        final VerificationInfo verificationInfo;
14377        final Certificate[][] certificates;
14378        final int installReason;
14379
14380        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14381                int installFlags, String installerPackageName, String volumeUuid,
14382                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14383                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14384            super(user);
14385            this.origin = origin;
14386            this.move = move;
14387            this.observer = observer;
14388            this.installFlags = installFlags;
14389            this.installerPackageName = installerPackageName;
14390            this.volumeUuid = volumeUuid;
14391            this.verificationInfo = verificationInfo;
14392            this.packageAbiOverride = packageAbiOverride;
14393            this.grantedRuntimePermissions = grantedPermissions;
14394            this.certificates = certificates;
14395            this.installReason = installReason;
14396        }
14397
14398        @Override
14399        public String toString() {
14400            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14401                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14402        }
14403
14404        private int installLocationPolicy(PackageInfoLite pkgLite) {
14405            String packageName = pkgLite.packageName;
14406            int installLocation = pkgLite.installLocation;
14407            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14408            // reader
14409            synchronized (mPackages) {
14410                // Currently installed package which the new package is attempting to replace or
14411                // null if no such package is installed.
14412                PackageParser.Package installedPkg = mPackages.get(packageName);
14413                // Package which currently owns the data which the new package will own if installed.
14414                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14415                // will be null whereas dataOwnerPkg will contain information about the package
14416                // which was uninstalled while keeping its data.
14417                PackageParser.Package dataOwnerPkg = installedPkg;
14418                if (dataOwnerPkg  == null) {
14419                    PackageSetting ps = mSettings.mPackages.get(packageName);
14420                    if (ps != null) {
14421                        dataOwnerPkg = ps.pkg;
14422                    }
14423                }
14424
14425                if (dataOwnerPkg != null) {
14426                    // If installed, the package will get access to data left on the device by its
14427                    // predecessor. As a security measure, this is permited only if this is not a
14428                    // version downgrade or if the predecessor package is marked as debuggable and
14429                    // a downgrade is explicitly requested.
14430                    //
14431                    // On debuggable platform builds, downgrades are permitted even for
14432                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14433                    // not offer security guarantees and thus it's OK to disable some security
14434                    // mechanisms to make debugging/testing easier on those builds. However, even on
14435                    // debuggable builds downgrades of packages are permitted only if requested via
14436                    // installFlags. This is because we aim to keep the behavior of debuggable
14437                    // platform builds as close as possible to the behavior of non-debuggable
14438                    // platform builds.
14439                    final boolean downgradeRequested =
14440                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14441                    final boolean packageDebuggable =
14442                                (dataOwnerPkg.applicationInfo.flags
14443                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14444                    final boolean downgradePermitted =
14445                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14446                    if (!downgradePermitted) {
14447                        try {
14448                            checkDowngrade(dataOwnerPkg, pkgLite);
14449                        } catch (PackageManagerException e) {
14450                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14451                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14452                        }
14453                    }
14454                }
14455
14456                if (installedPkg != null) {
14457                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14458                        // Check for updated system application.
14459                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14460                            if (onSd) {
14461                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14462                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14463                            }
14464                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14465                        } else {
14466                            if (onSd) {
14467                                // Install flag overrides everything.
14468                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14469                            }
14470                            // If current upgrade specifies particular preference
14471                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14472                                // Application explicitly specified internal.
14473                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14474                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14475                                // App explictly prefers external. Let policy decide
14476                            } else {
14477                                // Prefer previous location
14478                                if (isExternal(installedPkg)) {
14479                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14480                                }
14481                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14482                            }
14483                        }
14484                    } else {
14485                        // Invalid install. Return error code
14486                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14487                    }
14488                }
14489            }
14490            // All the special cases have been taken care of.
14491            // Return result based on recommended install location.
14492            if (onSd) {
14493                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14494            }
14495            return pkgLite.recommendedInstallLocation;
14496        }
14497
14498        /*
14499         * Invoke remote method to get package information and install
14500         * location values. Override install location based on default
14501         * policy if needed and then create install arguments based
14502         * on the install location.
14503         */
14504        public void handleStartCopy() throws RemoteException {
14505            int ret = PackageManager.INSTALL_SUCCEEDED;
14506
14507            // If we're already staged, we've firmly committed to an install location
14508            if (origin.staged) {
14509                if (origin.file != null) {
14510                    installFlags |= PackageManager.INSTALL_INTERNAL;
14511                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14512                } else if (origin.cid != null) {
14513                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14514                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14515                } else {
14516                    throw new IllegalStateException("Invalid stage location");
14517                }
14518            }
14519
14520            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14521            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14522            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14523            PackageInfoLite pkgLite = null;
14524
14525            if (onInt && onSd) {
14526                // Check if both bits are set.
14527                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14528                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14529            } else if (onSd && ephemeral) {
14530                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14531                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14532            } else {
14533                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14534                        packageAbiOverride);
14535
14536                if (DEBUG_EPHEMERAL && ephemeral) {
14537                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14538                }
14539
14540                /*
14541                 * If we have too little free space, try to free cache
14542                 * before giving up.
14543                 */
14544                if (!origin.staged && pkgLite.recommendedInstallLocation
14545                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14546                    // TODO: focus freeing disk space on the target device
14547                    final StorageManager storage = StorageManager.from(mContext);
14548                    final long lowThreshold = storage.getStorageLowBytes(
14549                            Environment.getDataDirectory());
14550
14551                    final long sizeBytes = mContainerService.calculateInstalledSize(
14552                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14553
14554                    try {
14555                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14556                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14557                                installFlags, packageAbiOverride);
14558                    } catch (InstallerException e) {
14559                        Slog.w(TAG, "Failed to free cache", e);
14560                    }
14561
14562                    /*
14563                     * The cache free must have deleted the file we
14564                     * downloaded to install.
14565                     *
14566                     * TODO: fix the "freeCache" call to not delete
14567                     *       the file we care about.
14568                     */
14569                    if (pkgLite.recommendedInstallLocation
14570                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14571                        pkgLite.recommendedInstallLocation
14572                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14573                    }
14574                }
14575            }
14576
14577            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14578                int loc = pkgLite.recommendedInstallLocation;
14579                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14580                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14581                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14582                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14583                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14584                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14585                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14586                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14587                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14588                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14589                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14590                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14591                } else {
14592                    // Override with defaults if needed.
14593                    loc = installLocationPolicy(pkgLite);
14594                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14595                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14596                    } else if (!onSd && !onInt) {
14597                        // Override install location with flags
14598                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14599                            // Set the flag to install on external media.
14600                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14601                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14602                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14603                            if (DEBUG_EPHEMERAL) {
14604                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14605                            }
14606                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14607                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14608                                    |PackageManager.INSTALL_INTERNAL);
14609                        } else {
14610                            // Make sure the flag for installing on external
14611                            // media is unset
14612                            installFlags |= PackageManager.INSTALL_INTERNAL;
14613                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14614                        }
14615                    }
14616                }
14617            }
14618
14619            final InstallArgs args = createInstallArgs(this);
14620            mArgs = args;
14621
14622            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14623                // TODO: http://b/22976637
14624                // Apps installed for "all" users use the device owner to verify the app
14625                UserHandle verifierUser = getUser();
14626                if (verifierUser == UserHandle.ALL) {
14627                    verifierUser = UserHandle.SYSTEM;
14628                }
14629
14630                /*
14631                 * Determine if we have any installed package verifiers. If we
14632                 * do, then we'll defer to them to verify the packages.
14633                 */
14634                final int requiredUid = mRequiredVerifierPackage == null ? -1
14635                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14636                                verifierUser.getIdentifier());
14637                if (!origin.existing && requiredUid != -1
14638                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14639                    final Intent verification = new Intent(
14640                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14641                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14642                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14643                            PACKAGE_MIME_TYPE);
14644                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14645
14646                    // Query all live verifiers based on current user state
14647                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14648                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14649
14650                    if (DEBUG_VERIFY) {
14651                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14652                                + verification.toString() + " with " + pkgLite.verifiers.length
14653                                + " optional verifiers");
14654                    }
14655
14656                    final int verificationId = mPendingVerificationToken++;
14657
14658                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14659
14660                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14661                            installerPackageName);
14662
14663                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14664                            installFlags);
14665
14666                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14667                            pkgLite.packageName);
14668
14669                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14670                            pkgLite.versionCode);
14671
14672                    if (verificationInfo != null) {
14673                        if (verificationInfo.originatingUri != null) {
14674                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14675                                    verificationInfo.originatingUri);
14676                        }
14677                        if (verificationInfo.referrer != null) {
14678                            verification.putExtra(Intent.EXTRA_REFERRER,
14679                                    verificationInfo.referrer);
14680                        }
14681                        if (verificationInfo.originatingUid >= 0) {
14682                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14683                                    verificationInfo.originatingUid);
14684                        }
14685                        if (verificationInfo.installerUid >= 0) {
14686                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14687                                    verificationInfo.installerUid);
14688                        }
14689                    }
14690
14691                    final PackageVerificationState verificationState = new PackageVerificationState(
14692                            requiredUid, args);
14693
14694                    mPendingVerification.append(verificationId, verificationState);
14695
14696                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14697                            receivers, verificationState);
14698
14699                    /*
14700                     * If any sufficient verifiers were listed in the package
14701                     * manifest, attempt to ask them.
14702                     */
14703                    if (sufficientVerifiers != null) {
14704                        final int N = sufficientVerifiers.size();
14705                        if (N == 0) {
14706                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14707                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14708                        } else {
14709                            for (int i = 0; i < N; i++) {
14710                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14711
14712                                final Intent sufficientIntent = new Intent(verification);
14713                                sufficientIntent.setComponent(verifierComponent);
14714                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14715                            }
14716                        }
14717                    }
14718
14719                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14720                            mRequiredVerifierPackage, receivers);
14721                    if (ret == PackageManager.INSTALL_SUCCEEDED
14722                            && mRequiredVerifierPackage != null) {
14723                        Trace.asyncTraceBegin(
14724                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14725                        /*
14726                         * Send the intent to the required verification agent,
14727                         * but only start the verification timeout after the
14728                         * target BroadcastReceivers have run.
14729                         */
14730                        verification.setComponent(requiredVerifierComponent);
14731                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14732                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14733                                new BroadcastReceiver() {
14734                                    @Override
14735                                    public void onReceive(Context context, Intent intent) {
14736                                        final Message msg = mHandler
14737                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14738                                        msg.arg1 = verificationId;
14739                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14740                                    }
14741                                }, null, 0, null, null);
14742
14743                        /*
14744                         * We don't want the copy to proceed until verification
14745                         * succeeds, so null out this field.
14746                         */
14747                        mArgs = null;
14748                    }
14749                } else {
14750                    /*
14751                     * No package verification is enabled, so immediately start
14752                     * the remote call to initiate copy using temporary file.
14753                     */
14754                    ret = args.copyApk(mContainerService, true);
14755                }
14756            }
14757
14758            mRet = ret;
14759        }
14760
14761        @Override
14762        void handleReturnCode() {
14763            // If mArgs is null, then MCS couldn't be reached. When it
14764            // reconnects, it will try again to install. At that point, this
14765            // will succeed.
14766            if (mArgs != null) {
14767                processPendingInstall(mArgs, mRet);
14768            }
14769        }
14770
14771        @Override
14772        void handleServiceError() {
14773            mArgs = createInstallArgs(this);
14774            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14775        }
14776
14777        public boolean isForwardLocked() {
14778            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14779        }
14780    }
14781
14782    /**
14783     * Used during creation of InstallArgs
14784     *
14785     * @param installFlags package installation flags
14786     * @return true if should be installed on external storage
14787     */
14788    private static boolean installOnExternalAsec(int installFlags) {
14789        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14790            return false;
14791        }
14792        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14793            return true;
14794        }
14795        return false;
14796    }
14797
14798    /**
14799     * Used during creation of InstallArgs
14800     *
14801     * @param installFlags package installation flags
14802     * @return true if should be installed as forward locked
14803     */
14804    private static boolean installForwardLocked(int installFlags) {
14805        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14806    }
14807
14808    private InstallArgs createInstallArgs(InstallParams params) {
14809        if (params.move != null) {
14810            return new MoveInstallArgs(params);
14811        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14812            return new AsecInstallArgs(params);
14813        } else {
14814            return new FileInstallArgs(params);
14815        }
14816    }
14817
14818    /**
14819     * Create args that describe an existing installed package. Typically used
14820     * when cleaning up old installs, or used as a move source.
14821     */
14822    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14823            String resourcePath, String[] instructionSets) {
14824        final boolean isInAsec;
14825        if (installOnExternalAsec(installFlags)) {
14826            /* Apps on SD card are always in ASEC containers. */
14827            isInAsec = true;
14828        } else if (installForwardLocked(installFlags)
14829                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14830            /*
14831             * Forward-locked apps are only in ASEC containers if they're the
14832             * new style
14833             */
14834            isInAsec = true;
14835        } else {
14836            isInAsec = false;
14837        }
14838
14839        if (isInAsec) {
14840            return new AsecInstallArgs(codePath, instructionSets,
14841                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14842        } else {
14843            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14844        }
14845    }
14846
14847    static abstract class InstallArgs {
14848        /** @see InstallParams#origin */
14849        final OriginInfo origin;
14850        /** @see InstallParams#move */
14851        final MoveInfo move;
14852
14853        final IPackageInstallObserver2 observer;
14854        // Always refers to PackageManager flags only
14855        final int installFlags;
14856        final String installerPackageName;
14857        final String volumeUuid;
14858        final UserHandle user;
14859        final String abiOverride;
14860        final String[] installGrantPermissions;
14861        /** If non-null, drop an async trace when the install completes */
14862        final String traceMethod;
14863        final int traceCookie;
14864        final Certificate[][] certificates;
14865        final int installReason;
14866
14867        // The list of instruction sets supported by this app. This is currently
14868        // only used during the rmdex() phase to clean up resources. We can get rid of this
14869        // if we move dex files under the common app path.
14870        /* nullable */ String[] instructionSets;
14871
14872        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14873                int installFlags, String installerPackageName, String volumeUuid,
14874                UserHandle user, String[] instructionSets,
14875                String abiOverride, String[] installGrantPermissions,
14876                String traceMethod, int traceCookie, Certificate[][] certificates,
14877                int installReason) {
14878            this.origin = origin;
14879            this.move = move;
14880            this.installFlags = installFlags;
14881            this.observer = observer;
14882            this.installerPackageName = installerPackageName;
14883            this.volumeUuid = volumeUuid;
14884            this.user = user;
14885            this.instructionSets = instructionSets;
14886            this.abiOverride = abiOverride;
14887            this.installGrantPermissions = installGrantPermissions;
14888            this.traceMethod = traceMethod;
14889            this.traceCookie = traceCookie;
14890            this.certificates = certificates;
14891            this.installReason = installReason;
14892        }
14893
14894        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14895        abstract int doPreInstall(int status);
14896
14897        /**
14898         * Rename package into final resting place. All paths on the given
14899         * scanned package should be updated to reflect the rename.
14900         */
14901        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14902        abstract int doPostInstall(int status, int uid);
14903
14904        /** @see PackageSettingBase#codePathString */
14905        abstract String getCodePath();
14906        /** @see PackageSettingBase#resourcePathString */
14907        abstract String getResourcePath();
14908
14909        // Need installer lock especially for dex file removal.
14910        abstract void cleanUpResourcesLI();
14911        abstract boolean doPostDeleteLI(boolean delete);
14912
14913        /**
14914         * Called before the source arguments are copied. This is used mostly
14915         * for MoveParams when it needs to read the source file to put it in the
14916         * destination.
14917         */
14918        int doPreCopy() {
14919            return PackageManager.INSTALL_SUCCEEDED;
14920        }
14921
14922        /**
14923         * Called after the source arguments are copied. This is used mostly for
14924         * MoveParams when it needs to read the source file to put it in the
14925         * destination.
14926         */
14927        int doPostCopy(int uid) {
14928            return PackageManager.INSTALL_SUCCEEDED;
14929        }
14930
14931        protected boolean isFwdLocked() {
14932            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14933        }
14934
14935        protected boolean isExternalAsec() {
14936            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14937        }
14938
14939        protected boolean isEphemeral() {
14940            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14941        }
14942
14943        UserHandle getUser() {
14944            return user;
14945        }
14946    }
14947
14948    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14949        if (!allCodePaths.isEmpty()) {
14950            if (instructionSets == null) {
14951                throw new IllegalStateException("instructionSet == null");
14952            }
14953            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14954            for (String codePath : allCodePaths) {
14955                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14956                    try {
14957                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14958                    } catch (InstallerException ignored) {
14959                    }
14960                }
14961            }
14962        }
14963    }
14964
14965    /**
14966     * Logic to handle installation of non-ASEC applications, including copying
14967     * and renaming logic.
14968     */
14969    class FileInstallArgs extends InstallArgs {
14970        private File codeFile;
14971        private File resourceFile;
14972
14973        // Example topology:
14974        // /data/app/com.example/base.apk
14975        // /data/app/com.example/split_foo.apk
14976        // /data/app/com.example/lib/arm/libfoo.so
14977        // /data/app/com.example/lib/arm64/libfoo.so
14978        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14979
14980        /** New install */
14981        FileInstallArgs(InstallParams params) {
14982            super(params.origin, params.move, params.observer, params.installFlags,
14983                    params.installerPackageName, params.volumeUuid,
14984                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14985                    params.grantedRuntimePermissions,
14986                    params.traceMethod, params.traceCookie, params.certificates,
14987                    params.installReason);
14988            if (isFwdLocked()) {
14989                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14990            }
14991        }
14992
14993        /** Existing install */
14994        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14995            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14996                    null, null, null, 0, null /*certificates*/,
14997                    PackageManager.INSTALL_REASON_UNKNOWN);
14998            this.codeFile = (codePath != null) ? new File(codePath) : null;
14999            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15000        }
15001
15002        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15003            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15004            try {
15005                return doCopyApk(imcs, temp);
15006            } finally {
15007                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15008            }
15009        }
15010
15011        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15012            if (origin.staged) {
15013                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15014                codeFile = origin.file;
15015                resourceFile = origin.file;
15016                return PackageManager.INSTALL_SUCCEEDED;
15017            }
15018
15019            try {
15020                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15021                final File tempDir =
15022                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15023                codeFile = tempDir;
15024                resourceFile = tempDir;
15025            } catch (IOException e) {
15026                Slog.w(TAG, "Failed to create copy file: " + e);
15027                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15028            }
15029
15030            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15031                @Override
15032                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15033                    if (!FileUtils.isValidExtFilename(name)) {
15034                        throw new IllegalArgumentException("Invalid filename: " + name);
15035                    }
15036                    try {
15037                        final File file = new File(codeFile, name);
15038                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15039                                O_RDWR | O_CREAT, 0644);
15040                        Os.chmod(file.getAbsolutePath(), 0644);
15041                        return new ParcelFileDescriptor(fd);
15042                    } catch (ErrnoException e) {
15043                        throw new RemoteException("Failed to open: " + e.getMessage());
15044                    }
15045                }
15046            };
15047
15048            int ret = PackageManager.INSTALL_SUCCEEDED;
15049            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15050            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15051                Slog.e(TAG, "Failed to copy package");
15052                return ret;
15053            }
15054
15055            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15056            NativeLibraryHelper.Handle handle = null;
15057            try {
15058                handle = NativeLibraryHelper.Handle.create(codeFile);
15059                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15060                        abiOverride);
15061            } catch (IOException e) {
15062                Slog.e(TAG, "Copying native libraries failed", e);
15063                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15064            } finally {
15065                IoUtils.closeQuietly(handle);
15066            }
15067
15068            return ret;
15069        }
15070
15071        int doPreInstall(int status) {
15072            if (status != PackageManager.INSTALL_SUCCEEDED) {
15073                cleanUp();
15074            }
15075            return status;
15076        }
15077
15078        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15079            if (status != PackageManager.INSTALL_SUCCEEDED) {
15080                cleanUp();
15081                return false;
15082            }
15083
15084            final File targetDir = codeFile.getParentFile();
15085            final File beforeCodeFile = codeFile;
15086            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15087
15088            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15089            try {
15090                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15091            } catch (ErrnoException e) {
15092                Slog.w(TAG, "Failed to rename", e);
15093                return false;
15094            }
15095
15096            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15097                Slog.w(TAG, "Failed to restorecon");
15098                return false;
15099            }
15100
15101            // Reflect the rename internally
15102            codeFile = afterCodeFile;
15103            resourceFile = afterCodeFile;
15104
15105            // Reflect the rename in scanned details
15106            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15107            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15108                    afterCodeFile, pkg.baseCodePath));
15109            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15110                    afterCodeFile, pkg.splitCodePaths));
15111
15112            // Reflect the rename in app info
15113            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15114            pkg.setApplicationInfoCodePath(pkg.codePath);
15115            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15116            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15117            pkg.setApplicationInfoResourcePath(pkg.codePath);
15118            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15119            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15120
15121            return true;
15122        }
15123
15124        int doPostInstall(int status, int uid) {
15125            if (status != PackageManager.INSTALL_SUCCEEDED) {
15126                cleanUp();
15127            }
15128            return status;
15129        }
15130
15131        @Override
15132        String getCodePath() {
15133            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15134        }
15135
15136        @Override
15137        String getResourcePath() {
15138            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15139        }
15140
15141        private boolean cleanUp() {
15142            if (codeFile == null || !codeFile.exists()) {
15143                return false;
15144            }
15145
15146            removeCodePathLI(codeFile);
15147
15148            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15149                resourceFile.delete();
15150            }
15151
15152            return true;
15153        }
15154
15155        void cleanUpResourcesLI() {
15156            // Try enumerating all code paths before deleting
15157            List<String> allCodePaths = Collections.EMPTY_LIST;
15158            if (codeFile != null && codeFile.exists()) {
15159                try {
15160                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15161                    allCodePaths = pkg.getAllCodePaths();
15162                } catch (PackageParserException e) {
15163                    // Ignored; we tried our best
15164                }
15165            }
15166
15167            cleanUp();
15168            removeDexFiles(allCodePaths, instructionSets);
15169        }
15170
15171        boolean doPostDeleteLI(boolean delete) {
15172            // XXX err, shouldn't we respect the delete flag?
15173            cleanUpResourcesLI();
15174            return true;
15175        }
15176    }
15177
15178    private boolean isAsecExternal(String cid) {
15179        final String asecPath = PackageHelper.getSdFilesystem(cid);
15180        return !asecPath.startsWith(mAsecInternalPath);
15181    }
15182
15183    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15184            PackageManagerException {
15185        if (copyRet < 0) {
15186            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15187                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15188                throw new PackageManagerException(copyRet, message);
15189            }
15190        }
15191    }
15192
15193    /**
15194     * Extract the StorageManagerService "container ID" from the full code path of an
15195     * .apk.
15196     */
15197    static String cidFromCodePath(String fullCodePath) {
15198        int eidx = fullCodePath.lastIndexOf("/");
15199        String subStr1 = fullCodePath.substring(0, eidx);
15200        int sidx = subStr1.lastIndexOf("/");
15201        return subStr1.substring(sidx+1, eidx);
15202    }
15203
15204    /**
15205     * Logic to handle installation of ASEC applications, including copying and
15206     * renaming logic.
15207     */
15208    class AsecInstallArgs extends InstallArgs {
15209        static final String RES_FILE_NAME = "pkg.apk";
15210        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15211
15212        String cid;
15213        String packagePath;
15214        String resourcePath;
15215
15216        /** New install */
15217        AsecInstallArgs(InstallParams params) {
15218            super(params.origin, params.move, params.observer, params.installFlags,
15219                    params.installerPackageName, params.volumeUuid,
15220                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15221                    params.grantedRuntimePermissions,
15222                    params.traceMethod, params.traceCookie, params.certificates,
15223                    params.installReason);
15224        }
15225
15226        /** Existing install */
15227        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15228                        boolean isExternal, boolean isForwardLocked) {
15229            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15230                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15231                    instructionSets, null, null, null, 0, null /*certificates*/,
15232                    PackageManager.INSTALL_REASON_UNKNOWN);
15233            // Hackily pretend we're still looking at a full code path
15234            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15235                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15236            }
15237
15238            // Extract cid from fullCodePath
15239            int eidx = fullCodePath.lastIndexOf("/");
15240            String subStr1 = fullCodePath.substring(0, eidx);
15241            int sidx = subStr1.lastIndexOf("/");
15242            cid = subStr1.substring(sidx+1, eidx);
15243            setMountPath(subStr1);
15244        }
15245
15246        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15247            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15248                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15249                    instructionSets, null, null, null, 0, null /*certificates*/,
15250                    PackageManager.INSTALL_REASON_UNKNOWN);
15251            this.cid = cid;
15252            setMountPath(PackageHelper.getSdDir(cid));
15253        }
15254
15255        void createCopyFile() {
15256            cid = mInstallerService.allocateExternalStageCidLegacy();
15257        }
15258
15259        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15260            if (origin.staged && origin.cid != null) {
15261                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15262                cid = origin.cid;
15263                setMountPath(PackageHelper.getSdDir(cid));
15264                return PackageManager.INSTALL_SUCCEEDED;
15265            }
15266
15267            if (temp) {
15268                createCopyFile();
15269            } else {
15270                /*
15271                 * Pre-emptively destroy the container since it's destroyed if
15272                 * copying fails due to it existing anyway.
15273                 */
15274                PackageHelper.destroySdDir(cid);
15275            }
15276
15277            final String newMountPath = imcs.copyPackageToContainer(
15278                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15279                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15280
15281            if (newMountPath != null) {
15282                setMountPath(newMountPath);
15283                return PackageManager.INSTALL_SUCCEEDED;
15284            } else {
15285                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15286            }
15287        }
15288
15289        @Override
15290        String getCodePath() {
15291            return packagePath;
15292        }
15293
15294        @Override
15295        String getResourcePath() {
15296            return resourcePath;
15297        }
15298
15299        int doPreInstall(int status) {
15300            if (status != PackageManager.INSTALL_SUCCEEDED) {
15301                // Destroy container
15302                PackageHelper.destroySdDir(cid);
15303            } else {
15304                boolean mounted = PackageHelper.isContainerMounted(cid);
15305                if (!mounted) {
15306                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15307                            Process.SYSTEM_UID);
15308                    if (newMountPath != null) {
15309                        setMountPath(newMountPath);
15310                    } else {
15311                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15312                    }
15313                }
15314            }
15315            return status;
15316        }
15317
15318        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15319            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15320            String newMountPath = null;
15321            if (PackageHelper.isContainerMounted(cid)) {
15322                // Unmount the container
15323                if (!PackageHelper.unMountSdDir(cid)) {
15324                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15325                    return false;
15326                }
15327            }
15328            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15329                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15330                        " which might be stale. Will try to clean up.");
15331                // Clean up the stale container and proceed to recreate.
15332                if (!PackageHelper.destroySdDir(newCacheId)) {
15333                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15334                    return false;
15335                }
15336                // Successfully cleaned up stale container. Try to rename again.
15337                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15338                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15339                            + " inspite of cleaning it up.");
15340                    return false;
15341                }
15342            }
15343            if (!PackageHelper.isContainerMounted(newCacheId)) {
15344                Slog.w(TAG, "Mounting container " + newCacheId);
15345                newMountPath = PackageHelper.mountSdDir(newCacheId,
15346                        getEncryptKey(), Process.SYSTEM_UID);
15347            } else {
15348                newMountPath = PackageHelper.getSdDir(newCacheId);
15349            }
15350            if (newMountPath == null) {
15351                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15352                return false;
15353            }
15354            Log.i(TAG, "Succesfully renamed " + cid +
15355                    " to " + newCacheId +
15356                    " at new path: " + newMountPath);
15357            cid = newCacheId;
15358
15359            final File beforeCodeFile = new File(packagePath);
15360            setMountPath(newMountPath);
15361            final File afterCodeFile = new File(packagePath);
15362
15363            // Reflect the rename in scanned details
15364            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15365            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15366                    afterCodeFile, pkg.baseCodePath));
15367            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15368                    afterCodeFile, pkg.splitCodePaths));
15369
15370            // Reflect the rename in app info
15371            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15372            pkg.setApplicationInfoCodePath(pkg.codePath);
15373            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15374            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15375            pkg.setApplicationInfoResourcePath(pkg.codePath);
15376            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15377            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15378
15379            return true;
15380        }
15381
15382        private void setMountPath(String mountPath) {
15383            final File mountFile = new File(mountPath);
15384
15385            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15386            if (monolithicFile.exists()) {
15387                packagePath = monolithicFile.getAbsolutePath();
15388                if (isFwdLocked()) {
15389                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15390                } else {
15391                    resourcePath = packagePath;
15392                }
15393            } else {
15394                packagePath = mountFile.getAbsolutePath();
15395                resourcePath = packagePath;
15396            }
15397        }
15398
15399        int doPostInstall(int status, int uid) {
15400            if (status != PackageManager.INSTALL_SUCCEEDED) {
15401                cleanUp();
15402            } else {
15403                final int groupOwner;
15404                final String protectedFile;
15405                if (isFwdLocked()) {
15406                    groupOwner = UserHandle.getSharedAppGid(uid);
15407                    protectedFile = RES_FILE_NAME;
15408                } else {
15409                    groupOwner = -1;
15410                    protectedFile = null;
15411                }
15412
15413                if (uid < Process.FIRST_APPLICATION_UID
15414                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15415                    Slog.e(TAG, "Failed to finalize " + cid);
15416                    PackageHelper.destroySdDir(cid);
15417                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15418                }
15419
15420                boolean mounted = PackageHelper.isContainerMounted(cid);
15421                if (!mounted) {
15422                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15423                }
15424            }
15425            return status;
15426        }
15427
15428        private void cleanUp() {
15429            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15430
15431            // Destroy secure container
15432            PackageHelper.destroySdDir(cid);
15433        }
15434
15435        private List<String> getAllCodePaths() {
15436            final File codeFile = new File(getCodePath());
15437            if (codeFile != null && codeFile.exists()) {
15438                try {
15439                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15440                    return pkg.getAllCodePaths();
15441                } catch (PackageParserException e) {
15442                    // Ignored; we tried our best
15443                }
15444            }
15445            return Collections.EMPTY_LIST;
15446        }
15447
15448        void cleanUpResourcesLI() {
15449            // Enumerate all code paths before deleting
15450            cleanUpResourcesLI(getAllCodePaths());
15451        }
15452
15453        private void cleanUpResourcesLI(List<String> allCodePaths) {
15454            cleanUp();
15455            removeDexFiles(allCodePaths, instructionSets);
15456        }
15457
15458        String getPackageName() {
15459            return getAsecPackageName(cid);
15460        }
15461
15462        boolean doPostDeleteLI(boolean delete) {
15463            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15464            final List<String> allCodePaths = getAllCodePaths();
15465            boolean mounted = PackageHelper.isContainerMounted(cid);
15466            if (mounted) {
15467                // Unmount first
15468                if (PackageHelper.unMountSdDir(cid)) {
15469                    mounted = false;
15470                }
15471            }
15472            if (!mounted && delete) {
15473                cleanUpResourcesLI(allCodePaths);
15474            }
15475            return !mounted;
15476        }
15477
15478        @Override
15479        int doPreCopy() {
15480            if (isFwdLocked()) {
15481                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15482                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15483                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15484                }
15485            }
15486
15487            return PackageManager.INSTALL_SUCCEEDED;
15488        }
15489
15490        @Override
15491        int doPostCopy(int uid) {
15492            if (isFwdLocked()) {
15493                if (uid < Process.FIRST_APPLICATION_UID
15494                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15495                                RES_FILE_NAME)) {
15496                    Slog.e(TAG, "Failed to finalize " + cid);
15497                    PackageHelper.destroySdDir(cid);
15498                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15499                }
15500            }
15501
15502            return PackageManager.INSTALL_SUCCEEDED;
15503        }
15504    }
15505
15506    /**
15507     * Logic to handle movement of existing installed applications.
15508     */
15509    class MoveInstallArgs extends InstallArgs {
15510        private File codeFile;
15511        private File resourceFile;
15512
15513        /** New install */
15514        MoveInstallArgs(InstallParams params) {
15515            super(params.origin, params.move, params.observer, params.installFlags,
15516                    params.installerPackageName, params.volumeUuid,
15517                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15518                    params.grantedRuntimePermissions,
15519                    params.traceMethod, params.traceCookie, params.certificates,
15520                    params.installReason);
15521        }
15522
15523        int copyApk(IMediaContainerService imcs, boolean temp) {
15524            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15525                    + move.fromUuid + " to " + move.toUuid);
15526            synchronized (mInstaller) {
15527                try {
15528                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15529                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15530                } catch (InstallerException e) {
15531                    Slog.w(TAG, "Failed to move app", e);
15532                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15533                }
15534            }
15535
15536            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15537            resourceFile = codeFile;
15538            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15539
15540            return PackageManager.INSTALL_SUCCEEDED;
15541        }
15542
15543        int doPreInstall(int status) {
15544            if (status != PackageManager.INSTALL_SUCCEEDED) {
15545                cleanUp(move.toUuid);
15546            }
15547            return status;
15548        }
15549
15550        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15551            if (status != PackageManager.INSTALL_SUCCEEDED) {
15552                cleanUp(move.toUuid);
15553                return false;
15554            }
15555
15556            // Reflect the move in app info
15557            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15558            pkg.setApplicationInfoCodePath(pkg.codePath);
15559            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15560            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15561            pkg.setApplicationInfoResourcePath(pkg.codePath);
15562            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15563            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15564
15565            return true;
15566        }
15567
15568        int doPostInstall(int status, int uid) {
15569            if (status == PackageManager.INSTALL_SUCCEEDED) {
15570                cleanUp(move.fromUuid);
15571            } else {
15572                cleanUp(move.toUuid);
15573            }
15574            return status;
15575        }
15576
15577        @Override
15578        String getCodePath() {
15579            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15580        }
15581
15582        @Override
15583        String getResourcePath() {
15584            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15585        }
15586
15587        private boolean cleanUp(String volumeUuid) {
15588            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15589                    move.dataAppName);
15590            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15591            final int[] userIds = sUserManager.getUserIds();
15592            synchronized (mInstallLock) {
15593                // Clean up both app data and code
15594                // All package moves are frozen until finished
15595                for (int userId : userIds) {
15596                    try {
15597                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15598                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15599                    } catch (InstallerException e) {
15600                        Slog.w(TAG, String.valueOf(e));
15601                    }
15602                }
15603                removeCodePathLI(codeFile);
15604            }
15605            return true;
15606        }
15607
15608        void cleanUpResourcesLI() {
15609            throw new UnsupportedOperationException();
15610        }
15611
15612        boolean doPostDeleteLI(boolean delete) {
15613            throw new UnsupportedOperationException();
15614        }
15615    }
15616
15617    static String getAsecPackageName(String packageCid) {
15618        int idx = packageCid.lastIndexOf("-");
15619        if (idx == -1) {
15620            return packageCid;
15621        }
15622        return packageCid.substring(0, idx);
15623    }
15624
15625    // Utility method used to create code paths based on package name and available index.
15626    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15627        String idxStr = "";
15628        int idx = 1;
15629        // Fall back to default value of idx=1 if prefix is not
15630        // part of oldCodePath
15631        if (oldCodePath != null) {
15632            String subStr = oldCodePath;
15633            // Drop the suffix right away
15634            if (suffix != null && subStr.endsWith(suffix)) {
15635                subStr = subStr.substring(0, subStr.length() - suffix.length());
15636            }
15637            // If oldCodePath already contains prefix find out the
15638            // ending index to either increment or decrement.
15639            int sidx = subStr.lastIndexOf(prefix);
15640            if (sidx != -1) {
15641                subStr = subStr.substring(sidx + prefix.length());
15642                if (subStr != null) {
15643                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15644                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15645                    }
15646                    try {
15647                        idx = Integer.parseInt(subStr);
15648                        if (idx <= 1) {
15649                            idx++;
15650                        } else {
15651                            idx--;
15652                        }
15653                    } catch(NumberFormatException e) {
15654                    }
15655                }
15656            }
15657        }
15658        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15659        return prefix + idxStr;
15660    }
15661
15662    private File getNextCodePath(File targetDir, String packageName) {
15663        File result;
15664        SecureRandom random = new SecureRandom();
15665        byte[] bytes = new byte[16];
15666        do {
15667            random.nextBytes(bytes);
15668            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15669            result = new File(targetDir, packageName + "-" + suffix);
15670        } while (result.exists());
15671        return result;
15672    }
15673
15674    // Utility method that returns the relative package path with respect
15675    // to the installation directory. Like say for /data/data/com.test-1.apk
15676    // string com.test-1 is returned.
15677    static String deriveCodePathName(String codePath) {
15678        if (codePath == null) {
15679            return null;
15680        }
15681        final File codeFile = new File(codePath);
15682        final String name = codeFile.getName();
15683        if (codeFile.isDirectory()) {
15684            return name;
15685        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15686            final int lastDot = name.lastIndexOf('.');
15687            return name.substring(0, lastDot);
15688        } else {
15689            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15690            return null;
15691        }
15692    }
15693
15694    static class PackageInstalledInfo {
15695        String name;
15696        int uid;
15697        // The set of users that originally had this package installed.
15698        int[] origUsers;
15699        // The set of users that now have this package installed.
15700        int[] newUsers;
15701        PackageParser.Package pkg;
15702        int returnCode;
15703        String returnMsg;
15704        PackageRemovedInfo removedInfo;
15705        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15706
15707        public void setError(int code, String msg) {
15708            setReturnCode(code);
15709            setReturnMessage(msg);
15710            Slog.w(TAG, msg);
15711        }
15712
15713        public void setError(String msg, PackageParserException e) {
15714            setReturnCode(e.error);
15715            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15716            Slog.w(TAG, msg, e);
15717        }
15718
15719        public void setError(String msg, PackageManagerException e) {
15720            returnCode = e.error;
15721            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15722            Slog.w(TAG, msg, e);
15723        }
15724
15725        public void setReturnCode(int returnCode) {
15726            this.returnCode = returnCode;
15727            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15728            for (int i = 0; i < childCount; i++) {
15729                addedChildPackages.valueAt(i).returnCode = returnCode;
15730            }
15731        }
15732
15733        private void setReturnMessage(String returnMsg) {
15734            this.returnMsg = returnMsg;
15735            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15736            for (int i = 0; i < childCount; i++) {
15737                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15738            }
15739        }
15740
15741        // In some error cases we want to convey more info back to the observer
15742        String origPackage;
15743        String origPermission;
15744    }
15745
15746    /*
15747     * Install a non-existing package.
15748     */
15749    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15750            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15751            PackageInstalledInfo res, int installReason) {
15752        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15753
15754        // Remember this for later, in case we need to rollback this install
15755        String pkgName = pkg.packageName;
15756
15757        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15758
15759        synchronized(mPackages) {
15760            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15761            if (renamedPackage != null) {
15762                // A package with the same name is already installed, though
15763                // it has been renamed to an older name.  The package we
15764                // are trying to install should be installed as an update to
15765                // the existing one, but that has not been requested, so bail.
15766                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15767                        + " without first uninstalling package running as "
15768                        + renamedPackage);
15769                return;
15770            }
15771            if (mPackages.containsKey(pkgName)) {
15772                // Don't allow installation over an existing package with the same name.
15773                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15774                        + " without first uninstalling.");
15775                return;
15776            }
15777        }
15778
15779        try {
15780            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15781                    System.currentTimeMillis(), user);
15782
15783            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15784
15785            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15786                prepareAppDataAfterInstallLIF(newPackage);
15787
15788            } else {
15789                // Remove package from internal structures, but keep around any
15790                // data that might have already existed
15791                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15792                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15793            }
15794        } catch (PackageManagerException e) {
15795            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15796        }
15797
15798        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15799    }
15800
15801    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15802        // Can't rotate keys during boot or if sharedUser.
15803        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15804                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15805            return false;
15806        }
15807        // app is using upgradeKeySets; make sure all are valid
15808        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15809        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15810        for (int i = 0; i < upgradeKeySets.length; i++) {
15811            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15812                Slog.wtf(TAG, "Package "
15813                         + (oldPs.name != null ? oldPs.name : "<null>")
15814                         + " contains upgrade-key-set reference to unknown key-set: "
15815                         + upgradeKeySets[i]
15816                         + " reverting to signatures check.");
15817                return false;
15818            }
15819        }
15820        return true;
15821    }
15822
15823    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15824        // Upgrade keysets are being used.  Determine if new package has a superset of the
15825        // required keys.
15826        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15827        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15828        for (int i = 0; i < upgradeKeySets.length; i++) {
15829            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15830            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15831                return true;
15832            }
15833        }
15834        return false;
15835    }
15836
15837    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15838        try (DigestInputStream digestStream =
15839                new DigestInputStream(new FileInputStream(file), digest)) {
15840            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15841        }
15842    }
15843
15844    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15845            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15846            int installReason) {
15847        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15848
15849        final PackageParser.Package oldPackage;
15850        final String pkgName = pkg.packageName;
15851        final int[] allUsers;
15852        final int[] installedUsers;
15853
15854        synchronized(mPackages) {
15855            oldPackage = mPackages.get(pkgName);
15856            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15857
15858            // don't allow upgrade to target a release SDK from a pre-release SDK
15859            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15860                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15861            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15862                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15863            if (oldTargetsPreRelease
15864                    && !newTargetsPreRelease
15865                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15866                Slog.w(TAG, "Can't install package targeting released sdk");
15867                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15868                return;
15869            }
15870
15871            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15872
15873            // don't allow an upgrade from full to ephemeral
15874            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15875                // can't downgrade from full to instant
15876                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15877                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15878                return;
15879            }
15880
15881            // verify signatures are valid
15882            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15883                if (!checkUpgradeKeySetLP(ps, pkg)) {
15884                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15885                            "New package not signed by keys specified by upgrade-keysets: "
15886                                    + pkgName);
15887                    return;
15888                }
15889            } else {
15890                // default to original signature matching
15891                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15892                        != PackageManager.SIGNATURE_MATCH) {
15893                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15894                            "New package has a different signature: " + pkgName);
15895                    return;
15896                }
15897            }
15898
15899            // don't allow a system upgrade unless the upgrade hash matches
15900            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15901                byte[] digestBytes = null;
15902                try {
15903                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15904                    updateDigest(digest, new File(pkg.baseCodePath));
15905                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15906                        for (String path : pkg.splitCodePaths) {
15907                            updateDigest(digest, new File(path));
15908                        }
15909                    }
15910                    digestBytes = digest.digest();
15911                } catch (NoSuchAlgorithmException | IOException e) {
15912                    res.setError(INSTALL_FAILED_INVALID_APK,
15913                            "Could not compute hash: " + pkgName);
15914                    return;
15915                }
15916                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15917                    res.setError(INSTALL_FAILED_INVALID_APK,
15918                            "New package fails restrict-update check: " + pkgName);
15919                    return;
15920                }
15921                // retain upgrade restriction
15922                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15923            }
15924
15925            // Check for shared user id changes
15926            String invalidPackageName =
15927                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15928            if (invalidPackageName != null) {
15929                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15930                        "Package " + invalidPackageName + " tried to change user "
15931                                + oldPackage.mSharedUserId);
15932                return;
15933            }
15934
15935            // In case of rollback, remember per-user/profile install state
15936            allUsers = sUserManager.getUserIds();
15937            installedUsers = ps.queryInstalledUsers(allUsers, true);
15938        }
15939
15940        // Update what is removed
15941        res.removedInfo = new PackageRemovedInfo();
15942        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15943        res.removedInfo.removedPackage = oldPackage.packageName;
15944        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15945        res.removedInfo.isUpdate = true;
15946        res.removedInfo.origUsers = installedUsers;
15947        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15948        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15949        for (int i = 0; i < installedUsers.length; i++) {
15950            final int userId = installedUsers[i];
15951            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15952        }
15953
15954        final int childCount = (oldPackage.childPackages != null)
15955                ? oldPackage.childPackages.size() : 0;
15956        for (int i = 0; i < childCount; i++) {
15957            boolean childPackageUpdated = false;
15958            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15959            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15960            if (res.addedChildPackages != null) {
15961                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15962                if (childRes != null) {
15963                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15964                    childRes.removedInfo.removedPackage = childPkg.packageName;
15965                    childRes.removedInfo.isUpdate = true;
15966                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15967                    childPackageUpdated = true;
15968                }
15969            }
15970            if (!childPackageUpdated) {
15971                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15972                childRemovedRes.removedPackage = childPkg.packageName;
15973                childRemovedRes.isUpdate = false;
15974                childRemovedRes.dataRemoved = true;
15975                synchronized (mPackages) {
15976                    if (childPs != null) {
15977                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15978                    }
15979                }
15980                if (res.removedInfo.removedChildPackages == null) {
15981                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15982                }
15983                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15984            }
15985        }
15986
15987        boolean sysPkg = (isSystemApp(oldPackage));
15988        if (sysPkg) {
15989            // Set the system/privileged flags as needed
15990            final boolean privileged =
15991                    (oldPackage.applicationInfo.privateFlags
15992                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15993            final int systemPolicyFlags = policyFlags
15994                    | PackageParser.PARSE_IS_SYSTEM
15995                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15996
15997            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15998                    user, allUsers, installerPackageName, res, installReason);
15999        } else {
16000            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16001                    user, allUsers, installerPackageName, res, installReason);
16002        }
16003    }
16004
16005    public List<String> getPreviousCodePaths(String packageName) {
16006        final PackageSetting ps = mSettings.mPackages.get(packageName);
16007        final List<String> result = new ArrayList<String>();
16008        if (ps != null && ps.oldCodePaths != null) {
16009            result.addAll(ps.oldCodePaths);
16010        }
16011        return result;
16012    }
16013
16014    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16015            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16016            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16017            int installReason) {
16018        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16019                + deletedPackage);
16020
16021        String pkgName = deletedPackage.packageName;
16022        boolean deletedPkg = true;
16023        boolean addedPkg = false;
16024        boolean updatedSettings = false;
16025        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16026        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16027                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16028
16029        final long origUpdateTime = (pkg.mExtras != null)
16030                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16031
16032        // First delete the existing package while retaining the data directory
16033        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16034                res.removedInfo, true, pkg)) {
16035            // If the existing package wasn't successfully deleted
16036            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16037            deletedPkg = false;
16038        } else {
16039            // Successfully deleted the old package; proceed with replace.
16040
16041            // If deleted package lived in a container, give users a chance to
16042            // relinquish resources before killing.
16043            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16044                if (DEBUG_INSTALL) {
16045                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16046                }
16047                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16048                final ArrayList<String> pkgList = new ArrayList<String>(1);
16049                pkgList.add(deletedPackage.applicationInfo.packageName);
16050                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16051            }
16052
16053            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16054                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16055            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16056
16057            try {
16058                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16059                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16060                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16061                        installReason);
16062
16063                // Update the in-memory copy of the previous code paths.
16064                PackageSetting ps = mSettings.mPackages.get(pkgName);
16065                if (!killApp) {
16066                    if (ps.oldCodePaths == null) {
16067                        ps.oldCodePaths = new ArraySet<>();
16068                    }
16069                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16070                    if (deletedPackage.splitCodePaths != null) {
16071                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16072                    }
16073                } else {
16074                    ps.oldCodePaths = null;
16075                }
16076                if (ps.childPackageNames != null) {
16077                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16078                        final String childPkgName = ps.childPackageNames.get(i);
16079                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16080                        childPs.oldCodePaths = ps.oldCodePaths;
16081                    }
16082                }
16083                // set instant app status, but, only if it's explicitly specified
16084                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16085                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16086                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16087                prepareAppDataAfterInstallLIF(newPackage);
16088                addedPkg = true;
16089            } catch (PackageManagerException e) {
16090                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16091            }
16092        }
16093
16094        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16095            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16096
16097            // Revert all internal state mutations and added folders for the failed install
16098            if (addedPkg) {
16099                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16100                        res.removedInfo, true, null);
16101            }
16102
16103            // Restore the old package
16104            if (deletedPkg) {
16105                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16106                File restoreFile = new File(deletedPackage.codePath);
16107                // Parse old package
16108                boolean oldExternal = isExternal(deletedPackage);
16109                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16110                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16111                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16112                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16113                try {
16114                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16115                            null);
16116                } catch (PackageManagerException e) {
16117                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16118                            + e.getMessage());
16119                    return;
16120                }
16121
16122                synchronized (mPackages) {
16123                    // Ensure the installer package name up to date
16124                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16125
16126                    // Update permissions for restored package
16127                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16128
16129                    mSettings.writeLPr();
16130                }
16131
16132                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16133            }
16134        } else {
16135            synchronized (mPackages) {
16136                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16137                if (ps != null) {
16138                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16139                    if (res.removedInfo.removedChildPackages != null) {
16140                        final int childCount = res.removedInfo.removedChildPackages.size();
16141                        // Iterate in reverse as we may modify the collection
16142                        for (int i = childCount - 1; i >= 0; i--) {
16143                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16144                            if (res.addedChildPackages.containsKey(childPackageName)) {
16145                                res.removedInfo.removedChildPackages.removeAt(i);
16146                            } else {
16147                                PackageRemovedInfo childInfo = res.removedInfo
16148                                        .removedChildPackages.valueAt(i);
16149                                childInfo.removedForAllUsers = mPackages.get(
16150                                        childInfo.removedPackage) == null;
16151                            }
16152                        }
16153                    }
16154                }
16155            }
16156        }
16157    }
16158
16159    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16160            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16161            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16162            int installReason) {
16163        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16164                + ", old=" + deletedPackage);
16165
16166        final boolean disabledSystem;
16167
16168        // Remove existing system package
16169        removePackageLI(deletedPackage, true);
16170
16171        synchronized (mPackages) {
16172            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16173        }
16174        if (!disabledSystem) {
16175            // We didn't need to disable the .apk as a current system package,
16176            // which means we are replacing another update that is already
16177            // installed.  We need to make sure to delete the older one's .apk.
16178            res.removedInfo.args = createInstallArgsForExisting(0,
16179                    deletedPackage.applicationInfo.getCodePath(),
16180                    deletedPackage.applicationInfo.getResourcePath(),
16181                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16182        } else {
16183            res.removedInfo.args = null;
16184        }
16185
16186        // Successfully disabled the old package. Now proceed with re-installation
16187        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16188                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16189        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16190
16191        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16192        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16193                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16194
16195        PackageParser.Package newPackage = null;
16196        try {
16197            // Add the package to the internal data structures
16198            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16199
16200            // Set the update and install times
16201            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16202            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16203                    System.currentTimeMillis());
16204
16205            // Update the package dynamic state if succeeded
16206            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16207                // Now that the install succeeded make sure we remove data
16208                // directories for any child package the update removed.
16209                final int deletedChildCount = (deletedPackage.childPackages != null)
16210                        ? deletedPackage.childPackages.size() : 0;
16211                final int newChildCount = (newPackage.childPackages != null)
16212                        ? newPackage.childPackages.size() : 0;
16213                for (int i = 0; i < deletedChildCount; i++) {
16214                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16215                    boolean childPackageDeleted = true;
16216                    for (int j = 0; j < newChildCount; j++) {
16217                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16218                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16219                            childPackageDeleted = false;
16220                            break;
16221                        }
16222                    }
16223                    if (childPackageDeleted) {
16224                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16225                                deletedChildPkg.packageName);
16226                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16227                            PackageRemovedInfo removedChildRes = res.removedInfo
16228                                    .removedChildPackages.get(deletedChildPkg.packageName);
16229                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16230                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16231                        }
16232                    }
16233                }
16234
16235                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16236                        installReason);
16237                prepareAppDataAfterInstallLIF(newPackage);
16238            }
16239        } catch (PackageManagerException e) {
16240            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16241            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16242        }
16243
16244        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16245            // Re installation failed. Restore old information
16246            // Remove new pkg information
16247            if (newPackage != null) {
16248                removeInstalledPackageLI(newPackage, true);
16249            }
16250            // Add back the old system package
16251            try {
16252                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16253            } catch (PackageManagerException e) {
16254                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16255            }
16256
16257            synchronized (mPackages) {
16258                if (disabledSystem) {
16259                    enableSystemPackageLPw(deletedPackage);
16260                }
16261
16262                // Ensure the installer package name up to date
16263                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16264
16265                // Update permissions for restored package
16266                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16267
16268                mSettings.writeLPr();
16269            }
16270
16271            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16272                    + " after failed upgrade");
16273        }
16274    }
16275
16276    /**
16277     * Checks whether the parent or any of the child packages have a change shared
16278     * user. For a package to be a valid update the shred users of the parent and
16279     * the children should match. We may later support changing child shared users.
16280     * @param oldPkg The updated package.
16281     * @param newPkg The update package.
16282     * @return The shared user that change between the versions.
16283     */
16284    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16285            PackageParser.Package newPkg) {
16286        // Check parent shared user
16287        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16288            return newPkg.packageName;
16289        }
16290        // Check child shared users
16291        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16292        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16293        for (int i = 0; i < newChildCount; i++) {
16294            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16295            // If this child was present, did it have the same shared user?
16296            for (int j = 0; j < oldChildCount; j++) {
16297                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16298                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16299                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16300                    return newChildPkg.packageName;
16301                }
16302            }
16303        }
16304        return null;
16305    }
16306
16307    private void removeNativeBinariesLI(PackageSetting ps) {
16308        // Remove the lib path for the parent package
16309        if (ps != null) {
16310            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16311            // Remove the lib path for the child packages
16312            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16313            for (int i = 0; i < childCount; i++) {
16314                PackageSetting childPs = null;
16315                synchronized (mPackages) {
16316                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16317                }
16318                if (childPs != null) {
16319                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16320                            .legacyNativeLibraryPathString);
16321                }
16322            }
16323        }
16324    }
16325
16326    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16327        // Enable the parent package
16328        mSettings.enableSystemPackageLPw(pkg.packageName);
16329        // Enable the child packages
16330        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16331        for (int i = 0; i < childCount; i++) {
16332            PackageParser.Package childPkg = pkg.childPackages.get(i);
16333            mSettings.enableSystemPackageLPw(childPkg.packageName);
16334        }
16335    }
16336
16337    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16338            PackageParser.Package newPkg) {
16339        // Disable the parent package (parent always replaced)
16340        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16341        // Disable the child packages
16342        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16343        for (int i = 0; i < childCount; i++) {
16344            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16345            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16346            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16347        }
16348        return disabled;
16349    }
16350
16351    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16352            String installerPackageName) {
16353        // Enable the parent package
16354        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16355        // Enable the child packages
16356        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16357        for (int i = 0; i < childCount; i++) {
16358            PackageParser.Package childPkg = pkg.childPackages.get(i);
16359            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16360        }
16361    }
16362
16363    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16364        // Collect all used permissions in the UID
16365        ArraySet<String> usedPermissions = new ArraySet<>();
16366        final int packageCount = su.packages.size();
16367        for (int i = 0; i < packageCount; i++) {
16368            PackageSetting ps = su.packages.valueAt(i);
16369            if (ps.pkg == null) {
16370                continue;
16371            }
16372            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16373            for (int j = 0; j < requestedPermCount; j++) {
16374                String permission = ps.pkg.requestedPermissions.get(j);
16375                BasePermission bp = mSettings.mPermissions.get(permission);
16376                if (bp != null) {
16377                    usedPermissions.add(permission);
16378                }
16379            }
16380        }
16381
16382        PermissionsState permissionsState = su.getPermissionsState();
16383        // Prune install permissions
16384        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16385        final int installPermCount = installPermStates.size();
16386        for (int i = installPermCount - 1; i >= 0;  i--) {
16387            PermissionState permissionState = installPermStates.get(i);
16388            if (!usedPermissions.contains(permissionState.getName())) {
16389                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16390                if (bp != null) {
16391                    permissionsState.revokeInstallPermission(bp);
16392                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16393                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16394                }
16395            }
16396        }
16397
16398        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16399
16400        // Prune runtime permissions
16401        for (int userId : allUserIds) {
16402            List<PermissionState> runtimePermStates = permissionsState
16403                    .getRuntimePermissionStates(userId);
16404            final int runtimePermCount = runtimePermStates.size();
16405            for (int i = runtimePermCount - 1; i >= 0; i--) {
16406                PermissionState permissionState = runtimePermStates.get(i);
16407                if (!usedPermissions.contains(permissionState.getName())) {
16408                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16409                    if (bp != null) {
16410                        permissionsState.revokeRuntimePermission(bp, userId);
16411                        permissionsState.updatePermissionFlags(bp, userId,
16412                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16413                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16414                                runtimePermissionChangedUserIds, userId);
16415                    }
16416                }
16417            }
16418        }
16419
16420        return runtimePermissionChangedUserIds;
16421    }
16422
16423    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16424            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16425        // Update the parent package setting
16426        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16427                res, user, installReason);
16428        // Update the child packages setting
16429        final int childCount = (newPackage.childPackages != null)
16430                ? newPackage.childPackages.size() : 0;
16431        for (int i = 0; i < childCount; i++) {
16432            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16433            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16434            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16435                    childRes.origUsers, childRes, user, installReason);
16436        }
16437    }
16438
16439    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16440            String installerPackageName, int[] allUsers, int[] installedForUsers,
16441            PackageInstalledInfo res, UserHandle user, int installReason) {
16442        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16443
16444        String pkgName = newPackage.packageName;
16445        synchronized (mPackages) {
16446            //write settings. the installStatus will be incomplete at this stage.
16447            //note that the new package setting would have already been
16448            //added to mPackages. It hasn't been persisted yet.
16449            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16450            // TODO: Remove this write? It's also written at the end of this method
16451            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16452            mSettings.writeLPr();
16453            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16454        }
16455
16456        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16457        synchronized (mPackages) {
16458            updatePermissionsLPw(newPackage.packageName, newPackage,
16459                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16460                            ? UPDATE_PERMISSIONS_ALL : 0));
16461            // For system-bundled packages, we assume that installing an upgraded version
16462            // of the package implies that the user actually wants to run that new code,
16463            // so we enable the package.
16464            PackageSetting ps = mSettings.mPackages.get(pkgName);
16465            final int userId = user.getIdentifier();
16466            if (ps != null) {
16467                if (isSystemApp(newPackage)) {
16468                    if (DEBUG_INSTALL) {
16469                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16470                    }
16471                    // Enable system package for requested users
16472                    if (res.origUsers != null) {
16473                        for (int origUserId : res.origUsers) {
16474                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16475                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16476                                        origUserId, installerPackageName);
16477                            }
16478                        }
16479                    }
16480                    // Also convey the prior install/uninstall state
16481                    if (allUsers != null && installedForUsers != null) {
16482                        for (int currentUserId : allUsers) {
16483                            final boolean installed = ArrayUtils.contains(
16484                                    installedForUsers, currentUserId);
16485                            if (DEBUG_INSTALL) {
16486                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16487                            }
16488                            ps.setInstalled(installed, currentUserId);
16489                        }
16490                        // these install state changes will be persisted in the
16491                        // upcoming call to mSettings.writeLPr().
16492                    }
16493                }
16494                // It's implied that when a user requests installation, they want the app to be
16495                // installed and enabled.
16496                if (userId != UserHandle.USER_ALL) {
16497                    ps.setInstalled(true, userId);
16498                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16499                }
16500
16501                // When replacing an existing package, preserve the original install reason for all
16502                // users that had the package installed before.
16503                final Set<Integer> previousUserIds = new ArraySet<>();
16504                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16505                    final int installReasonCount = res.removedInfo.installReasons.size();
16506                    for (int i = 0; i < installReasonCount; i++) {
16507                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16508                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16509                        ps.setInstallReason(previousInstallReason, previousUserId);
16510                        previousUserIds.add(previousUserId);
16511                    }
16512                }
16513
16514                // Set install reason for users that are having the package newly installed.
16515                if (userId == UserHandle.USER_ALL) {
16516                    for (int currentUserId : sUserManager.getUserIds()) {
16517                        if (!previousUserIds.contains(currentUserId)) {
16518                            ps.setInstallReason(installReason, currentUserId);
16519                        }
16520                    }
16521                } else if (!previousUserIds.contains(userId)) {
16522                    ps.setInstallReason(installReason, userId);
16523                }
16524                mSettings.writeKernelMappingLPr(ps);
16525            }
16526            res.name = pkgName;
16527            res.uid = newPackage.applicationInfo.uid;
16528            res.pkg = newPackage;
16529            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16530            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16531            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16532            //to update install status
16533            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16534            mSettings.writeLPr();
16535            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16536        }
16537
16538        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16539    }
16540
16541    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16542        try {
16543            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16544            installPackageLI(args, res);
16545        } finally {
16546            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16547        }
16548    }
16549
16550    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16551        final int installFlags = args.installFlags;
16552        final String installerPackageName = args.installerPackageName;
16553        final String volumeUuid = args.volumeUuid;
16554        final File tmpPackageFile = new File(args.getCodePath());
16555        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16556        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16557                || (args.volumeUuid != null));
16558        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16559        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16560        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16561        boolean replace = false;
16562        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16563        if (args.move != null) {
16564            // moving a complete application; perform an initial scan on the new install location
16565            scanFlags |= SCAN_INITIAL;
16566        }
16567        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16568            scanFlags |= SCAN_DONT_KILL_APP;
16569        }
16570        if (instantApp) {
16571            scanFlags |= SCAN_AS_INSTANT_APP;
16572        }
16573        if (fullApp) {
16574            scanFlags |= SCAN_AS_FULL_APP;
16575        }
16576
16577        // Result object to be returned
16578        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16579
16580        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16581
16582        // Sanity check
16583        if (instantApp && (forwardLocked || onExternal)) {
16584            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16585                    + " external=" + onExternal);
16586            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16587            return;
16588        }
16589
16590        // Retrieve PackageSettings and parse package
16591        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16592                | PackageParser.PARSE_ENFORCE_CODE
16593                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16594                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16595                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16596                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16597        PackageParser pp = new PackageParser();
16598        pp.setSeparateProcesses(mSeparateProcesses);
16599        pp.setDisplayMetrics(mMetrics);
16600
16601        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16602        final PackageParser.Package pkg;
16603        try {
16604            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16605        } catch (PackageParserException e) {
16606            res.setError("Failed parse during installPackageLI", e);
16607            return;
16608        } finally {
16609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16610        }
16611
16612//        // Ephemeral apps must have target SDK >= O.
16613//        // TODO: Update conditional and error message when O gets locked down
16614//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16615//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16616//                    "Ephemeral apps must have target SDK version of at least O");
16617//            return;
16618//        }
16619
16620        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16621            // Static shared libraries have synthetic package names
16622            renameStaticSharedLibraryPackage(pkg);
16623
16624            // No static shared libs on external storage
16625            if (onExternal) {
16626                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16627                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16628                        "Packages declaring static-shared libs cannot be updated");
16629                return;
16630            }
16631        }
16632
16633        // If we are installing a clustered package add results for the children
16634        if (pkg.childPackages != null) {
16635            synchronized (mPackages) {
16636                final int childCount = pkg.childPackages.size();
16637                for (int i = 0; i < childCount; i++) {
16638                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16639                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16640                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16641                    childRes.pkg = childPkg;
16642                    childRes.name = childPkg.packageName;
16643                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16644                    if (childPs != null) {
16645                        childRes.origUsers = childPs.queryInstalledUsers(
16646                                sUserManager.getUserIds(), true);
16647                    }
16648                    if ((mPackages.containsKey(childPkg.packageName))) {
16649                        childRes.removedInfo = new PackageRemovedInfo();
16650                        childRes.removedInfo.removedPackage = childPkg.packageName;
16651                    }
16652                    if (res.addedChildPackages == null) {
16653                        res.addedChildPackages = new ArrayMap<>();
16654                    }
16655                    res.addedChildPackages.put(childPkg.packageName, childRes);
16656                }
16657            }
16658        }
16659
16660        // If package doesn't declare API override, mark that we have an install
16661        // time CPU ABI override.
16662        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16663            pkg.cpuAbiOverride = args.abiOverride;
16664        }
16665
16666        String pkgName = res.name = pkg.packageName;
16667        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16668            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16669                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16670                return;
16671            }
16672        }
16673
16674        try {
16675            // either use what we've been given or parse directly from the APK
16676            if (args.certificates != null) {
16677                try {
16678                    PackageParser.populateCertificates(pkg, args.certificates);
16679                } catch (PackageParserException e) {
16680                    // there was something wrong with the certificates we were given;
16681                    // try to pull them from the APK
16682                    PackageParser.collectCertificates(pkg, parseFlags);
16683                }
16684            } else {
16685                PackageParser.collectCertificates(pkg, parseFlags);
16686            }
16687        } catch (PackageParserException e) {
16688            res.setError("Failed collect during installPackageLI", e);
16689            return;
16690        }
16691
16692        // Get rid of all references to package scan path via parser.
16693        pp = null;
16694        String oldCodePath = null;
16695        boolean systemApp = false;
16696        synchronized (mPackages) {
16697            // Check if installing already existing package
16698            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16699                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16700                if (pkg.mOriginalPackages != null
16701                        && pkg.mOriginalPackages.contains(oldName)
16702                        && mPackages.containsKey(oldName)) {
16703                    // This package is derived from an original package,
16704                    // and this device has been updating from that original
16705                    // name.  We must continue using the original name, so
16706                    // rename the new package here.
16707                    pkg.setPackageName(oldName);
16708                    pkgName = pkg.packageName;
16709                    replace = true;
16710                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16711                            + oldName + " pkgName=" + pkgName);
16712                } else if (mPackages.containsKey(pkgName)) {
16713                    // This package, under its official name, already exists
16714                    // on the device; we should replace it.
16715                    replace = true;
16716                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16717                }
16718
16719                // Child packages are installed through the parent package
16720                if (pkg.parentPackage != null) {
16721                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16722                            "Package " + pkg.packageName + " is child of package "
16723                                    + pkg.parentPackage.parentPackage + ". Child packages "
16724                                    + "can be updated only through the parent package.");
16725                    return;
16726                }
16727
16728                if (replace) {
16729                    // Prevent apps opting out from runtime permissions
16730                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16731                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16732                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16733                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16734                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16735                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16736                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16737                                        + " doesn't support runtime permissions but the old"
16738                                        + " target SDK " + oldTargetSdk + " does.");
16739                        return;
16740                    }
16741
16742                    // Prevent installing of child packages
16743                    if (oldPackage.parentPackage != null) {
16744                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16745                                "Package " + pkg.packageName + " is child of package "
16746                                        + oldPackage.parentPackage + ". Child packages "
16747                                        + "can be updated only through the parent package.");
16748                        return;
16749                    }
16750                }
16751            }
16752
16753            PackageSetting ps = mSettings.mPackages.get(pkgName);
16754            if (ps != null) {
16755                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16756
16757                // Static shared libs have same package with different versions where
16758                // we internally use a synthetic package name to allow multiple versions
16759                // of the same package, therefore we need to compare signatures against
16760                // the package setting for the latest library version.
16761                PackageSetting signatureCheckPs = ps;
16762                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16763                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16764                    if (libraryEntry != null) {
16765                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16766                    }
16767                }
16768
16769                // Quick sanity check that we're signed correctly if updating;
16770                // we'll check this again later when scanning, but we want to
16771                // bail early here before tripping over redefined permissions.
16772                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16773                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16774                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16775                                + pkg.packageName + " upgrade keys do not match the "
16776                                + "previously installed version");
16777                        return;
16778                    }
16779                } else {
16780                    try {
16781                        verifySignaturesLP(signatureCheckPs, pkg);
16782                    } catch (PackageManagerException e) {
16783                        res.setError(e.error, e.getMessage());
16784                        return;
16785                    }
16786                }
16787
16788                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16789                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16790                    systemApp = (ps.pkg.applicationInfo.flags &
16791                            ApplicationInfo.FLAG_SYSTEM) != 0;
16792                }
16793                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16794            }
16795
16796            // Check whether the newly-scanned package wants to define an already-defined perm
16797            int N = pkg.permissions.size();
16798            for (int i = N-1; i >= 0; i--) {
16799                PackageParser.Permission perm = pkg.permissions.get(i);
16800                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16801                if (bp != null) {
16802                    // If the defining package is signed with our cert, it's okay.  This
16803                    // also includes the "updating the same package" case, of course.
16804                    // "updating same package" could also involve key-rotation.
16805                    final boolean sigsOk;
16806                    if (bp.sourcePackage.equals(pkg.packageName)
16807                            && (bp.packageSetting instanceof PackageSetting)
16808                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16809                                    scanFlags))) {
16810                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16811                    } else {
16812                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16813                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16814                    }
16815                    if (!sigsOk) {
16816                        // If the owning package is the system itself, we log but allow
16817                        // install to proceed; we fail the install on all other permission
16818                        // redefinitions.
16819                        if (!bp.sourcePackage.equals("android")) {
16820                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16821                                    + pkg.packageName + " attempting to redeclare permission "
16822                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16823                            res.origPermission = perm.info.name;
16824                            res.origPackage = bp.sourcePackage;
16825                            return;
16826                        } else {
16827                            Slog.w(TAG, "Package " + pkg.packageName
16828                                    + " attempting to redeclare system permission "
16829                                    + perm.info.name + "; ignoring new declaration");
16830                            pkg.permissions.remove(i);
16831                        }
16832                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16833                        // Prevent apps to change protection level to dangerous from any other
16834                        // type as this would allow a privilege escalation where an app adds a
16835                        // normal/signature permission in other app's group and later redefines
16836                        // it as dangerous leading to the group auto-grant.
16837                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16838                                == PermissionInfo.PROTECTION_DANGEROUS) {
16839                            if (bp != null && !bp.isRuntime()) {
16840                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16841                                        + "non-runtime permission " + perm.info.name
16842                                        + " to runtime; keeping old protection level");
16843                                perm.info.protectionLevel = bp.protectionLevel;
16844                            }
16845                        }
16846                    }
16847                }
16848            }
16849        }
16850
16851        if (systemApp) {
16852            if (onExternal) {
16853                // Abort update; system app can't be replaced with app on sdcard
16854                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16855                        "Cannot install updates to system apps on sdcard");
16856                return;
16857            } else if (instantApp) {
16858                // Abort update; system app can't be replaced with an instant app
16859                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16860                        "Cannot update a system app with an instant app");
16861                return;
16862            }
16863        }
16864
16865        if (args.move != null) {
16866            // We did an in-place move, so dex is ready to roll
16867            scanFlags |= SCAN_NO_DEX;
16868            scanFlags |= SCAN_MOVE;
16869
16870            synchronized (mPackages) {
16871                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16872                if (ps == null) {
16873                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16874                            "Missing settings for moved package " + pkgName);
16875                }
16876
16877                // We moved the entire application as-is, so bring over the
16878                // previously derived ABI information.
16879                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16880                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16881            }
16882
16883        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16884            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16885            scanFlags |= SCAN_NO_DEX;
16886
16887            try {
16888                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16889                    args.abiOverride : pkg.cpuAbiOverride);
16890                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16891                        true /*extractLibs*/, mAppLib32InstallDir);
16892            } catch (PackageManagerException pme) {
16893                Slog.e(TAG, "Error deriving application ABI", pme);
16894                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16895                return;
16896            }
16897
16898            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16899            // Do not run PackageDexOptimizer through the local performDexOpt
16900            // method because `pkg` may not be in `mPackages` yet.
16901            //
16902            // Also, don't fail application installs if the dexopt step fails.
16903            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16904                    null /* instructionSets */, false /* checkProfiles */,
16905                    getCompilerFilterForReason(REASON_INSTALL),
16906                    getOrCreateCompilerPackageStats(pkg));
16907            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16908
16909            // Notify BackgroundDexOptJobService that the package has been changed.
16910            // If this is an update of a package which used to fail to compile,
16911            // BDOS will remove it from its blacklist.
16912            // TODO: Layering violation
16913            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16914        }
16915
16916        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16917            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16918            return;
16919        }
16920
16921        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16922
16923        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16924                "installPackageLI")) {
16925            if (replace) {
16926                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16927                    // Static libs have a synthetic package name containing the version
16928                    // and cannot be updated as an update would get a new package name,
16929                    // unless this is the exact same version code which is useful for
16930                    // development.
16931                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16932                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16933                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16934                                + "static-shared libs cannot be updated");
16935                        return;
16936                    }
16937                }
16938                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16939                        installerPackageName, res, args.installReason);
16940            } else {
16941                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16942                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16943            }
16944        }
16945        synchronized (mPackages) {
16946            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16947            if (ps != null) {
16948                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16949            }
16950
16951            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16952            for (int i = 0; i < childCount; i++) {
16953                PackageParser.Package childPkg = pkg.childPackages.get(i);
16954                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16955                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16956                if (childPs != null) {
16957                    childRes.newUsers = childPs.queryInstalledUsers(
16958                            sUserManager.getUserIds(), true);
16959                }
16960            }
16961
16962            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16963                updateSequenceNumberLP(pkgName, res.newUsers);
16964            }
16965        }
16966    }
16967
16968    private void startIntentFilterVerifications(int userId, boolean replacing,
16969            PackageParser.Package pkg) {
16970        if (mIntentFilterVerifierComponent == null) {
16971            Slog.w(TAG, "No IntentFilter verification will not be done as "
16972                    + "there is no IntentFilterVerifier available!");
16973            return;
16974        }
16975
16976        final int verifierUid = getPackageUid(
16977                mIntentFilterVerifierComponent.getPackageName(),
16978                MATCH_DEBUG_TRIAGED_MISSING,
16979                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16980
16981        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16982        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16983        mHandler.sendMessage(msg);
16984
16985        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16986        for (int i = 0; i < childCount; i++) {
16987            PackageParser.Package childPkg = pkg.childPackages.get(i);
16988            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16989            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16990            mHandler.sendMessage(msg);
16991        }
16992    }
16993
16994    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16995            PackageParser.Package pkg) {
16996        int size = pkg.activities.size();
16997        if (size == 0) {
16998            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16999                    "No activity, so no need to verify any IntentFilter!");
17000            return;
17001        }
17002
17003        final boolean hasDomainURLs = hasDomainURLs(pkg);
17004        if (!hasDomainURLs) {
17005            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17006                    "No domain URLs, so no need to verify any IntentFilter!");
17007            return;
17008        }
17009
17010        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17011                + " if any IntentFilter from the " + size
17012                + " Activities needs verification ...");
17013
17014        int count = 0;
17015        final String packageName = pkg.packageName;
17016
17017        synchronized (mPackages) {
17018            // If this is a new install and we see that we've already run verification for this
17019            // package, we have nothing to do: it means the state was restored from backup.
17020            if (!replacing) {
17021                IntentFilterVerificationInfo ivi =
17022                        mSettings.getIntentFilterVerificationLPr(packageName);
17023                if (ivi != null) {
17024                    if (DEBUG_DOMAIN_VERIFICATION) {
17025                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17026                                + ivi.getStatusString());
17027                    }
17028                    return;
17029                }
17030            }
17031
17032            // If any filters need to be verified, then all need to be.
17033            boolean needToVerify = false;
17034            for (PackageParser.Activity a : pkg.activities) {
17035                for (ActivityIntentInfo filter : a.intents) {
17036                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17037                        if (DEBUG_DOMAIN_VERIFICATION) {
17038                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17039                        }
17040                        needToVerify = true;
17041                        break;
17042                    }
17043                }
17044            }
17045
17046            if (needToVerify) {
17047                final int verificationId = mIntentFilterVerificationToken++;
17048                for (PackageParser.Activity a : pkg.activities) {
17049                    for (ActivityIntentInfo filter : a.intents) {
17050                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17051                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17052                                    "Verification needed for IntentFilter:" + filter.toString());
17053                            mIntentFilterVerifier.addOneIntentFilterVerification(
17054                                    verifierUid, userId, verificationId, filter, packageName);
17055                            count++;
17056                        }
17057                    }
17058                }
17059            }
17060        }
17061
17062        if (count > 0) {
17063            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17064                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17065                    +  " for userId:" + userId);
17066            mIntentFilterVerifier.startVerifications(userId);
17067        } else {
17068            if (DEBUG_DOMAIN_VERIFICATION) {
17069                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17070            }
17071        }
17072    }
17073
17074    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17075        final ComponentName cn  = filter.activity.getComponentName();
17076        final String packageName = cn.getPackageName();
17077
17078        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17079                packageName);
17080        if (ivi == null) {
17081            return true;
17082        }
17083        int status = ivi.getStatus();
17084        switch (status) {
17085            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17086            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17087                return true;
17088
17089            default:
17090                // Nothing to do
17091                return false;
17092        }
17093    }
17094
17095    private static boolean isMultiArch(ApplicationInfo info) {
17096        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17097    }
17098
17099    private static boolean isExternal(PackageParser.Package pkg) {
17100        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17101    }
17102
17103    private static boolean isExternal(PackageSetting ps) {
17104        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17105    }
17106
17107    private static boolean isSystemApp(PackageParser.Package pkg) {
17108        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17109    }
17110
17111    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17112        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17113    }
17114
17115    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17116        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17117    }
17118
17119    private static boolean isSystemApp(PackageSetting ps) {
17120        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17121    }
17122
17123    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17124        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17125    }
17126
17127    private int packageFlagsToInstallFlags(PackageSetting ps) {
17128        int installFlags = 0;
17129        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17130            // This existing package was an external ASEC install when we have
17131            // the external flag without a UUID
17132            installFlags |= PackageManager.INSTALL_EXTERNAL;
17133        }
17134        if (ps.isForwardLocked()) {
17135            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17136        }
17137        return installFlags;
17138    }
17139
17140    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17141        if (isExternal(pkg)) {
17142            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17143                return StorageManager.UUID_PRIMARY_PHYSICAL;
17144            } else {
17145                return pkg.volumeUuid;
17146            }
17147        } else {
17148            return StorageManager.UUID_PRIVATE_INTERNAL;
17149        }
17150    }
17151
17152    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17153        if (isExternal(pkg)) {
17154            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17155                return mSettings.getExternalVersion();
17156            } else {
17157                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17158            }
17159        } else {
17160            return mSettings.getInternalVersion();
17161        }
17162    }
17163
17164    private void deleteTempPackageFiles() {
17165        final FilenameFilter filter = new FilenameFilter() {
17166            public boolean accept(File dir, String name) {
17167                return name.startsWith("vmdl") && name.endsWith(".tmp");
17168            }
17169        };
17170        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17171            file.delete();
17172        }
17173    }
17174
17175    @Override
17176    public void deletePackageAsUser(String packageName, int versionCode,
17177            IPackageDeleteObserver observer, int userId, int flags) {
17178        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17179                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17180    }
17181
17182    @Override
17183    public void deletePackageVersioned(VersionedPackage versionedPackage,
17184            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17185        mContext.enforceCallingOrSelfPermission(
17186                android.Manifest.permission.DELETE_PACKAGES, null);
17187        Preconditions.checkNotNull(versionedPackage);
17188        Preconditions.checkNotNull(observer);
17189        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17190                PackageManager.VERSION_CODE_HIGHEST,
17191                Integer.MAX_VALUE, "versionCode must be >= -1");
17192
17193        final String packageName = versionedPackage.getPackageName();
17194        // TODO: We will change version code to long, so in the new API it is long
17195        final int versionCode = (int) versionedPackage.getVersionCode();
17196        final String internalPackageName;
17197        synchronized (mPackages) {
17198            // Normalize package name to handle renamed packages and static libs
17199            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17200                    // TODO: We will change version code to long, so in the new API it is long
17201                    (int) versionedPackage.getVersionCode());
17202        }
17203
17204        final int uid = Binder.getCallingUid();
17205        if (!isOrphaned(internalPackageName)
17206                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17207            try {
17208                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17209                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17210                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17211                observer.onUserActionRequired(intent);
17212            } catch (RemoteException re) {
17213            }
17214            return;
17215        }
17216        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17217        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17218        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17219            mContext.enforceCallingOrSelfPermission(
17220                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17221                    "deletePackage for user " + userId);
17222        }
17223
17224        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17225            try {
17226                observer.onPackageDeleted(packageName,
17227                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17228            } catch (RemoteException re) {
17229            }
17230            return;
17231        }
17232
17233        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17234            try {
17235                observer.onPackageDeleted(packageName,
17236                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17237            } catch (RemoteException re) {
17238            }
17239            return;
17240        }
17241
17242        if (DEBUG_REMOVE) {
17243            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17244                    + " deleteAllUsers: " + deleteAllUsers + " version="
17245                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17246                    ? "VERSION_CODE_HIGHEST" : versionCode));
17247        }
17248        // Queue up an async operation since the package deletion may take a little while.
17249        mHandler.post(new Runnable() {
17250            public void run() {
17251                mHandler.removeCallbacks(this);
17252                int returnCode;
17253                if (!deleteAllUsers) {
17254                    returnCode = deletePackageX(internalPackageName, versionCode,
17255                            userId, deleteFlags);
17256                } else {
17257                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17258                            internalPackageName, users);
17259                    // If nobody is blocking uninstall, proceed with delete for all users
17260                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17261                        returnCode = deletePackageX(internalPackageName, versionCode,
17262                                userId, deleteFlags);
17263                    } else {
17264                        // Otherwise uninstall individually for users with blockUninstalls=false
17265                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17266                        for (int userId : users) {
17267                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17268                                returnCode = deletePackageX(internalPackageName, versionCode,
17269                                        userId, userFlags);
17270                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17271                                    Slog.w(TAG, "Package delete failed for user " + userId
17272                                            + ", returnCode " + returnCode);
17273                                }
17274                            }
17275                        }
17276                        // The app has only been marked uninstalled for certain users.
17277                        // We still need to report that delete was blocked
17278                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17279                    }
17280                }
17281                try {
17282                    observer.onPackageDeleted(packageName, returnCode, null);
17283                } catch (RemoteException e) {
17284                    Log.i(TAG, "Observer no longer exists.");
17285                } //end catch
17286            } //end run
17287        });
17288    }
17289
17290    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17291        if (pkg.staticSharedLibName != null) {
17292            return pkg.manifestPackageName;
17293        }
17294        return pkg.packageName;
17295    }
17296
17297    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17298        // Handle renamed packages
17299        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17300        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17301
17302        // Is this a static library?
17303        SparseArray<SharedLibraryEntry> versionedLib =
17304                mStaticLibsByDeclaringPackage.get(packageName);
17305        if (versionedLib == null || versionedLib.size() <= 0) {
17306            return packageName;
17307        }
17308
17309        // Figure out which lib versions the caller can see
17310        SparseIntArray versionsCallerCanSee = null;
17311        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17312        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17313                && callingAppId != Process.ROOT_UID) {
17314            versionsCallerCanSee = new SparseIntArray();
17315            String libName = versionedLib.valueAt(0).info.getName();
17316            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17317            if (uidPackages != null) {
17318                for (String uidPackage : uidPackages) {
17319                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17320                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17321                    if (libIdx >= 0) {
17322                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17323                        versionsCallerCanSee.append(libVersion, libVersion);
17324                    }
17325                }
17326            }
17327        }
17328
17329        // Caller can see nothing - done
17330        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17331            return packageName;
17332        }
17333
17334        // Find the version the caller can see and the app version code
17335        SharedLibraryEntry highestVersion = null;
17336        final int versionCount = versionedLib.size();
17337        for (int i = 0; i < versionCount; i++) {
17338            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17339            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17340                    libEntry.info.getVersion()) < 0) {
17341                continue;
17342            }
17343            // TODO: We will change version code to long, so in the new API it is long
17344            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17345            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17346                if (libVersionCode == versionCode) {
17347                    return libEntry.apk;
17348                }
17349            } else if (highestVersion == null) {
17350                highestVersion = libEntry;
17351            } else if (libVersionCode  > highestVersion.info
17352                    .getDeclaringPackage().getVersionCode()) {
17353                highestVersion = libEntry;
17354            }
17355        }
17356
17357        if (highestVersion != null) {
17358            return highestVersion.apk;
17359        }
17360
17361        return packageName;
17362    }
17363
17364    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17365        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17366              || callingUid == Process.SYSTEM_UID) {
17367            return true;
17368        }
17369        final int callingUserId = UserHandle.getUserId(callingUid);
17370        // If the caller installed the pkgName, then allow it to silently uninstall.
17371        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17372            return true;
17373        }
17374
17375        // Allow package verifier to silently uninstall.
17376        if (mRequiredVerifierPackage != null &&
17377                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17378            return true;
17379        }
17380
17381        // Allow package uninstaller to silently uninstall.
17382        if (mRequiredUninstallerPackage != null &&
17383                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17384            return true;
17385        }
17386
17387        // Allow storage manager to silently uninstall.
17388        if (mStorageManagerPackage != null &&
17389                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17390            return true;
17391        }
17392        return false;
17393    }
17394
17395    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17396        int[] result = EMPTY_INT_ARRAY;
17397        for (int userId : userIds) {
17398            if (getBlockUninstallForUser(packageName, userId)) {
17399                result = ArrayUtils.appendInt(result, userId);
17400            }
17401        }
17402        return result;
17403    }
17404
17405    @Override
17406    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17407        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17408    }
17409
17410    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17411        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17412                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17413        try {
17414            if (dpm != null) {
17415                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17416                        /* callingUserOnly =*/ false);
17417                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17418                        : deviceOwnerComponentName.getPackageName();
17419                // Does the package contains the device owner?
17420                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17421                // this check is probably not needed, since DO should be registered as a device
17422                // admin on some user too. (Original bug for this: b/17657954)
17423                if (packageName.equals(deviceOwnerPackageName)) {
17424                    return true;
17425                }
17426                // Does it contain a device admin for any user?
17427                int[] users;
17428                if (userId == UserHandle.USER_ALL) {
17429                    users = sUserManager.getUserIds();
17430                } else {
17431                    users = new int[]{userId};
17432                }
17433                for (int i = 0; i < users.length; ++i) {
17434                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17435                        return true;
17436                    }
17437                }
17438            }
17439        } catch (RemoteException e) {
17440        }
17441        return false;
17442    }
17443
17444    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17445        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17446    }
17447
17448    /**
17449     *  This method is an internal method that could be get invoked either
17450     *  to delete an installed package or to clean up a failed installation.
17451     *  After deleting an installed package, a broadcast is sent to notify any
17452     *  listeners that the package has been removed. For cleaning up a failed
17453     *  installation, the broadcast is not necessary since the package's
17454     *  installation wouldn't have sent the initial broadcast either
17455     *  The key steps in deleting a package are
17456     *  deleting the package information in internal structures like mPackages,
17457     *  deleting the packages base directories through installd
17458     *  updating mSettings to reflect current status
17459     *  persisting settings for later use
17460     *  sending a broadcast if necessary
17461     */
17462    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17463        final PackageRemovedInfo info = new PackageRemovedInfo();
17464        final boolean res;
17465
17466        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17467                ? UserHandle.USER_ALL : userId;
17468
17469        if (isPackageDeviceAdmin(packageName, removeUser)) {
17470            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17471            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17472        }
17473
17474        PackageSetting uninstalledPs = null;
17475
17476        // for the uninstall-updates case and restricted profiles, remember the per-
17477        // user handle installed state
17478        int[] allUsers;
17479        synchronized (mPackages) {
17480            uninstalledPs = mSettings.mPackages.get(packageName);
17481            if (uninstalledPs == null) {
17482                Slog.w(TAG, "Not removing non-existent package " + packageName);
17483                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17484            }
17485
17486            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17487                    && uninstalledPs.versionCode != versionCode) {
17488                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17489                        + uninstalledPs.versionCode + " != " + versionCode);
17490                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17491            }
17492
17493            // Static shared libs can be declared by any package, so let us not
17494            // allow removing a package if it provides a lib others depend on.
17495            PackageParser.Package pkg = mPackages.get(packageName);
17496            if (pkg != null && pkg.staticSharedLibName != null) {
17497                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17498                        pkg.staticSharedLibVersion);
17499                if (libEntry != null) {
17500                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17501                            libEntry.info, 0, userId);
17502                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17503                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17504                                + " hosting lib " + libEntry.info.getName() + " version "
17505                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17506                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17507                    }
17508                }
17509            }
17510
17511            allUsers = sUserManager.getUserIds();
17512            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17513        }
17514
17515        final int freezeUser;
17516        if (isUpdatedSystemApp(uninstalledPs)
17517                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17518            // We're downgrading a system app, which will apply to all users, so
17519            // freeze them all during the downgrade
17520            freezeUser = UserHandle.USER_ALL;
17521        } else {
17522            freezeUser = removeUser;
17523        }
17524
17525        synchronized (mInstallLock) {
17526            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17527            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17528                    deleteFlags, "deletePackageX")) {
17529                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17530                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17531            }
17532            synchronized (mPackages) {
17533                if (res) {
17534                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17535                            info.removedUsers);
17536                    updateSequenceNumberLP(packageName, info.removedUsers);
17537                }
17538            }
17539        }
17540
17541        if (res) {
17542            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17543            info.sendPackageRemovedBroadcasts(killApp);
17544            info.sendSystemPackageUpdatedBroadcasts();
17545            info.sendSystemPackageAppearedBroadcasts();
17546        }
17547        // Force a gc here.
17548        Runtime.getRuntime().gc();
17549        // Delete the resources here after sending the broadcast to let
17550        // other processes clean up before deleting resources.
17551        if (info.args != null) {
17552            synchronized (mInstallLock) {
17553                info.args.doPostDeleteLI(true);
17554            }
17555        }
17556
17557        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17558    }
17559
17560    class PackageRemovedInfo {
17561        String removedPackage;
17562        int uid = -1;
17563        int removedAppId = -1;
17564        int[] origUsers;
17565        int[] removedUsers = null;
17566        SparseArray<Integer> installReasons;
17567        boolean isRemovedPackageSystemUpdate = false;
17568        boolean isUpdate;
17569        boolean dataRemoved;
17570        boolean removedForAllUsers;
17571        boolean isStaticSharedLib;
17572        // Clean up resources deleted packages.
17573        InstallArgs args = null;
17574        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17575        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17576
17577        void sendPackageRemovedBroadcasts(boolean killApp) {
17578            sendPackageRemovedBroadcastInternal(killApp);
17579            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17580            for (int i = 0; i < childCount; i++) {
17581                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17582                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17583            }
17584        }
17585
17586        void sendSystemPackageUpdatedBroadcasts() {
17587            if (isRemovedPackageSystemUpdate) {
17588                sendSystemPackageUpdatedBroadcastsInternal();
17589                final int childCount = (removedChildPackages != null)
17590                        ? removedChildPackages.size() : 0;
17591                for (int i = 0; i < childCount; i++) {
17592                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17593                    if (childInfo.isRemovedPackageSystemUpdate) {
17594                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17595                    }
17596                }
17597            }
17598        }
17599
17600        void sendSystemPackageAppearedBroadcasts() {
17601            final int packageCount = (appearedChildPackages != null)
17602                    ? appearedChildPackages.size() : 0;
17603            for (int i = 0; i < packageCount; i++) {
17604                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17605                sendPackageAddedForNewUsers(installedInfo.name, true,
17606                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17607            }
17608        }
17609
17610        private void sendSystemPackageUpdatedBroadcastsInternal() {
17611            Bundle extras = new Bundle(2);
17612            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17613            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17614            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17615                    extras, 0, null, null, null);
17616            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17617                    extras, 0, null, null, null);
17618            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17619                    null, 0, removedPackage, null, null);
17620        }
17621
17622        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17623            // Don't send static shared library removal broadcasts as these
17624            // libs are visible only the the apps that depend on them an one
17625            // cannot remove the library if it has a dependency.
17626            if (isStaticSharedLib) {
17627                return;
17628            }
17629            Bundle extras = new Bundle(2);
17630            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17631            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17632            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17633            if (isUpdate || isRemovedPackageSystemUpdate) {
17634                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17635            }
17636            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17637            if (removedPackage != null) {
17638                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17639                        extras, 0, null, null, removedUsers);
17640                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17641                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17642                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17643                            null, null, removedUsers);
17644                }
17645            }
17646            if (removedAppId >= 0) {
17647                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17648                        removedUsers);
17649            }
17650        }
17651    }
17652
17653    /*
17654     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17655     * flag is not set, the data directory is removed as well.
17656     * make sure this flag is set for partially installed apps. If not its meaningless to
17657     * delete a partially installed application.
17658     */
17659    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17660            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17661        String packageName = ps.name;
17662        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17663        // Retrieve object to delete permissions for shared user later on
17664        final PackageParser.Package deletedPkg;
17665        final PackageSetting deletedPs;
17666        // reader
17667        synchronized (mPackages) {
17668            deletedPkg = mPackages.get(packageName);
17669            deletedPs = mSettings.mPackages.get(packageName);
17670            if (outInfo != null) {
17671                outInfo.removedPackage = packageName;
17672                outInfo.isStaticSharedLib = deletedPkg != null
17673                        && deletedPkg.staticSharedLibName != null;
17674                outInfo.removedUsers = deletedPs != null
17675                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17676                        : null;
17677            }
17678        }
17679
17680        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17681
17682        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17683            final PackageParser.Package resolvedPkg;
17684            if (deletedPkg != null) {
17685                resolvedPkg = deletedPkg;
17686            } else {
17687                // We don't have a parsed package when it lives on an ejected
17688                // adopted storage device, so fake something together
17689                resolvedPkg = new PackageParser.Package(ps.name);
17690                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17691            }
17692            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17693                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17694            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17695            if (outInfo != null) {
17696                outInfo.dataRemoved = true;
17697            }
17698            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17699        }
17700
17701        int removedAppId = -1;
17702
17703        // writer
17704        synchronized (mPackages) {
17705            boolean installedStateChanged = false;
17706            if (deletedPs != null) {
17707                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17708                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17709                    clearDefaultBrowserIfNeeded(packageName);
17710                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17711                    removedAppId = mSettings.removePackageLPw(packageName);
17712                    if (outInfo != null) {
17713                        outInfo.removedAppId = removedAppId;
17714                    }
17715                    updatePermissionsLPw(deletedPs.name, null, 0);
17716                    if (deletedPs.sharedUser != null) {
17717                        // Remove permissions associated with package. Since runtime
17718                        // permissions are per user we have to kill the removed package
17719                        // or packages running under the shared user of the removed
17720                        // package if revoking the permissions requested only by the removed
17721                        // package is successful and this causes a change in gids.
17722                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17723                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17724                                    userId);
17725                            if (userIdToKill == UserHandle.USER_ALL
17726                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17727                                // If gids changed for this user, kill all affected packages.
17728                                mHandler.post(new Runnable() {
17729                                    @Override
17730                                    public void run() {
17731                                        // This has to happen with no lock held.
17732                                        killApplication(deletedPs.name, deletedPs.appId,
17733                                                KILL_APP_REASON_GIDS_CHANGED);
17734                                    }
17735                                });
17736                                break;
17737                            }
17738                        }
17739                    }
17740                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17741                }
17742                // make sure to preserve per-user disabled state if this removal was just
17743                // a downgrade of a system app to the factory package
17744                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17745                    if (DEBUG_REMOVE) {
17746                        Slog.d(TAG, "Propagating install state across downgrade");
17747                    }
17748                    for (int userId : allUserHandles) {
17749                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17750                        if (DEBUG_REMOVE) {
17751                            Slog.d(TAG, "    user " + userId + " => " + installed);
17752                        }
17753                        if (installed != ps.getInstalled(userId)) {
17754                            installedStateChanged = true;
17755                        }
17756                        ps.setInstalled(installed, userId);
17757                    }
17758                }
17759            }
17760            // can downgrade to reader
17761            if (writeSettings) {
17762                // Save settings now
17763                mSettings.writeLPr();
17764            }
17765            if (installedStateChanged) {
17766                mSettings.writeKernelMappingLPr(ps);
17767            }
17768        }
17769        if (removedAppId != -1) {
17770            // A user ID was deleted here. Go through all users and remove it
17771            // from KeyStore.
17772            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17773        }
17774    }
17775
17776    static boolean locationIsPrivileged(File path) {
17777        try {
17778            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17779                    .getCanonicalPath();
17780            return path.getCanonicalPath().startsWith(privilegedAppDir);
17781        } catch (IOException e) {
17782            Slog.e(TAG, "Unable to access code path " + path);
17783        }
17784        return false;
17785    }
17786
17787    /*
17788     * Tries to delete system package.
17789     */
17790    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17791            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17792            boolean writeSettings) {
17793        if (deletedPs.parentPackageName != null) {
17794            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17795            return false;
17796        }
17797
17798        final boolean applyUserRestrictions
17799                = (allUserHandles != null) && (outInfo.origUsers != null);
17800        final PackageSetting disabledPs;
17801        // Confirm if the system package has been updated
17802        // An updated system app can be deleted. This will also have to restore
17803        // the system pkg from system partition
17804        // reader
17805        synchronized (mPackages) {
17806            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17807        }
17808
17809        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17810                + " disabledPs=" + disabledPs);
17811
17812        if (disabledPs == null) {
17813            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17814            return false;
17815        } else if (DEBUG_REMOVE) {
17816            Slog.d(TAG, "Deleting system pkg from data partition");
17817        }
17818
17819        if (DEBUG_REMOVE) {
17820            if (applyUserRestrictions) {
17821                Slog.d(TAG, "Remembering install states:");
17822                for (int userId : allUserHandles) {
17823                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17824                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17825                }
17826            }
17827        }
17828
17829        // Delete the updated package
17830        outInfo.isRemovedPackageSystemUpdate = true;
17831        if (outInfo.removedChildPackages != null) {
17832            final int childCount = (deletedPs.childPackageNames != null)
17833                    ? deletedPs.childPackageNames.size() : 0;
17834            for (int i = 0; i < childCount; i++) {
17835                String childPackageName = deletedPs.childPackageNames.get(i);
17836                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17837                        .contains(childPackageName)) {
17838                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17839                            childPackageName);
17840                    if (childInfo != null) {
17841                        childInfo.isRemovedPackageSystemUpdate = true;
17842                    }
17843                }
17844            }
17845        }
17846
17847        if (disabledPs.versionCode < deletedPs.versionCode) {
17848            // Delete data for downgrades
17849            flags &= ~PackageManager.DELETE_KEEP_DATA;
17850        } else {
17851            // Preserve data by setting flag
17852            flags |= PackageManager.DELETE_KEEP_DATA;
17853        }
17854
17855        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17856                outInfo, writeSettings, disabledPs.pkg);
17857        if (!ret) {
17858            return false;
17859        }
17860
17861        // writer
17862        synchronized (mPackages) {
17863            // Reinstate the old system package
17864            enableSystemPackageLPw(disabledPs.pkg);
17865            // Remove any native libraries from the upgraded package.
17866            removeNativeBinariesLI(deletedPs);
17867        }
17868
17869        // Install the system package
17870        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17871        int parseFlags = mDefParseFlags
17872                | PackageParser.PARSE_MUST_BE_APK
17873                | PackageParser.PARSE_IS_SYSTEM
17874                | PackageParser.PARSE_IS_SYSTEM_DIR;
17875        if (locationIsPrivileged(disabledPs.codePath)) {
17876            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17877        }
17878
17879        final PackageParser.Package newPkg;
17880        try {
17881            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17882                0 /* currentTime */, null);
17883        } catch (PackageManagerException e) {
17884            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17885                    + e.getMessage());
17886            return false;
17887        }
17888
17889        try {
17890            // update shared libraries for the newly re-installed system package
17891            updateSharedLibrariesLPr(newPkg, null);
17892        } catch (PackageManagerException e) {
17893            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17894        }
17895
17896        prepareAppDataAfterInstallLIF(newPkg);
17897
17898        // writer
17899        synchronized (mPackages) {
17900            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17901
17902            // Propagate the permissions state as we do not want to drop on the floor
17903            // runtime permissions. The update permissions method below will take
17904            // care of removing obsolete permissions and grant install permissions.
17905            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17906            updatePermissionsLPw(newPkg.packageName, newPkg,
17907                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17908
17909            if (applyUserRestrictions) {
17910                boolean installedStateChanged = false;
17911                if (DEBUG_REMOVE) {
17912                    Slog.d(TAG, "Propagating install state across reinstall");
17913                }
17914                for (int userId : allUserHandles) {
17915                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17916                    if (DEBUG_REMOVE) {
17917                        Slog.d(TAG, "    user " + userId + " => " + installed);
17918                    }
17919                    if (installed != ps.getInstalled(userId)) {
17920                        installedStateChanged = true;
17921                    }
17922                    ps.setInstalled(installed, userId);
17923
17924                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17925                }
17926                // Regardless of writeSettings we need to ensure that this restriction
17927                // state propagation is persisted
17928                mSettings.writeAllUsersPackageRestrictionsLPr();
17929                if (installedStateChanged) {
17930                    mSettings.writeKernelMappingLPr(ps);
17931                }
17932            }
17933            // can downgrade to reader here
17934            if (writeSettings) {
17935                mSettings.writeLPr();
17936            }
17937        }
17938        return true;
17939    }
17940
17941    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17942            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17943            PackageRemovedInfo outInfo, boolean writeSettings,
17944            PackageParser.Package replacingPackage) {
17945        synchronized (mPackages) {
17946            if (outInfo != null) {
17947                outInfo.uid = ps.appId;
17948            }
17949
17950            if (outInfo != null && outInfo.removedChildPackages != null) {
17951                final int childCount = (ps.childPackageNames != null)
17952                        ? ps.childPackageNames.size() : 0;
17953                for (int i = 0; i < childCount; i++) {
17954                    String childPackageName = ps.childPackageNames.get(i);
17955                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17956                    if (childPs == null) {
17957                        return false;
17958                    }
17959                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17960                            childPackageName);
17961                    if (childInfo != null) {
17962                        childInfo.uid = childPs.appId;
17963                    }
17964                }
17965            }
17966        }
17967
17968        // Delete package data from internal structures and also remove data if flag is set
17969        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17970
17971        // Delete the child packages data
17972        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17973        for (int i = 0; i < childCount; i++) {
17974            PackageSetting childPs;
17975            synchronized (mPackages) {
17976                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17977            }
17978            if (childPs != null) {
17979                PackageRemovedInfo childOutInfo = (outInfo != null
17980                        && outInfo.removedChildPackages != null)
17981                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17982                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17983                        && (replacingPackage != null
17984                        && !replacingPackage.hasChildPackage(childPs.name))
17985                        ? flags & ~DELETE_KEEP_DATA : flags;
17986                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17987                        deleteFlags, writeSettings);
17988            }
17989        }
17990
17991        // Delete application code and resources only for parent packages
17992        if (ps.parentPackageName == null) {
17993            if (deleteCodeAndResources && (outInfo != null)) {
17994                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17995                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17996                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17997            }
17998        }
17999
18000        return true;
18001    }
18002
18003    @Override
18004    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18005            int userId) {
18006        mContext.enforceCallingOrSelfPermission(
18007                android.Manifest.permission.DELETE_PACKAGES, null);
18008        synchronized (mPackages) {
18009            PackageSetting ps = mSettings.mPackages.get(packageName);
18010            if (ps == null) {
18011                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18012                return false;
18013            }
18014            // Cannot block uninstall of static shared libs as they are
18015            // considered a part of the using app (emulating static linking).
18016            // Also static libs are installed always on internal storage.
18017            PackageParser.Package pkg = mPackages.get(packageName);
18018            if (pkg != null && pkg.staticSharedLibName != null) {
18019                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18020                        + " providing static shared library: " + pkg.staticSharedLibName);
18021                return false;
18022            }
18023            if (!ps.getInstalled(userId)) {
18024                // Can't block uninstall for an app that is not installed or enabled.
18025                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18026                return false;
18027            }
18028            ps.setBlockUninstall(blockUninstall, userId);
18029            mSettings.writePackageRestrictionsLPr(userId);
18030        }
18031        return true;
18032    }
18033
18034    @Override
18035    public boolean getBlockUninstallForUser(String packageName, int userId) {
18036        synchronized (mPackages) {
18037            PackageSetting ps = mSettings.mPackages.get(packageName);
18038            if (ps == null) {
18039                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18040                return false;
18041            }
18042            return ps.getBlockUninstall(userId);
18043        }
18044    }
18045
18046    @Override
18047    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18048        int callingUid = Binder.getCallingUid();
18049        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18050            throw new SecurityException(
18051                    "setRequiredForSystemUser can only be run by the system or root");
18052        }
18053        synchronized (mPackages) {
18054            PackageSetting ps = mSettings.mPackages.get(packageName);
18055            if (ps == null) {
18056                Log.w(TAG, "Package doesn't exist: " + packageName);
18057                return false;
18058            }
18059            if (systemUserApp) {
18060                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18061            } else {
18062                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18063            }
18064            mSettings.writeLPr();
18065        }
18066        return true;
18067    }
18068
18069    /*
18070     * This method handles package deletion in general
18071     */
18072    private boolean deletePackageLIF(String packageName, UserHandle user,
18073            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18074            PackageRemovedInfo outInfo, boolean writeSettings,
18075            PackageParser.Package replacingPackage) {
18076        if (packageName == null) {
18077            Slog.w(TAG, "Attempt to delete null packageName.");
18078            return false;
18079        }
18080
18081        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18082
18083        PackageSetting ps;
18084        synchronized (mPackages) {
18085            ps = mSettings.mPackages.get(packageName);
18086            if (ps == null) {
18087                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18088                return false;
18089            }
18090
18091            if (ps.parentPackageName != null && (!isSystemApp(ps)
18092                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18093                if (DEBUG_REMOVE) {
18094                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18095                            + ((user == null) ? UserHandle.USER_ALL : user));
18096                }
18097                final int removedUserId = (user != null) ? user.getIdentifier()
18098                        : UserHandle.USER_ALL;
18099                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18100                    return false;
18101                }
18102                markPackageUninstalledForUserLPw(ps, user);
18103                scheduleWritePackageRestrictionsLocked(user);
18104                return true;
18105            }
18106        }
18107
18108        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18109                && user.getIdentifier() != UserHandle.USER_ALL)) {
18110            // The caller is asking that the package only be deleted for a single
18111            // user.  To do this, we just mark its uninstalled state and delete
18112            // its data. If this is a system app, we only allow this to happen if
18113            // they have set the special DELETE_SYSTEM_APP which requests different
18114            // semantics than normal for uninstalling system apps.
18115            markPackageUninstalledForUserLPw(ps, user);
18116
18117            if (!isSystemApp(ps)) {
18118                // Do not uninstall the APK if an app should be cached
18119                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18120                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18121                    // Other user still have this package installed, so all
18122                    // we need to do is clear this user's data and save that
18123                    // it is uninstalled.
18124                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18125                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18126                        return false;
18127                    }
18128                    scheduleWritePackageRestrictionsLocked(user);
18129                    return true;
18130                } else {
18131                    // We need to set it back to 'installed' so the uninstall
18132                    // broadcasts will be sent correctly.
18133                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18134                    ps.setInstalled(true, user.getIdentifier());
18135                    mSettings.writeKernelMappingLPr(ps);
18136                }
18137            } else {
18138                // This is a system app, so we assume that the
18139                // other users still have this package installed, so all
18140                // we need to do is clear this user's data and save that
18141                // it is uninstalled.
18142                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18143                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18144                    return false;
18145                }
18146                scheduleWritePackageRestrictionsLocked(user);
18147                return true;
18148            }
18149        }
18150
18151        // If we are deleting a composite package for all users, keep track
18152        // of result for each child.
18153        if (ps.childPackageNames != null && outInfo != null) {
18154            synchronized (mPackages) {
18155                final int childCount = ps.childPackageNames.size();
18156                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18157                for (int i = 0; i < childCount; i++) {
18158                    String childPackageName = ps.childPackageNames.get(i);
18159                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18160                    childInfo.removedPackage = childPackageName;
18161                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18162                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18163                    if (childPs != null) {
18164                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18165                    }
18166                }
18167            }
18168        }
18169
18170        boolean ret = false;
18171        if (isSystemApp(ps)) {
18172            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18173            // When an updated system application is deleted we delete the existing resources
18174            // as well and fall back to existing code in system partition
18175            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18176        } else {
18177            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18178            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18179                    outInfo, writeSettings, replacingPackage);
18180        }
18181
18182        // Take a note whether we deleted the package for all users
18183        if (outInfo != null) {
18184            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18185            if (outInfo.removedChildPackages != null) {
18186                synchronized (mPackages) {
18187                    final int childCount = outInfo.removedChildPackages.size();
18188                    for (int i = 0; i < childCount; i++) {
18189                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18190                        if (childInfo != null) {
18191                            childInfo.removedForAllUsers = mPackages.get(
18192                                    childInfo.removedPackage) == null;
18193                        }
18194                    }
18195                }
18196            }
18197            // If we uninstalled an update to a system app there may be some
18198            // child packages that appeared as they are declared in the system
18199            // app but were not declared in the update.
18200            if (isSystemApp(ps)) {
18201                synchronized (mPackages) {
18202                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18203                    final int childCount = (updatedPs.childPackageNames != null)
18204                            ? updatedPs.childPackageNames.size() : 0;
18205                    for (int i = 0; i < childCount; i++) {
18206                        String childPackageName = updatedPs.childPackageNames.get(i);
18207                        if (outInfo.removedChildPackages == null
18208                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18209                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18210                            if (childPs == null) {
18211                                continue;
18212                            }
18213                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18214                            installRes.name = childPackageName;
18215                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18216                            installRes.pkg = mPackages.get(childPackageName);
18217                            installRes.uid = childPs.pkg.applicationInfo.uid;
18218                            if (outInfo.appearedChildPackages == null) {
18219                                outInfo.appearedChildPackages = new ArrayMap<>();
18220                            }
18221                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18222                        }
18223                    }
18224                }
18225            }
18226        }
18227
18228        return ret;
18229    }
18230
18231    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18232        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18233                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18234        for (int nextUserId : userIds) {
18235            if (DEBUG_REMOVE) {
18236                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18237            }
18238            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18239                    false /*installed*/,
18240                    true /*stopped*/,
18241                    true /*notLaunched*/,
18242                    false /*hidden*/,
18243                    false /*suspended*/,
18244                    false /*instantApp*/,
18245                    null /*lastDisableAppCaller*/,
18246                    null /*enabledComponents*/,
18247                    null /*disabledComponents*/,
18248                    false /*blockUninstall*/,
18249                    ps.readUserState(nextUserId).domainVerificationStatus,
18250                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18251        }
18252        mSettings.writeKernelMappingLPr(ps);
18253    }
18254
18255    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18256            PackageRemovedInfo outInfo) {
18257        final PackageParser.Package pkg;
18258        synchronized (mPackages) {
18259            pkg = mPackages.get(ps.name);
18260        }
18261
18262        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18263                : new int[] {userId};
18264        for (int nextUserId : userIds) {
18265            if (DEBUG_REMOVE) {
18266                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18267                        + nextUserId);
18268            }
18269
18270            destroyAppDataLIF(pkg, userId,
18271                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18272            destroyAppProfilesLIF(pkg, userId);
18273            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18274            schedulePackageCleaning(ps.name, nextUserId, false);
18275            synchronized (mPackages) {
18276                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18277                    scheduleWritePackageRestrictionsLocked(nextUserId);
18278                }
18279                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18280            }
18281        }
18282
18283        if (outInfo != null) {
18284            outInfo.removedPackage = ps.name;
18285            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18286            outInfo.removedAppId = ps.appId;
18287            outInfo.removedUsers = userIds;
18288        }
18289
18290        return true;
18291    }
18292
18293    private final class ClearStorageConnection implements ServiceConnection {
18294        IMediaContainerService mContainerService;
18295
18296        @Override
18297        public void onServiceConnected(ComponentName name, IBinder service) {
18298            synchronized (this) {
18299                mContainerService = IMediaContainerService.Stub
18300                        .asInterface(Binder.allowBlocking(service));
18301                notifyAll();
18302            }
18303        }
18304
18305        @Override
18306        public void onServiceDisconnected(ComponentName name) {
18307        }
18308    }
18309
18310    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18311        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18312
18313        final boolean mounted;
18314        if (Environment.isExternalStorageEmulated()) {
18315            mounted = true;
18316        } else {
18317            final String status = Environment.getExternalStorageState();
18318
18319            mounted = status.equals(Environment.MEDIA_MOUNTED)
18320                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18321        }
18322
18323        if (!mounted) {
18324            return;
18325        }
18326
18327        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18328        int[] users;
18329        if (userId == UserHandle.USER_ALL) {
18330            users = sUserManager.getUserIds();
18331        } else {
18332            users = new int[] { userId };
18333        }
18334        final ClearStorageConnection conn = new ClearStorageConnection();
18335        if (mContext.bindServiceAsUser(
18336                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18337            try {
18338                for (int curUser : users) {
18339                    long timeout = SystemClock.uptimeMillis() + 5000;
18340                    synchronized (conn) {
18341                        long now;
18342                        while (conn.mContainerService == null &&
18343                                (now = SystemClock.uptimeMillis()) < timeout) {
18344                            try {
18345                                conn.wait(timeout - now);
18346                            } catch (InterruptedException e) {
18347                            }
18348                        }
18349                    }
18350                    if (conn.mContainerService == null) {
18351                        return;
18352                    }
18353
18354                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18355                    clearDirectory(conn.mContainerService,
18356                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18357                    if (allData) {
18358                        clearDirectory(conn.mContainerService,
18359                                userEnv.buildExternalStorageAppDataDirs(packageName));
18360                        clearDirectory(conn.mContainerService,
18361                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18362                    }
18363                }
18364            } finally {
18365                mContext.unbindService(conn);
18366            }
18367        }
18368    }
18369
18370    @Override
18371    public void clearApplicationProfileData(String packageName) {
18372        enforceSystemOrRoot("Only the system can clear all profile data");
18373
18374        final PackageParser.Package pkg;
18375        synchronized (mPackages) {
18376            pkg = mPackages.get(packageName);
18377        }
18378
18379        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18380            synchronized (mInstallLock) {
18381                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18382                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18383                        true /* removeBaseMarker */);
18384            }
18385        }
18386    }
18387
18388    @Override
18389    public void clearApplicationUserData(final String packageName,
18390            final IPackageDataObserver observer, final int userId) {
18391        mContext.enforceCallingOrSelfPermission(
18392                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18393
18394        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18395                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18396
18397        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18398            throw new SecurityException("Cannot clear data for a protected package: "
18399                    + packageName);
18400        }
18401        // Queue up an async operation since the package deletion may take a little while.
18402        mHandler.post(new Runnable() {
18403            public void run() {
18404                mHandler.removeCallbacks(this);
18405                final boolean succeeded;
18406                try (PackageFreezer freezer = freezePackage(packageName,
18407                        "clearApplicationUserData")) {
18408                    synchronized (mInstallLock) {
18409                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18410                    }
18411                    clearExternalStorageDataSync(packageName, userId, true);
18412                    synchronized (mPackages) {
18413                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18414                                packageName, userId);
18415                    }
18416                }
18417                if (succeeded) {
18418                    // invoke DeviceStorageMonitor's update method to clear any notifications
18419                    DeviceStorageMonitorInternal dsm = LocalServices
18420                            .getService(DeviceStorageMonitorInternal.class);
18421                    if (dsm != null) {
18422                        dsm.checkMemory();
18423                    }
18424                }
18425                if(observer != null) {
18426                    try {
18427                        observer.onRemoveCompleted(packageName, succeeded);
18428                    } catch (RemoteException e) {
18429                        Log.i(TAG, "Observer no longer exists.");
18430                    }
18431                } //end if observer
18432            } //end run
18433        });
18434    }
18435
18436    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18437        if (packageName == null) {
18438            Slog.w(TAG, "Attempt to delete null packageName.");
18439            return false;
18440        }
18441
18442        // Try finding details about the requested package
18443        PackageParser.Package pkg;
18444        synchronized (mPackages) {
18445            pkg = mPackages.get(packageName);
18446            if (pkg == null) {
18447                final PackageSetting ps = mSettings.mPackages.get(packageName);
18448                if (ps != null) {
18449                    pkg = ps.pkg;
18450                }
18451            }
18452
18453            if (pkg == null) {
18454                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18455                return false;
18456            }
18457
18458            PackageSetting ps = (PackageSetting) pkg.mExtras;
18459            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18460        }
18461
18462        clearAppDataLIF(pkg, userId,
18463                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18464
18465        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18466        removeKeystoreDataIfNeeded(userId, appId);
18467
18468        UserManagerInternal umInternal = getUserManagerInternal();
18469        final int flags;
18470        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18471            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18472        } else if (umInternal.isUserRunning(userId)) {
18473            flags = StorageManager.FLAG_STORAGE_DE;
18474        } else {
18475            flags = 0;
18476        }
18477        prepareAppDataContentsLIF(pkg, userId, flags);
18478
18479        return true;
18480    }
18481
18482    /**
18483     * Reverts user permission state changes (permissions and flags) in
18484     * all packages for a given user.
18485     *
18486     * @param userId The device user for which to do a reset.
18487     */
18488    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18489        final int packageCount = mPackages.size();
18490        for (int i = 0; i < packageCount; i++) {
18491            PackageParser.Package pkg = mPackages.valueAt(i);
18492            PackageSetting ps = (PackageSetting) pkg.mExtras;
18493            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18494        }
18495    }
18496
18497    private void resetNetworkPolicies(int userId) {
18498        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18499    }
18500
18501    /**
18502     * Reverts user permission state changes (permissions and flags).
18503     *
18504     * @param ps The package for which to reset.
18505     * @param userId The device user for which to do a reset.
18506     */
18507    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18508            final PackageSetting ps, final int userId) {
18509        if (ps.pkg == null) {
18510            return;
18511        }
18512
18513        // These are flags that can change base on user actions.
18514        final int userSettableMask = FLAG_PERMISSION_USER_SET
18515                | FLAG_PERMISSION_USER_FIXED
18516                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18517                | FLAG_PERMISSION_REVIEW_REQUIRED;
18518
18519        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18520                | FLAG_PERMISSION_POLICY_FIXED;
18521
18522        boolean writeInstallPermissions = false;
18523        boolean writeRuntimePermissions = false;
18524
18525        final int permissionCount = ps.pkg.requestedPermissions.size();
18526        for (int i = 0; i < permissionCount; i++) {
18527            String permission = ps.pkg.requestedPermissions.get(i);
18528
18529            BasePermission bp = mSettings.mPermissions.get(permission);
18530            if (bp == null) {
18531                continue;
18532            }
18533
18534            // If shared user we just reset the state to which only this app contributed.
18535            if (ps.sharedUser != null) {
18536                boolean used = false;
18537                final int packageCount = ps.sharedUser.packages.size();
18538                for (int j = 0; j < packageCount; j++) {
18539                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18540                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18541                            && pkg.pkg.requestedPermissions.contains(permission)) {
18542                        used = true;
18543                        break;
18544                    }
18545                }
18546                if (used) {
18547                    continue;
18548                }
18549            }
18550
18551            PermissionsState permissionsState = ps.getPermissionsState();
18552
18553            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18554
18555            // Always clear the user settable flags.
18556            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18557                    bp.name) != null;
18558            // If permission review is enabled and this is a legacy app, mark the
18559            // permission as requiring a review as this is the initial state.
18560            int flags = 0;
18561            if (mPermissionReviewRequired
18562                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18563                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18564            }
18565            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18566                if (hasInstallState) {
18567                    writeInstallPermissions = true;
18568                } else {
18569                    writeRuntimePermissions = true;
18570                }
18571            }
18572
18573            // Below is only runtime permission handling.
18574            if (!bp.isRuntime()) {
18575                continue;
18576            }
18577
18578            // Never clobber system or policy.
18579            if ((oldFlags & policyOrSystemFlags) != 0) {
18580                continue;
18581            }
18582
18583            // If this permission was granted by default, make sure it is.
18584            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18585                if (permissionsState.grantRuntimePermission(bp, userId)
18586                        != PERMISSION_OPERATION_FAILURE) {
18587                    writeRuntimePermissions = true;
18588                }
18589            // If permission review is enabled the permissions for a legacy apps
18590            // are represented as constantly granted runtime ones, so don't revoke.
18591            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18592                // Otherwise, reset the permission.
18593                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18594                switch (revokeResult) {
18595                    case PERMISSION_OPERATION_SUCCESS:
18596                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18597                        writeRuntimePermissions = true;
18598                        final int appId = ps.appId;
18599                        mHandler.post(new Runnable() {
18600                            @Override
18601                            public void run() {
18602                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18603                            }
18604                        });
18605                    } break;
18606                }
18607            }
18608        }
18609
18610        // Synchronously write as we are taking permissions away.
18611        if (writeRuntimePermissions) {
18612            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18613        }
18614
18615        // Synchronously write as we are taking permissions away.
18616        if (writeInstallPermissions) {
18617            mSettings.writeLPr();
18618        }
18619    }
18620
18621    /**
18622     * Remove entries from the keystore daemon. Will only remove it if the
18623     * {@code appId} is valid.
18624     */
18625    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18626        if (appId < 0) {
18627            return;
18628        }
18629
18630        final KeyStore keyStore = KeyStore.getInstance();
18631        if (keyStore != null) {
18632            if (userId == UserHandle.USER_ALL) {
18633                for (final int individual : sUserManager.getUserIds()) {
18634                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18635                }
18636            } else {
18637                keyStore.clearUid(UserHandle.getUid(userId, appId));
18638            }
18639        } else {
18640            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18641        }
18642    }
18643
18644    @Override
18645    public void deleteApplicationCacheFiles(final String packageName,
18646            final IPackageDataObserver observer) {
18647        final int userId = UserHandle.getCallingUserId();
18648        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18649    }
18650
18651    @Override
18652    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18653            final IPackageDataObserver observer) {
18654        mContext.enforceCallingOrSelfPermission(
18655                android.Manifest.permission.DELETE_CACHE_FILES, null);
18656        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18657                /* requireFullPermission= */ true, /* checkShell= */ false,
18658                "delete application cache files");
18659
18660        final PackageParser.Package pkg;
18661        synchronized (mPackages) {
18662            pkg = mPackages.get(packageName);
18663        }
18664
18665        // Queue up an async operation since the package deletion may take a little while.
18666        mHandler.post(new Runnable() {
18667            public void run() {
18668                synchronized (mInstallLock) {
18669                    final int flags = StorageManager.FLAG_STORAGE_DE
18670                            | StorageManager.FLAG_STORAGE_CE;
18671                    // We're only clearing cache files, so we don't care if the
18672                    // app is unfrozen and still able to run
18673                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18674                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18675                }
18676                clearExternalStorageDataSync(packageName, userId, false);
18677                if (observer != null) {
18678                    try {
18679                        observer.onRemoveCompleted(packageName, true);
18680                    } catch (RemoteException e) {
18681                        Log.i(TAG, "Observer no longer exists.");
18682                    }
18683                }
18684            }
18685        });
18686    }
18687
18688    @Override
18689    public void getPackageSizeInfo(final String packageName, int userHandle,
18690            final IPackageStatsObserver observer) {
18691        mContext.enforceCallingOrSelfPermission(
18692                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18693        if (packageName == null) {
18694            throw new IllegalArgumentException("Attempt to get size of null packageName");
18695        }
18696
18697        PackageStats stats = new PackageStats(packageName, userHandle);
18698
18699        /*
18700         * Queue up an async operation since the package measurement may take a
18701         * little while.
18702         */
18703        Message msg = mHandler.obtainMessage(INIT_COPY);
18704        msg.obj = new MeasureParams(stats, observer);
18705        mHandler.sendMessage(msg);
18706    }
18707
18708    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18709        final PackageSetting ps;
18710        synchronized (mPackages) {
18711            ps = mSettings.mPackages.get(packageName);
18712            if (ps == null) {
18713                Slog.w(TAG, "Failed to find settings for " + packageName);
18714                return false;
18715            }
18716        }
18717
18718        final String[] packageNames = { packageName };
18719        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18720        final String[] codePaths = { ps.codePathString };
18721
18722        try {
18723            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18724                    ps.appId, ceDataInodes, codePaths, stats);
18725
18726            // For now, ignore code size of packages on system partition
18727            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18728                stats.codeSize = 0;
18729            }
18730
18731            // External clients expect these to be tracked separately
18732            stats.dataSize -= stats.cacheSize;
18733
18734        } catch (InstallerException e) {
18735            Slog.w(TAG, String.valueOf(e));
18736            return false;
18737        }
18738
18739        return true;
18740    }
18741
18742    private int getUidTargetSdkVersionLockedLPr(int uid) {
18743        Object obj = mSettings.getUserIdLPr(uid);
18744        if (obj instanceof SharedUserSetting) {
18745            final SharedUserSetting sus = (SharedUserSetting) obj;
18746            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18747            final Iterator<PackageSetting> it = sus.packages.iterator();
18748            while (it.hasNext()) {
18749                final PackageSetting ps = it.next();
18750                if (ps.pkg != null) {
18751                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18752                    if (v < vers) vers = v;
18753                }
18754            }
18755            return vers;
18756        } else if (obj instanceof PackageSetting) {
18757            final PackageSetting ps = (PackageSetting) obj;
18758            if (ps.pkg != null) {
18759                return ps.pkg.applicationInfo.targetSdkVersion;
18760            }
18761        }
18762        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18763    }
18764
18765    @Override
18766    public void addPreferredActivity(IntentFilter filter, int match,
18767            ComponentName[] set, ComponentName activity, int userId) {
18768        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18769                "Adding preferred");
18770    }
18771
18772    private void addPreferredActivityInternal(IntentFilter filter, int match,
18773            ComponentName[] set, ComponentName activity, boolean always, int userId,
18774            String opname) {
18775        // writer
18776        int callingUid = Binder.getCallingUid();
18777        enforceCrossUserPermission(callingUid, userId,
18778                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18779        if (filter.countActions() == 0) {
18780            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18781            return;
18782        }
18783        synchronized (mPackages) {
18784            if (mContext.checkCallingOrSelfPermission(
18785                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18786                    != PackageManager.PERMISSION_GRANTED) {
18787                if (getUidTargetSdkVersionLockedLPr(callingUid)
18788                        < Build.VERSION_CODES.FROYO) {
18789                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18790                            + callingUid);
18791                    return;
18792                }
18793                mContext.enforceCallingOrSelfPermission(
18794                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18795            }
18796
18797            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18798            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18799                    + userId + ":");
18800            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18801            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18802            scheduleWritePackageRestrictionsLocked(userId);
18803            postPreferredActivityChangedBroadcast(userId);
18804        }
18805    }
18806
18807    private void postPreferredActivityChangedBroadcast(int userId) {
18808        mHandler.post(() -> {
18809            final IActivityManager am = ActivityManager.getService();
18810            if (am == null) {
18811                return;
18812            }
18813
18814            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18815            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18816            try {
18817                am.broadcastIntent(null, intent, null, null,
18818                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18819                        null, false, false, userId);
18820            } catch (RemoteException e) {
18821            }
18822        });
18823    }
18824
18825    @Override
18826    public void replacePreferredActivity(IntentFilter filter, int match,
18827            ComponentName[] set, ComponentName activity, int userId) {
18828        if (filter.countActions() != 1) {
18829            throw new IllegalArgumentException(
18830                    "replacePreferredActivity expects filter to have only 1 action.");
18831        }
18832        if (filter.countDataAuthorities() != 0
18833                || filter.countDataPaths() != 0
18834                || filter.countDataSchemes() > 1
18835                || filter.countDataTypes() != 0) {
18836            throw new IllegalArgumentException(
18837                    "replacePreferredActivity expects filter to have no data authorities, " +
18838                    "paths, or types; and at most one scheme.");
18839        }
18840
18841        final int callingUid = Binder.getCallingUid();
18842        enforceCrossUserPermission(callingUid, userId,
18843                true /* requireFullPermission */, false /* checkShell */,
18844                "replace preferred activity");
18845        synchronized (mPackages) {
18846            if (mContext.checkCallingOrSelfPermission(
18847                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18848                    != PackageManager.PERMISSION_GRANTED) {
18849                if (getUidTargetSdkVersionLockedLPr(callingUid)
18850                        < Build.VERSION_CODES.FROYO) {
18851                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18852                            + Binder.getCallingUid());
18853                    return;
18854                }
18855                mContext.enforceCallingOrSelfPermission(
18856                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18857            }
18858
18859            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18860            if (pir != null) {
18861                // Get all of the existing entries that exactly match this filter.
18862                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18863                if (existing != null && existing.size() == 1) {
18864                    PreferredActivity cur = existing.get(0);
18865                    if (DEBUG_PREFERRED) {
18866                        Slog.i(TAG, "Checking replace of preferred:");
18867                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18868                        if (!cur.mPref.mAlways) {
18869                            Slog.i(TAG, "  -- CUR; not mAlways!");
18870                        } else {
18871                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18872                            Slog.i(TAG, "  -- CUR: mSet="
18873                                    + Arrays.toString(cur.mPref.mSetComponents));
18874                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18875                            Slog.i(TAG, "  -- NEW: mMatch="
18876                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18877                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18878                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18879                        }
18880                    }
18881                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18882                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18883                            && cur.mPref.sameSet(set)) {
18884                        // Setting the preferred activity to what it happens to be already
18885                        if (DEBUG_PREFERRED) {
18886                            Slog.i(TAG, "Replacing with same preferred activity "
18887                                    + cur.mPref.mShortComponent + " for user "
18888                                    + userId + ":");
18889                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18890                        }
18891                        return;
18892                    }
18893                }
18894
18895                if (existing != null) {
18896                    if (DEBUG_PREFERRED) {
18897                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18898                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18899                    }
18900                    for (int i = 0; i < existing.size(); i++) {
18901                        PreferredActivity pa = existing.get(i);
18902                        if (DEBUG_PREFERRED) {
18903                            Slog.i(TAG, "Removing existing preferred activity "
18904                                    + pa.mPref.mComponent + ":");
18905                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18906                        }
18907                        pir.removeFilter(pa);
18908                    }
18909                }
18910            }
18911            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18912                    "Replacing preferred");
18913        }
18914    }
18915
18916    @Override
18917    public void clearPackagePreferredActivities(String packageName) {
18918        final int uid = Binder.getCallingUid();
18919        // writer
18920        synchronized (mPackages) {
18921            PackageParser.Package pkg = mPackages.get(packageName);
18922            if (pkg == null || pkg.applicationInfo.uid != uid) {
18923                if (mContext.checkCallingOrSelfPermission(
18924                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18925                        != PackageManager.PERMISSION_GRANTED) {
18926                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18927                            < Build.VERSION_CODES.FROYO) {
18928                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18929                                + Binder.getCallingUid());
18930                        return;
18931                    }
18932                    mContext.enforceCallingOrSelfPermission(
18933                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18934                }
18935            }
18936
18937            int user = UserHandle.getCallingUserId();
18938            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18939                scheduleWritePackageRestrictionsLocked(user);
18940            }
18941        }
18942    }
18943
18944    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18945    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18946        ArrayList<PreferredActivity> removed = null;
18947        boolean changed = false;
18948        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18949            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18950            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18951            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18952                continue;
18953            }
18954            Iterator<PreferredActivity> it = pir.filterIterator();
18955            while (it.hasNext()) {
18956                PreferredActivity pa = it.next();
18957                // Mark entry for removal only if it matches the package name
18958                // and the entry is of type "always".
18959                if (packageName == null ||
18960                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18961                                && pa.mPref.mAlways)) {
18962                    if (removed == null) {
18963                        removed = new ArrayList<PreferredActivity>();
18964                    }
18965                    removed.add(pa);
18966                }
18967            }
18968            if (removed != null) {
18969                for (int j=0; j<removed.size(); j++) {
18970                    PreferredActivity pa = removed.get(j);
18971                    pir.removeFilter(pa);
18972                }
18973                changed = true;
18974            }
18975        }
18976        if (changed) {
18977            postPreferredActivityChangedBroadcast(userId);
18978        }
18979        return changed;
18980    }
18981
18982    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18983    private void clearIntentFilterVerificationsLPw(int userId) {
18984        final int packageCount = mPackages.size();
18985        for (int i = 0; i < packageCount; i++) {
18986            PackageParser.Package pkg = mPackages.valueAt(i);
18987            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18988        }
18989    }
18990
18991    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18992    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18993        if (userId == UserHandle.USER_ALL) {
18994            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18995                    sUserManager.getUserIds())) {
18996                for (int oneUserId : sUserManager.getUserIds()) {
18997                    scheduleWritePackageRestrictionsLocked(oneUserId);
18998                }
18999            }
19000        } else {
19001            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19002                scheduleWritePackageRestrictionsLocked(userId);
19003            }
19004        }
19005    }
19006
19007    void clearDefaultBrowserIfNeeded(String packageName) {
19008        for (int oneUserId : sUserManager.getUserIds()) {
19009            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19010            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19011            if (packageName.equals(defaultBrowserPackageName)) {
19012                setDefaultBrowserPackageName(null, oneUserId);
19013            }
19014        }
19015    }
19016
19017    @Override
19018    public void resetApplicationPreferences(int userId) {
19019        mContext.enforceCallingOrSelfPermission(
19020                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19021        final long identity = Binder.clearCallingIdentity();
19022        // writer
19023        try {
19024            synchronized (mPackages) {
19025                clearPackagePreferredActivitiesLPw(null, userId);
19026                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19027                // TODO: We have to reset the default SMS and Phone. This requires
19028                // significant refactoring to keep all default apps in the package
19029                // manager (cleaner but more work) or have the services provide
19030                // callbacks to the package manager to request a default app reset.
19031                applyFactoryDefaultBrowserLPw(userId);
19032                clearIntentFilterVerificationsLPw(userId);
19033                primeDomainVerificationsLPw(userId);
19034                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19035                scheduleWritePackageRestrictionsLocked(userId);
19036            }
19037            resetNetworkPolicies(userId);
19038        } finally {
19039            Binder.restoreCallingIdentity(identity);
19040        }
19041    }
19042
19043    @Override
19044    public int getPreferredActivities(List<IntentFilter> outFilters,
19045            List<ComponentName> outActivities, String packageName) {
19046
19047        int num = 0;
19048        final int userId = UserHandle.getCallingUserId();
19049        // reader
19050        synchronized (mPackages) {
19051            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19052            if (pir != null) {
19053                final Iterator<PreferredActivity> it = pir.filterIterator();
19054                while (it.hasNext()) {
19055                    final PreferredActivity pa = it.next();
19056                    if (packageName == null
19057                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19058                                    && pa.mPref.mAlways)) {
19059                        if (outFilters != null) {
19060                            outFilters.add(new IntentFilter(pa));
19061                        }
19062                        if (outActivities != null) {
19063                            outActivities.add(pa.mPref.mComponent);
19064                        }
19065                    }
19066                }
19067            }
19068        }
19069
19070        return num;
19071    }
19072
19073    @Override
19074    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19075            int userId) {
19076        int callingUid = Binder.getCallingUid();
19077        if (callingUid != Process.SYSTEM_UID) {
19078            throw new SecurityException(
19079                    "addPersistentPreferredActivity can only be run by the system");
19080        }
19081        if (filter.countActions() == 0) {
19082            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19083            return;
19084        }
19085        synchronized (mPackages) {
19086            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19087                    ":");
19088            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19089            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19090                    new PersistentPreferredActivity(filter, activity));
19091            scheduleWritePackageRestrictionsLocked(userId);
19092            postPreferredActivityChangedBroadcast(userId);
19093        }
19094    }
19095
19096    @Override
19097    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19098        int callingUid = Binder.getCallingUid();
19099        if (callingUid != Process.SYSTEM_UID) {
19100            throw new SecurityException(
19101                    "clearPackagePersistentPreferredActivities can only be run by the system");
19102        }
19103        ArrayList<PersistentPreferredActivity> removed = null;
19104        boolean changed = false;
19105        synchronized (mPackages) {
19106            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19107                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19108                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19109                        .valueAt(i);
19110                if (userId != thisUserId) {
19111                    continue;
19112                }
19113                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19114                while (it.hasNext()) {
19115                    PersistentPreferredActivity ppa = it.next();
19116                    // Mark entry for removal only if it matches the package name.
19117                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19118                        if (removed == null) {
19119                            removed = new ArrayList<PersistentPreferredActivity>();
19120                        }
19121                        removed.add(ppa);
19122                    }
19123                }
19124                if (removed != null) {
19125                    for (int j=0; j<removed.size(); j++) {
19126                        PersistentPreferredActivity ppa = removed.get(j);
19127                        ppir.removeFilter(ppa);
19128                    }
19129                    changed = true;
19130                }
19131            }
19132
19133            if (changed) {
19134                scheduleWritePackageRestrictionsLocked(userId);
19135                postPreferredActivityChangedBroadcast(userId);
19136            }
19137        }
19138    }
19139
19140    /**
19141     * Common machinery for picking apart a restored XML blob and passing
19142     * it to a caller-supplied functor to be applied to the running system.
19143     */
19144    private void restoreFromXml(XmlPullParser parser, int userId,
19145            String expectedStartTag, BlobXmlRestorer functor)
19146            throws IOException, XmlPullParserException {
19147        int type;
19148        while ((type = parser.next()) != XmlPullParser.START_TAG
19149                && type != XmlPullParser.END_DOCUMENT) {
19150        }
19151        if (type != XmlPullParser.START_TAG) {
19152            // oops didn't find a start tag?!
19153            if (DEBUG_BACKUP) {
19154                Slog.e(TAG, "Didn't find start tag during restore");
19155            }
19156            return;
19157        }
19158Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19159        // this is supposed to be TAG_PREFERRED_BACKUP
19160        if (!expectedStartTag.equals(parser.getName())) {
19161            if (DEBUG_BACKUP) {
19162                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19163            }
19164            return;
19165        }
19166
19167        // skip interfering stuff, then we're aligned with the backing implementation
19168        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19169Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19170        functor.apply(parser, userId);
19171    }
19172
19173    private interface BlobXmlRestorer {
19174        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19175    }
19176
19177    /**
19178     * Non-Binder method, support for the backup/restore mechanism: write the
19179     * full set of preferred activities in its canonical XML format.  Returns the
19180     * XML output as a byte array, or null if there is none.
19181     */
19182    @Override
19183    public byte[] getPreferredActivityBackup(int userId) {
19184        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19185            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19186        }
19187
19188        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19189        try {
19190            final XmlSerializer serializer = new FastXmlSerializer();
19191            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19192            serializer.startDocument(null, true);
19193            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19194
19195            synchronized (mPackages) {
19196                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19197            }
19198
19199            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19200            serializer.endDocument();
19201            serializer.flush();
19202        } catch (Exception e) {
19203            if (DEBUG_BACKUP) {
19204                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19205            }
19206            return null;
19207        }
19208
19209        return dataStream.toByteArray();
19210    }
19211
19212    @Override
19213    public void restorePreferredActivities(byte[] backup, int userId) {
19214        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19215            throw new SecurityException("Only the system may call restorePreferredActivities()");
19216        }
19217
19218        try {
19219            final XmlPullParser parser = Xml.newPullParser();
19220            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19221            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19222                    new BlobXmlRestorer() {
19223                        @Override
19224                        public void apply(XmlPullParser parser, int userId)
19225                                throws XmlPullParserException, IOException {
19226                            synchronized (mPackages) {
19227                                mSettings.readPreferredActivitiesLPw(parser, userId);
19228                            }
19229                        }
19230                    } );
19231        } catch (Exception e) {
19232            if (DEBUG_BACKUP) {
19233                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19234            }
19235        }
19236    }
19237
19238    /**
19239     * Non-Binder method, support for the backup/restore mechanism: write the
19240     * default browser (etc) settings in its canonical XML format.  Returns the default
19241     * browser XML representation as a byte array, or null if there is none.
19242     */
19243    @Override
19244    public byte[] getDefaultAppsBackup(int userId) {
19245        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19246            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19247        }
19248
19249        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19250        try {
19251            final XmlSerializer serializer = new FastXmlSerializer();
19252            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19253            serializer.startDocument(null, true);
19254            serializer.startTag(null, TAG_DEFAULT_APPS);
19255
19256            synchronized (mPackages) {
19257                mSettings.writeDefaultAppsLPr(serializer, userId);
19258            }
19259
19260            serializer.endTag(null, TAG_DEFAULT_APPS);
19261            serializer.endDocument();
19262            serializer.flush();
19263        } catch (Exception e) {
19264            if (DEBUG_BACKUP) {
19265                Slog.e(TAG, "Unable to write default apps for backup", e);
19266            }
19267            return null;
19268        }
19269
19270        return dataStream.toByteArray();
19271    }
19272
19273    @Override
19274    public void restoreDefaultApps(byte[] backup, int userId) {
19275        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19276            throw new SecurityException("Only the system may call restoreDefaultApps()");
19277        }
19278
19279        try {
19280            final XmlPullParser parser = Xml.newPullParser();
19281            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19282            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19283                    new BlobXmlRestorer() {
19284                        @Override
19285                        public void apply(XmlPullParser parser, int userId)
19286                                throws XmlPullParserException, IOException {
19287                            synchronized (mPackages) {
19288                                mSettings.readDefaultAppsLPw(parser, userId);
19289                            }
19290                        }
19291                    } );
19292        } catch (Exception e) {
19293            if (DEBUG_BACKUP) {
19294                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19295            }
19296        }
19297    }
19298
19299    @Override
19300    public byte[] getIntentFilterVerificationBackup(int userId) {
19301        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19302            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19303        }
19304
19305        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19306        try {
19307            final XmlSerializer serializer = new FastXmlSerializer();
19308            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19309            serializer.startDocument(null, true);
19310            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19311
19312            synchronized (mPackages) {
19313                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19314            }
19315
19316            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19317            serializer.endDocument();
19318            serializer.flush();
19319        } catch (Exception e) {
19320            if (DEBUG_BACKUP) {
19321                Slog.e(TAG, "Unable to write default apps for backup", e);
19322            }
19323            return null;
19324        }
19325
19326        return dataStream.toByteArray();
19327    }
19328
19329    @Override
19330    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19331        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19332            throw new SecurityException("Only the system may call restorePreferredActivities()");
19333        }
19334
19335        try {
19336            final XmlPullParser parser = Xml.newPullParser();
19337            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19338            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19339                    new BlobXmlRestorer() {
19340                        @Override
19341                        public void apply(XmlPullParser parser, int userId)
19342                                throws XmlPullParserException, IOException {
19343                            synchronized (mPackages) {
19344                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19345                                mSettings.writeLPr();
19346                            }
19347                        }
19348                    } );
19349        } catch (Exception e) {
19350            if (DEBUG_BACKUP) {
19351                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19352            }
19353        }
19354    }
19355
19356    @Override
19357    public byte[] getPermissionGrantBackup(int userId) {
19358        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19359            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19360        }
19361
19362        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19363        try {
19364            final XmlSerializer serializer = new FastXmlSerializer();
19365            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19366            serializer.startDocument(null, true);
19367            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19368
19369            synchronized (mPackages) {
19370                serializeRuntimePermissionGrantsLPr(serializer, userId);
19371            }
19372
19373            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19374            serializer.endDocument();
19375            serializer.flush();
19376        } catch (Exception e) {
19377            if (DEBUG_BACKUP) {
19378                Slog.e(TAG, "Unable to write default apps for backup", e);
19379            }
19380            return null;
19381        }
19382
19383        return dataStream.toByteArray();
19384    }
19385
19386    @Override
19387    public void restorePermissionGrants(byte[] backup, int userId) {
19388        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19389            throw new SecurityException("Only the system may call restorePermissionGrants()");
19390        }
19391
19392        try {
19393            final XmlPullParser parser = Xml.newPullParser();
19394            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19395            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19396                    new BlobXmlRestorer() {
19397                        @Override
19398                        public void apply(XmlPullParser parser, int userId)
19399                                throws XmlPullParserException, IOException {
19400                            synchronized (mPackages) {
19401                                processRestoredPermissionGrantsLPr(parser, userId);
19402                            }
19403                        }
19404                    } );
19405        } catch (Exception e) {
19406            if (DEBUG_BACKUP) {
19407                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19408            }
19409        }
19410    }
19411
19412    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19413            throws IOException {
19414        serializer.startTag(null, TAG_ALL_GRANTS);
19415
19416        final int N = mSettings.mPackages.size();
19417        for (int i = 0; i < N; i++) {
19418            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19419            boolean pkgGrantsKnown = false;
19420
19421            PermissionsState packagePerms = ps.getPermissionsState();
19422
19423            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19424                final int grantFlags = state.getFlags();
19425                // only look at grants that are not system/policy fixed
19426                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19427                    final boolean isGranted = state.isGranted();
19428                    // And only back up the user-twiddled state bits
19429                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19430                        final String packageName = mSettings.mPackages.keyAt(i);
19431                        if (!pkgGrantsKnown) {
19432                            serializer.startTag(null, TAG_GRANT);
19433                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19434                            pkgGrantsKnown = true;
19435                        }
19436
19437                        final boolean userSet =
19438                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19439                        final boolean userFixed =
19440                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19441                        final boolean revoke =
19442                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19443
19444                        serializer.startTag(null, TAG_PERMISSION);
19445                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19446                        if (isGranted) {
19447                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19448                        }
19449                        if (userSet) {
19450                            serializer.attribute(null, ATTR_USER_SET, "true");
19451                        }
19452                        if (userFixed) {
19453                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19454                        }
19455                        if (revoke) {
19456                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19457                        }
19458                        serializer.endTag(null, TAG_PERMISSION);
19459                    }
19460                }
19461            }
19462
19463            if (pkgGrantsKnown) {
19464                serializer.endTag(null, TAG_GRANT);
19465            }
19466        }
19467
19468        serializer.endTag(null, TAG_ALL_GRANTS);
19469    }
19470
19471    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19472            throws XmlPullParserException, IOException {
19473        String pkgName = null;
19474        int outerDepth = parser.getDepth();
19475        int type;
19476        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19477                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19478            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19479                continue;
19480            }
19481
19482            final String tagName = parser.getName();
19483            if (tagName.equals(TAG_GRANT)) {
19484                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19485                if (DEBUG_BACKUP) {
19486                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19487                }
19488            } else if (tagName.equals(TAG_PERMISSION)) {
19489
19490                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19491                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19492
19493                int newFlagSet = 0;
19494                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19495                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19496                }
19497                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19498                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19499                }
19500                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19501                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19502                }
19503                if (DEBUG_BACKUP) {
19504                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19505                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19506                }
19507                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19508                if (ps != null) {
19509                    // Already installed so we apply the grant immediately
19510                    if (DEBUG_BACKUP) {
19511                        Slog.v(TAG, "        + already installed; applying");
19512                    }
19513                    PermissionsState perms = ps.getPermissionsState();
19514                    BasePermission bp = mSettings.mPermissions.get(permName);
19515                    if (bp != null) {
19516                        if (isGranted) {
19517                            perms.grantRuntimePermission(bp, userId);
19518                        }
19519                        if (newFlagSet != 0) {
19520                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19521                        }
19522                    }
19523                } else {
19524                    // Need to wait for post-restore install to apply the grant
19525                    if (DEBUG_BACKUP) {
19526                        Slog.v(TAG, "        - not yet installed; saving for later");
19527                    }
19528                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19529                            isGranted, newFlagSet, userId);
19530                }
19531            } else {
19532                PackageManagerService.reportSettingsProblem(Log.WARN,
19533                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19534                XmlUtils.skipCurrentTag(parser);
19535            }
19536        }
19537
19538        scheduleWriteSettingsLocked();
19539        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19540    }
19541
19542    @Override
19543    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19544            int sourceUserId, int targetUserId, int flags) {
19545        mContext.enforceCallingOrSelfPermission(
19546                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19547        int callingUid = Binder.getCallingUid();
19548        enforceOwnerRights(ownerPackage, callingUid);
19549        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19550        if (intentFilter.countActions() == 0) {
19551            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19552            return;
19553        }
19554        synchronized (mPackages) {
19555            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19556                    ownerPackage, targetUserId, flags);
19557            CrossProfileIntentResolver resolver =
19558                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19559            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19560            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19561            if (existing != null) {
19562                int size = existing.size();
19563                for (int i = 0; i < size; i++) {
19564                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19565                        return;
19566                    }
19567                }
19568            }
19569            resolver.addFilter(newFilter);
19570            scheduleWritePackageRestrictionsLocked(sourceUserId);
19571        }
19572    }
19573
19574    @Override
19575    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19576        mContext.enforceCallingOrSelfPermission(
19577                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19578        int callingUid = Binder.getCallingUid();
19579        enforceOwnerRights(ownerPackage, callingUid);
19580        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19581        synchronized (mPackages) {
19582            CrossProfileIntentResolver resolver =
19583                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19584            ArraySet<CrossProfileIntentFilter> set =
19585                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19586            for (CrossProfileIntentFilter filter : set) {
19587                if (filter.getOwnerPackage().equals(ownerPackage)) {
19588                    resolver.removeFilter(filter);
19589                }
19590            }
19591            scheduleWritePackageRestrictionsLocked(sourceUserId);
19592        }
19593    }
19594
19595    // Enforcing that callingUid is owning pkg on userId
19596    private void enforceOwnerRights(String pkg, int callingUid) {
19597        // The system owns everything.
19598        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19599            return;
19600        }
19601        int callingUserId = UserHandle.getUserId(callingUid);
19602        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19603        if (pi == null) {
19604            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19605                    + callingUserId);
19606        }
19607        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19608            throw new SecurityException("Calling uid " + callingUid
19609                    + " does not own package " + pkg);
19610        }
19611    }
19612
19613    @Override
19614    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19615        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19616    }
19617
19618    private Intent getHomeIntent() {
19619        Intent intent = new Intent(Intent.ACTION_MAIN);
19620        intent.addCategory(Intent.CATEGORY_HOME);
19621        intent.addCategory(Intent.CATEGORY_DEFAULT);
19622        return intent;
19623    }
19624
19625    private IntentFilter getHomeFilter() {
19626        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19627        filter.addCategory(Intent.CATEGORY_HOME);
19628        filter.addCategory(Intent.CATEGORY_DEFAULT);
19629        return filter;
19630    }
19631
19632    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19633            int userId) {
19634        Intent intent  = getHomeIntent();
19635        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19636                PackageManager.GET_META_DATA, userId);
19637        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19638                true, false, false, userId);
19639
19640        allHomeCandidates.clear();
19641        if (list != null) {
19642            for (ResolveInfo ri : list) {
19643                allHomeCandidates.add(ri);
19644            }
19645        }
19646        return (preferred == null || preferred.activityInfo == null)
19647                ? null
19648                : new ComponentName(preferred.activityInfo.packageName,
19649                        preferred.activityInfo.name);
19650    }
19651
19652    @Override
19653    public void setHomeActivity(ComponentName comp, int userId) {
19654        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19655        getHomeActivitiesAsUser(homeActivities, userId);
19656
19657        boolean found = false;
19658
19659        final int size = homeActivities.size();
19660        final ComponentName[] set = new ComponentName[size];
19661        for (int i = 0; i < size; i++) {
19662            final ResolveInfo candidate = homeActivities.get(i);
19663            final ActivityInfo info = candidate.activityInfo;
19664            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19665            set[i] = activityName;
19666            if (!found && activityName.equals(comp)) {
19667                found = true;
19668            }
19669        }
19670        if (!found) {
19671            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19672                    + userId);
19673        }
19674        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19675                set, comp, userId);
19676    }
19677
19678    private @Nullable String getSetupWizardPackageName() {
19679        final Intent intent = new Intent(Intent.ACTION_MAIN);
19680        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19681
19682        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19683                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19684                        | MATCH_DISABLED_COMPONENTS,
19685                UserHandle.myUserId());
19686        if (matches.size() == 1) {
19687            return matches.get(0).getComponentInfo().packageName;
19688        } else {
19689            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19690                    + ": matches=" + matches);
19691            return null;
19692        }
19693    }
19694
19695    private @Nullable String getStorageManagerPackageName() {
19696        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19697
19698        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19699                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19700                        | MATCH_DISABLED_COMPONENTS,
19701                UserHandle.myUserId());
19702        if (matches.size() == 1) {
19703            return matches.get(0).getComponentInfo().packageName;
19704        } else {
19705            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19706                    + matches.size() + ": matches=" + matches);
19707            return null;
19708        }
19709    }
19710
19711    @Override
19712    public void setApplicationEnabledSetting(String appPackageName,
19713            int newState, int flags, int userId, String callingPackage) {
19714        if (!sUserManager.exists(userId)) return;
19715        if (callingPackage == null) {
19716            callingPackage = Integer.toString(Binder.getCallingUid());
19717        }
19718        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19719    }
19720
19721    @Override
19722    public void setComponentEnabledSetting(ComponentName componentName,
19723            int newState, int flags, int userId) {
19724        if (!sUserManager.exists(userId)) return;
19725        setEnabledSetting(componentName.getPackageName(),
19726                componentName.getClassName(), newState, flags, userId, null);
19727    }
19728
19729    private void setEnabledSetting(final String packageName, String className, int newState,
19730            final int flags, int userId, String callingPackage) {
19731        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19732              || newState == COMPONENT_ENABLED_STATE_ENABLED
19733              || newState == COMPONENT_ENABLED_STATE_DISABLED
19734              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19735              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19736            throw new IllegalArgumentException("Invalid new component state: "
19737                    + newState);
19738        }
19739        PackageSetting pkgSetting;
19740        final int uid = Binder.getCallingUid();
19741        final int permission;
19742        if (uid == Process.SYSTEM_UID) {
19743            permission = PackageManager.PERMISSION_GRANTED;
19744        } else {
19745            permission = mContext.checkCallingOrSelfPermission(
19746                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19747        }
19748        enforceCrossUserPermission(uid, userId,
19749                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19750        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19751        boolean sendNow = false;
19752        boolean isApp = (className == null);
19753        String componentName = isApp ? packageName : className;
19754        int packageUid = -1;
19755        ArrayList<String> components;
19756
19757        // writer
19758        synchronized (mPackages) {
19759            pkgSetting = mSettings.mPackages.get(packageName);
19760            if (pkgSetting == null) {
19761                if (className == null) {
19762                    throw new IllegalArgumentException("Unknown package: " + packageName);
19763                }
19764                throw new IllegalArgumentException(
19765                        "Unknown component: " + packageName + "/" + className);
19766            }
19767        }
19768
19769        // Limit who can change which apps
19770        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19771            // Don't allow apps that don't have permission to modify other apps
19772            if (!allowedByPermission) {
19773                throw new SecurityException(
19774                        "Permission Denial: attempt to change component state from pid="
19775                        + Binder.getCallingPid()
19776                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19777            }
19778            // Don't allow changing protected packages.
19779            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19780                throw new SecurityException("Cannot disable a protected package: " + packageName);
19781            }
19782        }
19783
19784        synchronized (mPackages) {
19785            if (uid == Process.SHELL_UID
19786                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19787                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19788                // unless it is a test package.
19789                int oldState = pkgSetting.getEnabled(userId);
19790                if (className == null
19791                    &&
19792                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19793                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19794                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19795                    &&
19796                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19797                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19798                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19799                    // ok
19800                } else {
19801                    throw new SecurityException(
19802                            "Shell cannot change component state for " + packageName + "/"
19803                            + className + " to " + newState);
19804                }
19805            }
19806            if (className == null) {
19807                // We're dealing with an application/package level state change
19808                if (pkgSetting.getEnabled(userId) == newState) {
19809                    // Nothing to do
19810                    return;
19811                }
19812                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19813                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19814                    // Don't care about who enables an app.
19815                    callingPackage = null;
19816                }
19817                pkgSetting.setEnabled(newState, userId, callingPackage);
19818                // pkgSetting.pkg.mSetEnabled = newState;
19819            } else {
19820                // We're dealing with a component level state change
19821                // First, verify that this is a valid class name.
19822                PackageParser.Package pkg = pkgSetting.pkg;
19823                if (pkg == null || !pkg.hasComponentClassName(className)) {
19824                    if (pkg != null &&
19825                            pkg.applicationInfo.targetSdkVersion >=
19826                                    Build.VERSION_CODES.JELLY_BEAN) {
19827                        throw new IllegalArgumentException("Component class " + className
19828                                + " does not exist in " + packageName);
19829                    } else {
19830                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19831                                + className + " does not exist in " + packageName);
19832                    }
19833                }
19834                switch (newState) {
19835                case COMPONENT_ENABLED_STATE_ENABLED:
19836                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19837                        return;
19838                    }
19839                    break;
19840                case COMPONENT_ENABLED_STATE_DISABLED:
19841                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19842                        return;
19843                    }
19844                    break;
19845                case COMPONENT_ENABLED_STATE_DEFAULT:
19846                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19847                        return;
19848                    }
19849                    break;
19850                default:
19851                    Slog.e(TAG, "Invalid new component state: " + newState);
19852                    return;
19853                }
19854            }
19855            scheduleWritePackageRestrictionsLocked(userId);
19856            updateSequenceNumberLP(packageName, new int[] { userId });
19857            components = mPendingBroadcasts.get(userId, packageName);
19858            final boolean newPackage = components == null;
19859            if (newPackage) {
19860                components = new ArrayList<String>();
19861            }
19862            if (!components.contains(componentName)) {
19863                components.add(componentName);
19864            }
19865            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19866                sendNow = true;
19867                // Purge entry from pending broadcast list if another one exists already
19868                // since we are sending one right away.
19869                mPendingBroadcasts.remove(userId, packageName);
19870            } else {
19871                if (newPackage) {
19872                    mPendingBroadcasts.put(userId, packageName, components);
19873                }
19874                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19875                    // Schedule a message
19876                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19877                }
19878            }
19879        }
19880
19881        long callingId = Binder.clearCallingIdentity();
19882        try {
19883            if (sendNow) {
19884                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19885                sendPackageChangedBroadcast(packageName,
19886                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19887            }
19888        } finally {
19889            Binder.restoreCallingIdentity(callingId);
19890        }
19891    }
19892
19893    @Override
19894    public void flushPackageRestrictionsAsUser(int userId) {
19895        if (!sUserManager.exists(userId)) {
19896            return;
19897        }
19898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19899                false /* checkShell */, "flushPackageRestrictions");
19900        synchronized (mPackages) {
19901            mSettings.writePackageRestrictionsLPr(userId);
19902            mDirtyUsers.remove(userId);
19903            if (mDirtyUsers.isEmpty()) {
19904                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19905            }
19906        }
19907    }
19908
19909    private void sendPackageChangedBroadcast(String packageName,
19910            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19911        if (DEBUG_INSTALL)
19912            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19913                    + componentNames);
19914        Bundle extras = new Bundle(4);
19915        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19916        String nameList[] = new String[componentNames.size()];
19917        componentNames.toArray(nameList);
19918        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19919        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19920        extras.putInt(Intent.EXTRA_UID, packageUid);
19921        // If this is not reporting a change of the overall package, then only send it
19922        // to registered receivers.  We don't want to launch a swath of apps for every
19923        // little component state change.
19924        final int flags = !componentNames.contains(packageName)
19925                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19926        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19927                new int[] {UserHandle.getUserId(packageUid)});
19928    }
19929
19930    @Override
19931    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19932        if (!sUserManager.exists(userId)) return;
19933        final int uid = Binder.getCallingUid();
19934        final int permission = mContext.checkCallingOrSelfPermission(
19935                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19936        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19937        enforceCrossUserPermission(uid, userId,
19938                true /* requireFullPermission */, true /* checkShell */, "stop package");
19939        // writer
19940        synchronized (mPackages) {
19941            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19942                    allowedByPermission, uid, userId)) {
19943                scheduleWritePackageRestrictionsLocked(userId);
19944            }
19945        }
19946    }
19947
19948    @Override
19949    public String getInstallerPackageName(String packageName) {
19950        // reader
19951        synchronized (mPackages) {
19952            return mSettings.getInstallerPackageNameLPr(packageName);
19953        }
19954    }
19955
19956    public boolean isOrphaned(String packageName) {
19957        // reader
19958        synchronized (mPackages) {
19959            return mSettings.isOrphaned(packageName);
19960        }
19961    }
19962
19963    @Override
19964    public int getApplicationEnabledSetting(String packageName, int userId) {
19965        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19966        int uid = Binder.getCallingUid();
19967        enforceCrossUserPermission(uid, userId,
19968                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19969        // reader
19970        synchronized (mPackages) {
19971            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19972        }
19973    }
19974
19975    @Override
19976    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19977        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19978        int uid = Binder.getCallingUid();
19979        enforceCrossUserPermission(uid, userId,
19980                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19981        // reader
19982        synchronized (mPackages) {
19983            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19984        }
19985    }
19986
19987    @Override
19988    public void enterSafeMode() {
19989        enforceSystemOrRoot("Only the system can request entering safe mode");
19990
19991        if (!mSystemReady) {
19992            mSafeMode = true;
19993        }
19994    }
19995
19996    @Override
19997    public void systemReady() {
19998        mSystemReady = true;
19999
20000        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20001        // disabled after already being started.
20002        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20003                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20004
20005        // Read the compatibilty setting when the system is ready.
20006        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20007                mContext.getContentResolver(),
20008                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20009        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20010        if (DEBUG_SETTINGS) {
20011            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20012        }
20013
20014        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20015
20016        synchronized (mPackages) {
20017            // Verify that all of the preferred activity components actually
20018            // exist.  It is possible for applications to be updated and at
20019            // that point remove a previously declared activity component that
20020            // had been set as a preferred activity.  We try to clean this up
20021            // the next time we encounter that preferred activity, but it is
20022            // possible for the user flow to never be able to return to that
20023            // situation so here we do a sanity check to make sure we haven't
20024            // left any junk around.
20025            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20026            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20027                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20028                removed.clear();
20029                for (PreferredActivity pa : pir.filterSet()) {
20030                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20031                        removed.add(pa);
20032                    }
20033                }
20034                if (removed.size() > 0) {
20035                    for (int r=0; r<removed.size(); r++) {
20036                        PreferredActivity pa = removed.get(r);
20037                        Slog.w(TAG, "Removing dangling preferred activity: "
20038                                + pa.mPref.mComponent);
20039                        pir.removeFilter(pa);
20040                    }
20041                    mSettings.writePackageRestrictionsLPr(
20042                            mSettings.mPreferredActivities.keyAt(i));
20043                }
20044            }
20045
20046            for (int userId : UserManagerService.getInstance().getUserIds()) {
20047                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20048                    grantPermissionsUserIds = ArrayUtils.appendInt(
20049                            grantPermissionsUserIds, userId);
20050                }
20051            }
20052        }
20053        sUserManager.systemReady();
20054
20055        // If we upgraded grant all default permissions before kicking off.
20056        for (int userId : grantPermissionsUserIds) {
20057            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20058        }
20059
20060        // If we did not grant default permissions, we preload from this the
20061        // default permission exceptions lazily to ensure we don't hit the
20062        // disk on a new user creation.
20063        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20064            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20065        }
20066
20067        // Kick off any messages waiting for system ready
20068        if (mPostSystemReadyMessages != null) {
20069            for (Message msg : mPostSystemReadyMessages) {
20070                msg.sendToTarget();
20071            }
20072            mPostSystemReadyMessages = null;
20073        }
20074
20075        // Watch for external volumes that come and go over time
20076        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20077        storage.registerListener(mStorageListener);
20078
20079        mInstallerService.systemReady();
20080        mPackageDexOptimizer.systemReady();
20081
20082        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20083                StorageManagerInternal.class);
20084        StorageManagerInternal.addExternalStoragePolicy(
20085                new StorageManagerInternal.ExternalStorageMountPolicy() {
20086            @Override
20087            public int getMountMode(int uid, String packageName) {
20088                if (Process.isIsolated(uid)) {
20089                    return Zygote.MOUNT_EXTERNAL_NONE;
20090                }
20091                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20092                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20093                }
20094                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20095                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20096                }
20097                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20098                    return Zygote.MOUNT_EXTERNAL_READ;
20099                }
20100                return Zygote.MOUNT_EXTERNAL_WRITE;
20101            }
20102
20103            @Override
20104            public boolean hasExternalStorage(int uid, String packageName) {
20105                return true;
20106            }
20107        });
20108
20109        // Now that we're mostly running, clean up stale users and apps
20110        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20111        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20112
20113        if (mPrivappPermissionsViolations != null) {
20114            Slog.wtf(TAG,"Signature|privileged permissions not in "
20115                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20116            mPrivappPermissionsViolations = null;
20117        }
20118    }
20119
20120    @Override
20121    public boolean isSafeMode() {
20122        return mSafeMode;
20123    }
20124
20125    @Override
20126    public boolean hasSystemUidErrors() {
20127        return mHasSystemUidErrors;
20128    }
20129
20130    static String arrayToString(int[] array) {
20131        StringBuffer buf = new StringBuffer(128);
20132        buf.append('[');
20133        if (array != null) {
20134            for (int i=0; i<array.length; i++) {
20135                if (i > 0) buf.append(", ");
20136                buf.append(array[i]);
20137            }
20138        }
20139        buf.append(']');
20140        return buf.toString();
20141    }
20142
20143    static class DumpState {
20144        public static final int DUMP_LIBS = 1 << 0;
20145        public static final int DUMP_FEATURES = 1 << 1;
20146        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20147        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20148        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20149        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20150        public static final int DUMP_PERMISSIONS = 1 << 6;
20151        public static final int DUMP_PACKAGES = 1 << 7;
20152        public static final int DUMP_SHARED_USERS = 1 << 8;
20153        public static final int DUMP_MESSAGES = 1 << 9;
20154        public static final int DUMP_PROVIDERS = 1 << 10;
20155        public static final int DUMP_VERIFIERS = 1 << 11;
20156        public static final int DUMP_PREFERRED = 1 << 12;
20157        public static final int DUMP_PREFERRED_XML = 1 << 13;
20158        public static final int DUMP_KEYSETS = 1 << 14;
20159        public static final int DUMP_VERSION = 1 << 15;
20160        public static final int DUMP_INSTALLS = 1 << 16;
20161        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20162        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20163        public static final int DUMP_FROZEN = 1 << 19;
20164        public static final int DUMP_DEXOPT = 1 << 20;
20165        public static final int DUMP_COMPILER_STATS = 1 << 21;
20166
20167        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20168
20169        private int mTypes;
20170
20171        private int mOptions;
20172
20173        private boolean mTitlePrinted;
20174
20175        private SharedUserSetting mSharedUser;
20176
20177        public boolean isDumping(int type) {
20178            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20179                return true;
20180            }
20181
20182            return (mTypes & type) != 0;
20183        }
20184
20185        public void setDump(int type) {
20186            mTypes |= type;
20187        }
20188
20189        public boolean isOptionEnabled(int option) {
20190            return (mOptions & option) != 0;
20191        }
20192
20193        public void setOptionEnabled(int option) {
20194            mOptions |= option;
20195        }
20196
20197        public boolean onTitlePrinted() {
20198            final boolean printed = mTitlePrinted;
20199            mTitlePrinted = true;
20200            return printed;
20201        }
20202
20203        public boolean getTitlePrinted() {
20204            return mTitlePrinted;
20205        }
20206
20207        public void setTitlePrinted(boolean enabled) {
20208            mTitlePrinted = enabled;
20209        }
20210
20211        public SharedUserSetting getSharedUser() {
20212            return mSharedUser;
20213        }
20214
20215        public void setSharedUser(SharedUserSetting user) {
20216            mSharedUser = user;
20217        }
20218    }
20219
20220    @Override
20221    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20222            FileDescriptor err, String[] args, ShellCallback callback,
20223            ResultReceiver resultReceiver) {
20224        (new PackageManagerShellCommand(this)).exec(
20225                this, in, out, err, args, callback, resultReceiver);
20226    }
20227
20228    @Override
20229    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20230        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20231                != PackageManager.PERMISSION_GRANTED) {
20232            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20233                    + Binder.getCallingPid()
20234                    + ", uid=" + Binder.getCallingUid()
20235                    + " without permission "
20236                    + android.Manifest.permission.DUMP);
20237            return;
20238        }
20239
20240        DumpState dumpState = new DumpState();
20241        boolean fullPreferred = false;
20242        boolean checkin = false;
20243
20244        String packageName = null;
20245        ArraySet<String> permissionNames = null;
20246
20247        int opti = 0;
20248        while (opti < args.length) {
20249            String opt = args[opti];
20250            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20251                break;
20252            }
20253            opti++;
20254
20255            if ("-a".equals(opt)) {
20256                // Right now we only know how to print all.
20257            } else if ("-h".equals(opt)) {
20258                pw.println("Package manager dump options:");
20259                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20260                pw.println("    --checkin: dump for a checkin");
20261                pw.println("    -f: print details of intent filters");
20262                pw.println("    -h: print this help");
20263                pw.println("  cmd may be one of:");
20264                pw.println("    l[ibraries]: list known shared libraries");
20265                pw.println("    f[eatures]: list device features");
20266                pw.println("    k[eysets]: print known keysets");
20267                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20268                pw.println("    perm[issions]: dump permissions");
20269                pw.println("    permission [name ...]: dump declaration and use of given permission");
20270                pw.println("    pref[erred]: print preferred package settings");
20271                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20272                pw.println("    prov[iders]: dump content providers");
20273                pw.println("    p[ackages]: dump installed packages");
20274                pw.println("    s[hared-users]: dump shared user IDs");
20275                pw.println("    m[essages]: print collected runtime messages");
20276                pw.println("    v[erifiers]: print package verifier info");
20277                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20278                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20279                pw.println("    version: print database version info");
20280                pw.println("    write: write current settings now");
20281                pw.println("    installs: details about install sessions");
20282                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20283                pw.println("    dexopt: dump dexopt state");
20284                pw.println("    compiler-stats: dump compiler statistics");
20285                pw.println("    <package.name>: info about given package");
20286                return;
20287            } else if ("--checkin".equals(opt)) {
20288                checkin = true;
20289            } else if ("-f".equals(opt)) {
20290                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20291            } else {
20292                pw.println("Unknown argument: " + opt + "; use -h for help");
20293            }
20294        }
20295
20296        // Is the caller requesting to dump a particular piece of data?
20297        if (opti < args.length) {
20298            String cmd = args[opti];
20299            opti++;
20300            // Is this a package name?
20301            if ("android".equals(cmd) || cmd.contains(".")) {
20302                packageName = cmd;
20303                // When dumping a single package, we always dump all of its
20304                // filter information since the amount of data will be reasonable.
20305                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20306            } else if ("check-permission".equals(cmd)) {
20307                if (opti >= args.length) {
20308                    pw.println("Error: check-permission missing permission argument");
20309                    return;
20310                }
20311                String perm = args[opti];
20312                opti++;
20313                if (opti >= args.length) {
20314                    pw.println("Error: check-permission missing package argument");
20315                    return;
20316                }
20317
20318                String pkg = args[opti];
20319                opti++;
20320                int user = UserHandle.getUserId(Binder.getCallingUid());
20321                if (opti < args.length) {
20322                    try {
20323                        user = Integer.parseInt(args[opti]);
20324                    } catch (NumberFormatException e) {
20325                        pw.println("Error: check-permission user argument is not a number: "
20326                                + args[opti]);
20327                        return;
20328                    }
20329                }
20330
20331                // Normalize package name to handle renamed packages and static libs
20332                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20333
20334                pw.println(checkPermission(perm, pkg, user));
20335                return;
20336            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20337                dumpState.setDump(DumpState.DUMP_LIBS);
20338            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20339                dumpState.setDump(DumpState.DUMP_FEATURES);
20340            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20341                if (opti >= args.length) {
20342                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20343                            | DumpState.DUMP_SERVICE_RESOLVERS
20344                            | DumpState.DUMP_RECEIVER_RESOLVERS
20345                            | DumpState.DUMP_CONTENT_RESOLVERS);
20346                } else {
20347                    while (opti < args.length) {
20348                        String name = args[opti];
20349                        if ("a".equals(name) || "activity".equals(name)) {
20350                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20351                        } else if ("s".equals(name) || "service".equals(name)) {
20352                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20353                        } else if ("r".equals(name) || "receiver".equals(name)) {
20354                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20355                        } else if ("c".equals(name) || "content".equals(name)) {
20356                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20357                        } else {
20358                            pw.println("Error: unknown resolver table type: " + name);
20359                            return;
20360                        }
20361                        opti++;
20362                    }
20363                }
20364            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20365                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20366            } else if ("permission".equals(cmd)) {
20367                if (opti >= args.length) {
20368                    pw.println("Error: permission requires permission name");
20369                    return;
20370                }
20371                permissionNames = new ArraySet<>();
20372                while (opti < args.length) {
20373                    permissionNames.add(args[opti]);
20374                    opti++;
20375                }
20376                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20377                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20378            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20379                dumpState.setDump(DumpState.DUMP_PREFERRED);
20380            } else if ("preferred-xml".equals(cmd)) {
20381                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20382                if (opti < args.length && "--full".equals(args[opti])) {
20383                    fullPreferred = true;
20384                    opti++;
20385                }
20386            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20387                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20388            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20389                dumpState.setDump(DumpState.DUMP_PACKAGES);
20390            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20391                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20392            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20393                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20394            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20395                dumpState.setDump(DumpState.DUMP_MESSAGES);
20396            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20397                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20398            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20399                    || "intent-filter-verifiers".equals(cmd)) {
20400                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20401            } else if ("version".equals(cmd)) {
20402                dumpState.setDump(DumpState.DUMP_VERSION);
20403            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_KEYSETS);
20405            } else if ("installs".equals(cmd)) {
20406                dumpState.setDump(DumpState.DUMP_INSTALLS);
20407            } else if ("frozen".equals(cmd)) {
20408                dumpState.setDump(DumpState.DUMP_FROZEN);
20409            } else if ("dexopt".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_DEXOPT);
20411            } else if ("compiler-stats".equals(cmd)) {
20412                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20413            } else if ("write".equals(cmd)) {
20414                synchronized (mPackages) {
20415                    mSettings.writeLPr();
20416                    pw.println("Settings written.");
20417                    return;
20418                }
20419            }
20420        }
20421
20422        if (checkin) {
20423            pw.println("vers,1");
20424        }
20425
20426        // reader
20427        synchronized (mPackages) {
20428            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20429                if (!checkin) {
20430                    if (dumpState.onTitlePrinted())
20431                        pw.println();
20432                    pw.println("Database versions:");
20433                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20434                }
20435            }
20436
20437            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20438                if (!checkin) {
20439                    if (dumpState.onTitlePrinted())
20440                        pw.println();
20441                    pw.println("Verifiers:");
20442                    pw.print("  Required: ");
20443                    pw.print(mRequiredVerifierPackage);
20444                    pw.print(" (uid=");
20445                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20446                            UserHandle.USER_SYSTEM));
20447                    pw.println(")");
20448                } else if (mRequiredVerifierPackage != null) {
20449                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20450                    pw.print(",");
20451                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20452                            UserHandle.USER_SYSTEM));
20453                }
20454            }
20455
20456            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20457                    packageName == null) {
20458                if (mIntentFilterVerifierComponent != null) {
20459                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20460                    if (!checkin) {
20461                        if (dumpState.onTitlePrinted())
20462                            pw.println();
20463                        pw.println("Intent Filter Verifier:");
20464                        pw.print("  Using: ");
20465                        pw.print(verifierPackageName);
20466                        pw.print(" (uid=");
20467                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20468                                UserHandle.USER_SYSTEM));
20469                        pw.println(")");
20470                    } else if (verifierPackageName != null) {
20471                        pw.print("ifv,"); pw.print(verifierPackageName);
20472                        pw.print(",");
20473                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20474                                UserHandle.USER_SYSTEM));
20475                    }
20476                } else {
20477                    pw.println();
20478                    pw.println("No Intent Filter Verifier available!");
20479                }
20480            }
20481
20482            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20483                boolean printedHeader = false;
20484                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20485                while (it.hasNext()) {
20486                    String libName = it.next();
20487                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20488                    if (versionedLib == null) {
20489                        continue;
20490                    }
20491                    final int versionCount = versionedLib.size();
20492                    for (int i = 0; i < versionCount; i++) {
20493                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20494                        if (!checkin) {
20495                            if (!printedHeader) {
20496                                if (dumpState.onTitlePrinted())
20497                                    pw.println();
20498                                pw.println("Libraries:");
20499                                printedHeader = true;
20500                            }
20501                            pw.print("  ");
20502                        } else {
20503                            pw.print("lib,");
20504                        }
20505                        pw.print(libEntry.info.getName());
20506                        if (libEntry.info.isStatic()) {
20507                            pw.print(" version=" + libEntry.info.getVersion());
20508                        }
20509                        if (!checkin) {
20510                            pw.print(" -> ");
20511                        }
20512                        if (libEntry.path != null) {
20513                            pw.print(" (jar) ");
20514                            pw.print(libEntry.path);
20515                        } else {
20516                            pw.print(" (apk) ");
20517                            pw.print(libEntry.apk);
20518                        }
20519                        pw.println();
20520                    }
20521                }
20522            }
20523
20524            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20525                if (dumpState.onTitlePrinted())
20526                    pw.println();
20527                if (!checkin) {
20528                    pw.println("Features:");
20529                }
20530
20531                synchronized (mAvailableFeatures) {
20532                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20533                        if (checkin) {
20534                            pw.print("feat,");
20535                            pw.print(feat.name);
20536                            pw.print(",");
20537                            pw.println(feat.version);
20538                        } else {
20539                            pw.print("  ");
20540                            pw.print(feat.name);
20541                            if (feat.version > 0) {
20542                                pw.print(" version=");
20543                                pw.print(feat.version);
20544                            }
20545                            pw.println();
20546                        }
20547                    }
20548                }
20549            }
20550
20551            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20552                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20553                        : "Activity Resolver Table:", "  ", packageName,
20554                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20555                    dumpState.setTitlePrinted(true);
20556                }
20557            }
20558            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20559                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20560                        : "Receiver Resolver Table:", "  ", packageName,
20561                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20562                    dumpState.setTitlePrinted(true);
20563                }
20564            }
20565            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20566                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20567                        : "Service Resolver Table:", "  ", packageName,
20568                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20569                    dumpState.setTitlePrinted(true);
20570                }
20571            }
20572            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20573                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20574                        : "Provider Resolver Table:", "  ", packageName,
20575                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20576                    dumpState.setTitlePrinted(true);
20577                }
20578            }
20579
20580            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20581                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20582                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20583                    int user = mSettings.mPreferredActivities.keyAt(i);
20584                    if (pir.dump(pw,
20585                            dumpState.getTitlePrinted()
20586                                ? "\nPreferred Activities User " + user + ":"
20587                                : "Preferred Activities User " + user + ":", "  ",
20588                            packageName, true, false)) {
20589                        dumpState.setTitlePrinted(true);
20590                    }
20591                }
20592            }
20593
20594            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20595                pw.flush();
20596                FileOutputStream fout = new FileOutputStream(fd);
20597                BufferedOutputStream str = new BufferedOutputStream(fout);
20598                XmlSerializer serializer = new FastXmlSerializer();
20599                try {
20600                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20601                    serializer.startDocument(null, true);
20602                    serializer.setFeature(
20603                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20604                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20605                    serializer.endDocument();
20606                    serializer.flush();
20607                } catch (IllegalArgumentException e) {
20608                    pw.println("Failed writing: " + e);
20609                } catch (IllegalStateException e) {
20610                    pw.println("Failed writing: " + e);
20611                } catch (IOException e) {
20612                    pw.println("Failed writing: " + e);
20613                }
20614            }
20615
20616            if (!checkin
20617                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20618                    && packageName == null) {
20619                pw.println();
20620                int count = mSettings.mPackages.size();
20621                if (count == 0) {
20622                    pw.println("No applications!");
20623                    pw.println();
20624                } else {
20625                    final String prefix = "  ";
20626                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20627                    if (allPackageSettings.size() == 0) {
20628                        pw.println("No domain preferred apps!");
20629                        pw.println();
20630                    } else {
20631                        pw.println("App verification status:");
20632                        pw.println();
20633                        count = 0;
20634                        for (PackageSetting ps : allPackageSettings) {
20635                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20636                            if (ivi == null || ivi.getPackageName() == null) continue;
20637                            pw.println(prefix + "Package: " + ivi.getPackageName());
20638                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20639                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20640                            pw.println();
20641                            count++;
20642                        }
20643                        if (count == 0) {
20644                            pw.println(prefix + "No app verification established.");
20645                            pw.println();
20646                        }
20647                        for (int userId : sUserManager.getUserIds()) {
20648                            pw.println("App linkages for user " + userId + ":");
20649                            pw.println();
20650                            count = 0;
20651                            for (PackageSetting ps : allPackageSettings) {
20652                                final long status = ps.getDomainVerificationStatusForUser(userId);
20653                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20654                                        && !DEBUG_DOMAIN_VERIFICATION) {
20655                                    continue;
20656                                }
20657                                pw.println(prefix + "Package: " + ps.name);
20658                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20659                                String statusStr = IntentFilterVerificationInfo.
20660                                        getStatusStringFromValue(status);
20661                                pw.println(prefix + "Status:  " + statusStr);
20662                                pw.println();
20663                                count++;
20664                            }
20665                            if (count == 0) {
20666                                pw.println(prefix + "No configured app linkages.");
20667                                pw.println();
20668                            }
20669                        }
20670                    }
20671                }
20672            }
20673
20674            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20675                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20676                if (packageName == null && permissionNames == null) {
20677                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20678                        if (iperm == 0) {
20679                            if (dumpState.onTitlePrinted())
20680                                pw.println();
20681                            pw.println("AppOp Permissions:");
20682                        }
20683                        pw.print("  AppOp Permission ");
20684                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20685                        pw.println(":");
20686                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20687                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20688                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20689                        }
20690                    }
20691                }
20692            }
20693
20694            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20695                boolean printedSomething = false;
20696                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20697                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20698                        continue;
20699                    }
20700                    if (!printedSomething) {
20701                        if (dumpState.onTitlePrinted())
20702                            pw.println();
20703                        pw.println("Registered ContentProviders:");
20704                        printedSomething = true;
20705                    }
20706                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20707                    pw.print("    "); pw.println(p.toString());
20708                }
20709                printedSomething = false;
20710                for (Map.Entry<String, PackageParser.Provider> entry :
20711                        mProvidersByAuthority.entrySet()) {
20712                    PackageParser.Provider p = entry.getValue();
20713                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20714                        continue;
20715                    }
20716                    if (!printedSomething) {
20717                        if (dumpState.onTitlePrinted())
20718                            pw.println();
20719                        pw.println("ContentProvider Authorities:");
20720                        printedSomething = true;
20721                    }
20722                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20723                    pw.print("    "); pw.println(p.toString());
20724                    if (p.info != null && p.info.applicationInfo != null) {
20725                        final String appInfo = p.info.applicationInfo.toString();
20726                        pw.print("      applicationInfo="); pw.println(appInfo);
20727                    }
20728                }
20729            }
20730
20731            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20732                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20733            }
20734
20735            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20736                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20737            }
20738
20739            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20740                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20741            }
20742
20743            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20744                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20745            }
20746
20747            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20748                // XXX should handle packageName != null by dumping only install data that
20749                // the given package is involved with.
20750                if (dumpState.onTitlePrinted()) pw.println();
20751                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20752            }
20753
20754            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20755                // XXX should handle packageName != null by dumping only install data that
20756                // the given package is involved with.
20757                if (dumpState.onTitlePrinted()) pw.println();
20758
20759                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20760                ipw.println();
20761                ipw.println("Frozen packages:");
20762                ipw.increaseIndent();
20763                if (mFrozenPackages.size() == 0) {
20764                    ipw.println("(none)");
20765                } else {
20766                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20767                        ipw.println(mFrozenPackages.valueAt(i));
20768                    }
20769                }
20770                ipw.decreaseIndent();
20771            }
20772
20773            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20774                if (dumpState.onTitlePrinted()) pw.println();
20775                dumpDexoptStateLPr(pw, packageName);
20776            }
20777
20778            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20779                if (dumpState.onTitlePrinted()) pw.println();
20780                dumpCompilerStatsLPr(pw, packageName);
20781            }
20782
20783            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20784                if (dumpState.onTitlePrinted()) pw.println();
20785                mSettings.dumpReadMessagesLPr(pw, dumpState);
20786
20787                pw.println();
20788                pw.println("Package warning messages:");
20789                BufferedReader in = null;
20790                String line = null;
20791                try {
20792                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20793                    while ((line = in.readLine()) != null) {
20794                        if (line.contains("ignored: updated version")) continue;
20795                        pw.println(line);
20796                    }
20797                } catch (IOException ignored) {
20798                } finally {
20799                    IoUtils.closeQuietly(in);
20800                }
20801            }
20802
20803            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20804                BufferedReader in = null;
20805                String line = null;
20806                try {
20807                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20808                    while ((line = in.readLine()) != null) {
20809                        if (line.contains("ignored: updated version")) continue;
20810                        pw.print("msg,");
20811                        pw.println(line);
20812                    }
20813                } catch (IOException ignored) {
20814                } finally {
20815                    IoUtils.closeQuietly(in);
20816                }
20817            }
20818        }
20819    }
20820
20821    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20822        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20823        ipw.println();
20824        ipw.println("Dexopt state:");
20825        ipw.increaseIndent();
20826        Collection<PackageParser.Package> packages = null;
20827        if (packageName != null) {
20828            PackageParser.Package targetPackage = mPackages.get(packageName);
20829            if (targetPackage != null) {
20830                packages = Collections.singletonList(targetPackage);
20831            } else {
20832                ipw.println("Unable to find package: " + packageName);
20833                return;
20834            }
20835        } else {
20836            packages = mPackages.values();
20837        }
20838
20839        for (PackageParser.Package pkg : packages) {
20840            ipw.println("[" + pkg.packageName + "]");
20841            ipw.increaseIndent();
20842            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20843            ipw.decreaseIndent();
20844        }
20845    }
20846
20847    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20848        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20849        ipw.println();
20850        ipw.println("Compiler stats:");
20851        ipw.increaseIndent();
20852        Collection<PackageParser.Package> packages = null;
20853        if (packageName != null) {
20854            PackageParser.Package targetPackage = mPackages.get(packageName);
20855            if (targetPackage != null) {
20856                packages = Collections.singletonList(targetPackage);
20857            } else {
20858                ipw.println("Unable to find package: " + packageName);
20859                return;
20860            }
20861        } else {
20862            packages = mPackages.values();
20863        }
20864
20865        for (PackageParser.Package pkg : packages) {
20866            ipw.println("[" + pkg.packageName + "]");
20867            ipw.increaseIndent();
20868
20869            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20870            if (stats == null) {
20871                ipw.println("(No recorded stats)");
20872            } else {
20873                stats.dump(ipw);
20874            }
20875            ipw.decreaseIndent();
20876        }
20877    }
20878
20879    private String dumpDomainString(String packageName) {
20880        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20881                .getList();
20882        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20883
20884        ArraySet<String> result = new ArraySet<>();
20885        if (iviList.size() > 0) {
20886            for (IntentFilterVerificationInfo ivi : iviList) {
20887                for (String host : ivi.getDomains()) {
20888                    result.add(host);
20889                }
20890            }
20891        }
20892        if (filters != null && filters.size() > 0) {
20893            for (IntentFilter filter : filters) {
20894                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20895                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20896                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20897                    result.addAll(filter.getHostsList());
20898                }
20899            }
20900        }
20901
20902        StringBuilder sb = new StringBuilder(result.size() * 16);
20903        for (String domain : result) {
20904            if (sb.length() > 0) sb.append(" ");
20905            sb.append(domain);
20906        }
20907        return sb.toString();
20908    }
20909
20910    // ------- apps on sdcard specific code -------
20911    static final boolean DEBUG_SD_INSTALL = false;
20912
20913    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20914
20915    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20916
20917    private boolean mMediaMounted = false;
20918
20919    static String getEncryptKey() {
20920        try {
20921            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20922                    SD_ENCRYPTION_KEYSTORE_NAME);
20923            if (sdEncKey == null) {
20924                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20925                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20926                if (sdEncKey == null) {
20927                    Slog.e(TAG, "Failed to create encryption keys");
20928                    return null;
20929                }
20930            }
20931            return sdEncKey;
20932        } catch (NoSuchAlgorithmException nsae) {
20933            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20934            return null;
20935        } catch (IOException ioe) {
20936            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20937            return null;
20938        }
20939    }
20940
20941    /*
20942     * Update media status on PackageManager.
20943     */
20944    @Override
20945    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20946        int callingUid = Binder.getCallingUid();
20947        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20948            throw new SecurityException("Media status can only be updated by the system");
20949        }
20950        // reader; this apparently protects mMediaMounted, but should probably
20951        // be a different lock in that case.
20952        synchronized (mPackages) {
20953            Log.i(TAG, "Updating external media status from "
20954                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20955                    + (mediaStatus ? "mounted" : "unmounted"));
20956            if (DEBUG_SD_INSTALL)
20957                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20958                        + ", mMediaMounted=" + mMediaMounted);
20959            if (mediaStatus == mMediaMounted) {
20960                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20961                        : 0, -1);
20962                mHandler.sendMessage(msg);
20963                return;
20964            }
20965            mMediaMounted = mediaStatus;
20966        }
20967        // Queue up an async operation since the package installation may take a
20968        // little while.
20969        mHandler.post(new Runnable() {
20970            public void run() {
20971                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20972            }
20973        });
20974    }
20975
20976    /**
20977     * Called by StorageManagerService when the initial ASECs to scan are available.
20978     * Should block until all the ASEC containers are finished being scanned.
20979     */
20980    public void scanAvailableAsecs() {
20981        updateExternalMediaStatusInner(true, false, false);
20982    }
20983
20984    /*
20985     * Collect information of applications on external media, map them against
20986     * existing containers and update information based on current mount status.
20987     * Please note that we always have to report status if reportStatus has been
20988     * set to true especially when unloading packages.
20989     */
20990    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20991            boolean externalStorage) {
20992        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20993        int[] uidArr = EmptyArray.INT;
20994
20995        final String[] list = PackageHelper.getSecureContainerList();
20996        if (ArrayUtils.isEmpty(list)) {
20997            Log.i(TAG, "No secure containers found");
20998        } else {
20999            // Process list of secure containers and categorize them
21000            // as active or stale based on their package internal state.
21001
21002            // reader
21003            synchronized (mPackages) {
21004                for (String cid : list) {
21005                    // Leave stages untouched for now; installer service owns them
21006                    if (PackageInstallerService.isStageName(cid)) continue;
21007
21008                    if (DEBUG_SD_INSTALL)
21009                        Log.i(TAG, "Processing container " + cid);
21010                    String pkgName = getAsecPackageName(cid);
21011                    if (pkgName == null) {
21012                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21013                        continue;
21014                    }
21015                    if (DEBUG_SD_INSTALL)
21016                        Log.i(TAG, "Looking for pkg : " + pkgName);
21017
21018                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21019                    if (ps == null) {
21020                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21021                        continue;
21022                    }
21023
21024                    /*
21025                     * Skip packages that are not external if we're unmounting
21026                     * external storage.
21027                     */
21028                    if (externalStorage && !isMounted && !isExternal(ps)) {
21029                        continue;
21030                    }
21031
21032                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21033                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21034                    // The package status is changed only if the code path
21035                    // matches between settings and the container id.
21036                    if (ps.codePathString != null
21037                            && ps.codePathString.startsWith(args.getCodePath())) {
21038                        if (DEBUG_SD_INSTALL) {
21039                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21040                                    + " at code path: " + ps.codePathString);
21041                        }
21042
21043                        // We do have a valid package installed on sdcard
21044                        processCids.put(args, ps.codePathString);
21045                        final int uid = ps.appId;
21046                        if (uid != -1) {
21047                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21048                        }
21049                    } else {
21050                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21051                                + ps.codePathString);
21052                    }
21053                }
21054            }
21055
21056            Arrays.sort(uidArr);
21057        }
21058
21059        // Process packages with valid entries.
21060        if (isMounted) {
21061            if (DEBUG_SD_INSTALL)
21062                Log.i(TAG, "Loading packages");
21063            loadMediaPackages(processCids, uidArr, externalStorage);
21064            startCleaningPackages();
21065            mInstallerService.onSecureContainersAvailable();
21066        } else {
21067            if (DEBUG_SD_INSTALL)
21068                Log.i(TAG, "Unloading packages");
21069            unloadMediaPackages(processCids, uidArr, reportStatus);
21070        }
21071    }
21072
21073    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21074            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21075        final int size = infos.size();
21076        final String[] packageNames = new String[size];
21077        final int[] packageUids = new int[size];
21078        for (int i = 0; i < size; i++) {
21079            final ApplicationInfo info = infos.get(i);
21080            packageNames[i] = info.packageName;
21081            packageUids[i] = info.uid;
21082        }
21083        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21084                finishedReceiver);
21085    }
21086
21087    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21088            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21089        sendResourcesChangedBroadcast(mediaStatus, replacing,
21090                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21091    }
21092
21093    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21094            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21095        int size = pkgList.length;
21096        if (size > 0) {
21097            // Send broadcasts here
21098            Bundle extras = new Bundle();
21099            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21100            if (uidArr != null) {
21101                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21102            }
21103            if (replacing) {
21104                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21105            }
21106            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21107                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21108            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21109        }
21110    }
21111
21112   /*
21113     * Look at potentially valid container ids from processCids If package
21114     * information doesn't match the one on record or package scanning fails,
21115     * the cid is added to list of removeCids. We currently don't delete stale
21116     * containers.
21117     */
21118    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21119            boolean externalStorage) {
21120        ArrayList<String> pkgList = new ArrayList<String>();
21121        Set<AsecInstallArgs> keys = processCids.keySet();
21122
21123        for (AsecInstallArgs args : keys) {
21124            String codePath = processCids.get(args);
21125            if (DEBUG_SD_INSTALL)
21126                Log.i(TAG, "Loading container : " + args.cid);
21127            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21128            try {
21129                // Make sure there are no container errors first.
21130                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21131                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21132                            + " when installing from sdcard");
21133                    continue;
21134                }
21135                // Check code path here.
21136                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21137                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21138                            + " does not match one in settings " + codePath);
21139                    continue;
21140                }
21141                // Parse package
21142                int parseFlags = mDefParseFlags;
21143                if (args.isExternalAsec()) {
21144                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21145                }
21146                if (args.isFwdLocked()) {
21147                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21148                }
21149
21150                synchronized (mInstallLock) {
21151                    PackageParser.Package pkg = null;
21152                    try {
21153                        // Sadly we don't know the package name yet to freeze it
21154                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21155                                SCAN_IGNORE_FROZEN, 0, null);
21156                    } catch (PackageManagerException e) {
21157                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21158                    }
21159                    // Scan the package
21160                    if (pkg != null) {
21161                        /*
21162                         * TODO why is the lock being held? doPostInstall is
21163                         * called in other places without the lock. This needs
21164                         * to be straightened out.
21165                         */
21166                        // writer
21167                        synchronized (mPackages) {
21168                            retCode = PackageManager.INSTALL_SUCCEEDED;
21169                            pkgList.add(pkg.packageName);
21170                            // Post process args
21171                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21172                                    pkg.applicationInfo.uid);
21173                        }
21174                    } else {
21175                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21176                    }
21177                }
21178
21179            } finally {
21180                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21181                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21182                }
21183            }
21184        }
21185        // writer
21186        synchronized (mPackages) {
21187            // If the platform SDK has changed since the last time we booted,
21188            // we need to re-grant app permission to catch any new ones that
21189            // appear. This is really a hack, and means that apps can in some
21190            // cases get permissions that the user didn't initially explicitly
21191            // allow... it would be nice to have some better way to handle
21192            // this situation.
21193            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21194                    : mSettings.getInternalVersion();
21195            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21196                    : StorageManager.UUID_PRIVATE_INTERNAL;
21197
21198            int updateFlags = UPDATE_PERMISSIONS_ALL;
21199            if (ver.sdkVersion != mSdkVersion) {
21200                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21201                        + mSdkVersion + "; regranting permissions for external");
21202                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21203            }
21204            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21205
21206            // Yay, everything is now upgraded
21207            ver.forceCurrent();
21208
21209            // can downgrade to reader
21210            // Persist settings
21211            mSettings.writeLPr();
21212        }
21213        // Send a broadcast to let everyone know we are done processing
21214        if (pkgList.size() > 0) {
21215            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21216        }
21217    }
21218
21219   /*
21220     * Utility method to unload a list of specified containers
21221     */
21222    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21223        // Just unmount all valid containers.
21224        for (AsecInstallArgs arg : cidArgs) {
21225            synchronized (mInstallLock) {
21226                arg.doPostDeleteLI(false);
21227           }
21228       }
21229   }
21230
21231    /*
21232     * Unload packages mounted on external media. This involves deleting package
21233     * data from internal structures, sending broadcasts about disabled packages,
21234     * gc'ing to free up references, unmounting all secure containers
21235     * corresponding to packages on external media, and posting a
21236     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21237     * that we always have to post this message if status has been requested no
21238     * matter what.
21239     */
21240    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21241            final boolean reportStatus) {
21242        if (DEBUG_SD_INSTALL)
21243            Log.i(TAG, "unloading media packages");
21244        ArrayList<String> pkgList = new ArrayList<String>();
21245        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21246        final Set<AsecInstallArgs> keys = processCids.keySet();
21247        for (AsecInstallArgs args : keys) {
21248            String pkgName = args.getPackageName();
21249            if (DEBUG_SD_INSTALL)
21250                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21251            // Delete package internally
21252            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21253            synchronized (mInstallLock) {
21254                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21255                final boolean res;
21256                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21257                        "unloadMediaPackages")) {
21258                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21259                            null);
21260                }
21261                if (res) {
21262                    pkgList.add(pkgName);
21263                } else {
21264                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21265                    failedList.add(args);
21266                }
21267            }
21268        }
21269
21270        // reader
21271        synchronized (mPackages) {
21272            // We didn't update the settings after removing each package;
21273            // write them now for all packages.
21274            mSettings.writeLPr();
21275        }
21276
21277        // We have to absolutely send UPDATED_MEDIA_STATUS only
21278        // after confirming that all the receivers processed the ordered
21279        // broadcast when packages get disabled, force a gc to clean things up.
21280        // and unload all the containers.
21281        if (pkgList.size() > 0) {
21282            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21283                    new IIntentReceiver.Stub() {
21284                public void performReceive(Intent intent, int resultCode, String data,
21285                        Bundle extras, boolean ordered, boolean sticky,
21286                        int sendingUser) throws RemoteException {
21287                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21288                            reportStatus ? 1 : 0, 1, keys);
21289                    mHandler.sendMessage(msg);
21290                }
21291            });
21292        } else {
21293            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21294                    keys);
21295            mHandler.sendMessage(msg);
21296        }
21297    }
21298
21299    private void loadPrivatePackages(final VolumeInfo vol) {
21300        mHandler.post(new Runnable() {
21301            @Override
21302            public void run() {
21303                loadPrivatePackagesInner(vol);
21304            }
21305        });
21306    }
21307
21308    private void loadPrivatePackagesInner(VolumeInfo vol) {
21309        final String volumeUuid = vol.fsUuid;
21310        if (TextUtils.isEmpty(volumeUuid)) {
21311            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21312            return;
21313        }
21314
21315        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21316        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21317        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21318
21319        final VersionInfo ver;
21320        final List<PackageSetting> packages;
21321        synchronized (mPackages) {
21322            ver = mSettings.findOrCreateVersion(volumeUuid);
21323            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21324        }
21325
21326        for (PackageSetting ps : packages) {
21327            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21328            synchronized (mInstallLock) {
21329                final PackageParser.Package pkg;
21330                try {
21331                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21332                    loaded.add(pkg.applicationInfo);
21333
21334                } catch (PackageManagerException e) {
21335                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21336                }
21337
21338                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21339                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21340                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21341                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21342                }
21343            }
21344        }
21345
21346        // Reconcile app data for all started/unlocked users
21347        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21348        final UserManager um = mContext.getSystemService(UserManager.class);
21349        UserManagerInternal umInternal = getUserManagerInternal();
21350        for (UserInfo user : um.getUsers()) {
21351            final int flags;
21352            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21353                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21354            } else if (umInternal.isUserRunning(user.id)) {
21355                flags = StorageManager.FLAG_STORAGE_DE;
21356            } else {
21357                continue;
21358            }
21359
21360            try {
21361                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21362                synchronized (mInstallLock) {
21363                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21364                }
21365            } catch (IllegalStateException e) {
21366                // Device was probably ejected, and we'll process that event momentarily
21367                Slog.w(TAG, "Failed to prepare storage: " + e);
21368            }
21369        }
21370
21371        synchronized (mPackages) {
21372            int updateFlags = UPDATE_PERMISSIONS_ALL;
21373            if (ver.sdkVersion != mSdkVersion) {
21374                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21375                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21376                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21377            }
21378            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21379
21380            // Yay, everything is now upgraded
21381            ver.forceCurrent();
21382
21383            mSettings.writeLPr();
21384        }
21385
21386        for (PackageFreezer freezer : freezers) {
21387            freezer.close();
21388        }
21389
21390        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21391        sendResourcesChangedBroadcast(true, false, loaded, null);
21392    }
21393
21394    private void unloadPrivatePackages(final VolumeInfo vol) {
21395        mHandler.post(new Runnable() {
21396            @Override
21397            public void run() {
21398                unloadPrivatePackagesInner(vol);
21399            }
21400        });
21401    }
21402
21403    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21404        final String volumeUuid = vol.fsUuid;
21405        if (TextUtils.isEmpty(volumeUuid)) {
21406            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21407            return;
21408        }
21409
21410        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21411        synchronized (mInstallLock) {
21412        synchronized (mPackages) {
21413            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21414            for (PackageSetting ps : packages) {
21415                if (ps.pkg == null) continue;
21416
21417                final ApplicationInfo info = ps.pkg.applicationInfo;
21418                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21419                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21420
21421                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21422                        "unloadPrivatePackagesInner")) {
21423                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21424                            false, null)) {
21425                        unloaded.add(info);
21426                    } else {
21427                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21428                    }
21429                }
21430
21431                // Try very hard to release any references to this package
21432                // so we don't risk the system server being killed due to
21433                // open FDs
21434                AttributeCache.instance().removePackage(ps.name);
21435            }
21436
21437            mSettings.writeLPr();
21438        }
21439        }
21440
21441        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21442        sendResourcesChangedBroadcast(false, false, unloaded, null);
21443
21444        // Try very hard to release any references to this path so we don't risk
21445        // the system server being killed due to open FDs
21446        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21447
21448        for (int i = 0; i < 3; i++) {
21449            System.gc();
21450            System.runFinalization();
21451        }
21452    }
21453
21454    private void assertPackageKnown(String volumeUuid, String packageName)
21455            throws PackageManagerException {
21456        synchronized (mPackages) {
21457            // Normalize package name to handle renamed packages
21458            packageName = normalizePackageNameLPr(packageName);
21459
21460            final PackageSetting ps = mSettings.mPackages.get(packageName);
21461            if (ps == null) {
21462                throw new PackageManagerException("Package " + packageName + " is unknown");
21463            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21464                throw new PackageManagerException(
21465                        "Package " + packageName + " found on unknown volume " + volumeUuid
21466                                + "; expected volume " + ps.volumeUuid);
21467            }
21468        }
21469    }
21470
21471    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21472            throws PackageManagerException {
21473        synchronized (mPackages) {
21474            // Normalize package name to handle renamed packages
21475            packageName = normalizePackageNameLPr(packageName);
21476
21477            final PackageSetting ps = mSettings.mPackages.get(packageName);
21478            if (ps == null) {
21479                throw new PackageManagerException("Package " + packageName + " is unknown");
21480            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21481                throw new PackageManagerException(
21482                        "Package " + packageName + " found on unknown volume " + volumeUuid
21483                                + "; expected volume " + ps.volumeUuid);
21484            } else if (!ps.getInstalled(userId)) {
21485                throw new PackageManagerException(
21486                        "Package " + packageName + " not installed for user " + userId);
21487            }
21488        }
21489    }
21490
21491    private List<String> collectAbsoluteCodePaths() {
21492        synchronized (mPackages) {
21493            List<String> codePaths = new ArrayList<>();
21494            final int packageCount = mSettings.mPackages.size();
21495            for (int i = 0; i < packageCount; i++) {
21496                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21497                codePaths.add(ps.codePath.getAbsolutePath());
21498            }
21499            return codePaths;
21500        }
21501    }
21502
21503    /**
21504     * Examine all apps present on given mounted volume, and destroy apps that
21505     * aren't expected, either due to uninstallation or reinstallation on
21506     * another volume.
21507     */
21508    private void reconcileApps(String volumeUuid) {
21509        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21510        List<File> filesToDelete = null;
21511
21512        final File[] files = FileUtils.listFilesOrEmpty(
21513                Environment.getDataAppDirectory(volumeUuid));
21514        for (File file : files) {
21515            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21516                    && !PackageInstallerService.isStageName(file.getName());
21517            if (!isPackage) {
21518                // Ignore entries which are not packages
21519                continue;
21520            }
21521
21522            String absolutePath = file.getAbsolutePath();
21523
21524            boolean pathValid = false;
21525            final int absoluteCodePathCount = absoluteCodePaths.size();
21526            for (int i = 0; i < absoluteCodePathCount; i++) {
21527                String absoluteCodePath = absoluteCodePaths.get(i);
21528                if (absolutePath.startsWith(absoluteCodePath)) {
21529                    pathValid = true;
21530                    break;
21531                }
21532            }
21533
21534            if (!pathValid) {
21535                if (filesToDelete == null) {
21536                    filesToDelete = new ArrayList<>();
21537                }
21538                filesToDelete.add(file);
21539            }
21540        }
21541
21542        if (filesToDelete != null) {
21543            final int fileToDeleteCount = filesToDelete.size();
21544            for (int i = 0; i < fileToDeleteCount; i++) {
21545                File fileToDelete = filesToDelete.get(i);
21546                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21547                synchronized (mInstallLock) {
21548                    removeCodePathLI(fileToDelete);
21549                }
21550            }
21551        }
21552    }
21553
21554    /**
21555     * Reconcile all app data for the given user.
21556     * <p>
21557     * Verifies that directories exist and that ownership and labeling is
21558     * correct for all installed apps on all mounted volumes.
21559     */
21560    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21561        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21562        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21563            final String volumeUuid = vol.getFsUuid();
21564            synchronized (mInstallLock) {
21565                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21566            }
21567        }
21568    }
21569
21570    /**
21571     * Reconcile all app data on given mounted volume.
21572     * <p>
21573     * Destroys app data that isn't expected, either due to uninstallation or
21574     * reinstallation on another volume.
21575     * <p>
21576     * Verifies that directories exist and that ownership and labeling is
21577     * correct for all installed apps.
21578     */
21579    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21580            boolean migrateAppData) {
21581        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21582                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21583
21584        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21585        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21586
21587        // First look for stale data that doesn't belong, and check if things
21588        // have changed since we did our last restorecon
21589        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21590            if (StorageManager.isFileEncryptedNativeOrEmulated()
21591                    && !StorageManager.isUserKeyUnlocked(userId)) {
21592                throw new RuntimeException(
21593                        "Yikes, someone asked us to reconcile CE storage while " + userId
21594                                + " was still locked; this would have caused massive data loss!");
21595            }
21596
21597            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21598            for (File file : files) {
21599                final String packageName = file.getName();
21600                try {
21601                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21602                } catch (PackageManagerException e) {
21603                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21604                    try {
21605                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21606                                StorageManager.FLAG_STORAGE_CE, 0);
21607                    } catch (InstallerException e2) {
21608                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21609                    }
21610                }
21611            }
21612        }
21613        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21614            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21615            for (File file : files) {
21616                final String packageName = file.getName();
21617                try {
21618                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21619                } catch (PackageManagerException e) {
21620                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21621                    try {
21622                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21623                                StorageManager.FLAG_STORAGE_DE, 0);
21624                    } catch (InstallerException e2) {
21625                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21626                    }
21627                }
21628            }
21629        }
21630
21631        // Ensure that data directories are ready to roll for all packages
21632        // installed for this volume and user
21633        final List<PackageSetting> packages;
21634        synchronized (mPackages) {
21635            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21636        }
21637        int preparedCount = 0;
21638        for (PackageSetting ps : packages) {
21639            final String packageName = ps.name;
21640            if (ps.pkg == null) {
21641                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21642                // TODO: might be due to legacy ASEC apps; we should circle back
21643                // and reconcile again once they're scanned
21644                continue;
21645            }
21646
21647            if (ps.getInstalled(userId)) {
21648                prepareAppDataLIF(ps.pkg, userId, flags);
21649
21650                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21651                    // We may have just shuffled around app data directories, so
21652                    // prepare them one more time
21653                    prepareAppDataLIF(ps.pkg, userId, flags);
21654                }
21655
21656                preparedCount++;
21657            }
21658        }
21659
21660        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21661    }
21662
21663    /**
21664     * Prepare app data for the given app just after it was installed or
21665     * upgraded. This method carefully only touches users that it's installed
21666     * for, and it forces a restorecon to handle any seinfo changes.
21667     * <p>
21668     * Verifies that directories exist and that ownership and labeling is
21669     * correct for all installed apps. If there is an ownership mismatch, it
21670     * will try recovering system apps by wiping data; third-party app data is
21671     * left intact.
21672     * <p>
21673     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21674     */
21675    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21676        final PackageSetting ps;
21677        synchronized (mPackages) {
21678            ps = mSettings.mPackages.get(pkg.packageName);
21679            mSettings.writeKernelMappingLPr(ps);
21680        }
21681
21682        final UserManager um = mContext.getSystemService(UserManager.class);
21683        UserManagerInternal umInternal = getUserManagerInternal();
21684        for (UserInfo user : um.getUsers()) {
21685            final int flags;
21686            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21687                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21688            } else if (umInternal.isUserRunning(user.id)) {
21689                flags = StorageManager.FLAG_STORAGE_DE;
21690            } else {
21691                continue;
21692            }
21693
21694            if (ps.getInstalled(user.id)) {
21695                // TODO: when user data is locked, mark that we're still dirty
21696                prepareAppDataLIF(pkg, user.id, flags);
21697            }
21698        }
21699    }
21700
21701    /**
21702     * Prepare app data for the given app.
21703     * <p>
21704     * Verifies that directories exist and that ownership and labeling is
21705     * correct for all installed apps. If there is an ownership mismatch, this
21706     * will try recovering system apps by wiping data; third-party app data is
21707     * left intact.
21708     */
21709    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21710        if (pkg == null) {
21711            Slog.wtf(TAG, "Package was null!", new Throwable());
21712            return;
21713        }
21714        prepareAppDataLeafLIF(pkg, userId, flags);
21715        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21716        for (int i = 0; i < childCount; i++) {
21717            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21718        }
21719    }
21720
21721    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21722        if (DEBUG_APP_DATA) {
21723            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21724                    + Integer.toHexString(flags));
21725        }
21726
21727        final String volumeUuid = pkg.volumeUuid;
21728        final String packageName = pkg.packageName;
21729        final ApplicationInfo app = pkg.applicationInfo;
21730        final int appId = UserHandle.getAppId(app.uid);
21731
21732        Preconditions.checkNotNull(app.seInfo);
21733
21734        long ceDataInode = -1;
21735        try {
21736            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21737                    appId, app.seInfo, app.targetSdkVersion);
21738        } catch (InstallerException e) {
21739            if (app.isSystemApp()) {
21740                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21741                        + ", but trying to recover: " + e);
21742                destroyAppDataLeafLIF(pkg, userId, flags);
21743                try {
21744                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21745                            appId, app.seInfo, app.targetSdkVersion);
21746                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21747                } catch (InstallerException e2) {
21748                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21749                }
21750            } else {
21751                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21752            }
21753        }
21754
21755        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21756            // TODO: mark this structure as dirty so we persist it!
21757            synchronized (mPackages) {
21758                final PackageSetting ps = mSettings.mPackages.get(packageName);
21759                if (ps != null) {
21760                    ps.setCeDataInode(ceDataInode, userId);
21761                }
21762            }
21763        }
21764
21765        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21766    }
21767
21768    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21769        if (pkg == null) {
21770            Slog.wtf(TAG, "Package was null!", new Throwable());
21771            return;
21772        }
21773        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21774        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21775        for (int i = 0; i < childCount; i++) {
21776            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21777        }
21778    }
21779
21780    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21781        final String volumeUuid = pkg.volumeUuid;
21782        final String packageName = pkg.packageName;
21783        final ApplicationInfo app = pkg.applicationInfo;
21784
21785        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21786            // Create a native library symlink only if we have native libraries
21787            // and if the native libraries are 32 bit libraries. We do not provide
21788            // this symlink for 64 bit libraries.
21789            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21790                final String nativeLibPath = app.nativeLibraryDir;
21791                try {
21792                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21793                            nativeLibPath, userId);
21794                } catch (InstallerException e) {
21795                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21796                }
21797            }
21798        }
21799    }
21800
21801    /**
21802     * For system apps on non-FBE devices, this method migrates any existing
21803     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21804     * requested by the app.
21805     */
21806    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21807        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21808                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21809            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21810                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21811            try {
21812                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21813                        storageTarget);
21814            } catch (InstallerException e) {
21815                logCriticalInfo(Log.WARN,
21816                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21817            }
21818            return true;
21819        } else {
21820            return false;
21821        }
21822    }
21823
21824    public PackageFreezer freezePackage(String packageName, String killReason) {
21825        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21826    }
21827
21828    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21829        return new PackageFreezer(packageName, userId, killReason);
21830    }
21831
21832    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21833            String killReason) {
21834        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21835    }
21836
21837    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21838            String killReason) {
21839        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21840            return new PackageFreezer();
21841        } else {
21842            return freezePackage(packageName, userId, killReason);
21843        }
21844    }
21845
21846    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21847            String killReason) {
21848        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21849    }
21850
21851    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21852            String killReason) {
21853        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21854            return new PackageFreezer();
21855        } else {
21856            return freezePackage(packageName, userId, killReason);
21857        }
21858    }
21859
21860    /**
21861     * Class that freezes and kills the given package upon creation, and
21862     * unfreezes it upon closing. This is typically used when doing surgery on
21863     * app code/data to prevent the app from running while you're working.
21864     */
21865    private class PackageFreezer implements AutoCloseable {
21866        private final String mPackageName;
21867        private final PackageFreezer[] mChildren;
21868
21869        private final boolean mWeFroze;
21870
21871        private final AtomicBoolean mClosed = new AtomicBoolean();
21872        private final CloseGuard mCloseGuard = CloseGuard.get();
21873
21874        /**
21875         * Create and return a stub freezer that doesn't actually do anything,
21876         * typically used when someone requested
21877         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21878         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21879         */
21880        public PackageFreezer() {
21881            mPackageName = null;
21882            mChildren = null;
21883            mWeFroze = false;
21884            mCloseGuard.open("close");
21885        }
21886
21887        public PackageFreezer(String packageName, int userId, String killReason) {
21888            synchronized (mPackages) {
21889                mPackageName = packageName;
21890                mWeFroze = mFrozenPackages.add(mPackageName);
21891
21892                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21893                if (ps != null) {
21894                    killApplication(ps.name, ps.appId, userId, killReason);
21895                }
21896
21897                final PackageParser.Package p = mPackages.get(packageName);
21898                if (p != null && p.childPackages != null) {
21899                    final int N = p.childPackages.size();
21900                    mChildren = new PackageFreezer[N];
21901                    for (int i = 0; i < N; i++) {
21902                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21903                                userId, killReason);
21904                    }
21905                } else {
21906                    mChildren = null;
21907                }
21908            }
21909            mCloseGuard.open("close");
21910        }
21911
21912        @Override
21913        protected void finalize() throws Throwable {
21914            try {
21915                mCloseGuard.warnIfOpen();
21916                close();
21917            } finally {
21918                super.finalize();
21919            }
21920        }
21921
21922        @Override
21923        public void close() {
21924            mCloseGuard.close();
21925            if (mClosed.compareAndSet(false, true)) {
21926                synchronized (mPackages) {
21927                    if (mWeFroze) {
21928                        mFrozenPackages.remove(mPackageName);
21929                    }
21930
21931                    if (mChildren != null) {
21932                        for (PackageFreezer freezer : mChildren) {
21933                            freezer.close();
21934                        }
21935                    }
21936                }
21937            }
21938        }
21939    }
21940
21941    /**
21942     * Verify that given package is currently frozen.
21943     */
21944    private void checkPackageFrozen(String packageName) {
21945        synchronized (mPackages) {
21946            if (!mFrozenPackages.contains(packageName)) {
21947                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21948            }
21949        }
21950    }
21951
21952    @Override
21953    public int movePackage(final String packageName, final String volumeUuid) {
21954        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21955
21956        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21957        final int moveId = mNextMoveId.getAndIncrement();
21958        mHandler.post(new Runnable() {
21959            @Override
21960            public void run() {
21961                try {
21962                    movePackageInternal(packageName, volumeUuid, moveId, user);
21963                } catch (PackageManagerException e) {
21964                    Slog.w(TAG, "Failed to move " + packageName, e);
21965                    mMoveCallbacks.notifyStatusChanged(moveId,
21966                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21967                }
21968            }
21969        });
21970        return moveId;
21971    }
21972
21973    private void movePackageInternal(final String packageName, final String volumeUuid,
21974            final int moveId, UserHandle user) throws PackageManagerException {
21975        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21976        final PackageManager pm = mContext.getPackageManager();
21977
21978        final boolean currentAsec;
21979        final String currentVolumeUuid;
21980        final File codeFile;
21981        final String installerPackageName;
21982        final String packageAbiOverride;
21983        final int appId;
21984        final String seinfo;
21985        final String label;
21986        final int targetSdkVersion;
21987        final PackageFreezer freezer;
21988        final int[] installedUserIds;
21989
21990        // reader
21991        synchronized (mPackages) {
21992            final PackageParser.Package pkg = mPackages.get(packageName);
21993            final PackageSetting ps = mSettings.mPackages.get(packageName);
21994            if (pkg == null || ps == null) {
21995                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21996            }
21997
21998            if (pkg.applicationInfo.isSystemApp()) {
21999                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22000                        "Cannot move system application");
22001            }
22002
22003            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22004            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22005                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22006            if (isInternalStorage && !allow3rdPartyOnInternal) {
22007                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22008                        "3rd party apps are not allowed on internal storage");
22009            }
22010
22011            if (pkg.applicationInfo.isExternalAsec()) {
22012                currentAsec = true;
22013                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22014            } else if (pkg.applicationInfo.isForwardLocked()) {
22015                currentAsec = true;
22016                currentVolumeUuid = "forward_locked";
22017            } else {
22018                currentAsec = false;
22019                currentVolumeUuid = ps.volumeUuid;
22020
22021                final File probe = new File(pkg.codePath);
22022                final File probeOat = new File(probe, "oat");
22023                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22024                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22025                            "Move only supported for modern cluster style installs");
22026                }
22027            }
22028
22029            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22030                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22031                        "Package already moved to " + volumeUuid);
22032            }
22033            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22034                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22035                        "Device admin cannot be moved");
22036            }
22037
22038            if (mFrozenPackages.contains(packageName)) {
22039                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22040                        "Failed to move already frozen package");
22041            }
22042
22043            codeFile = new File(pkg.codePath);
22044            installerPackageName = ps.installerPackageName;
22045            packageAbiOverride = ps.cpuAbiOverrideString;
22046            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22047            seinfo = pkg.applicationInfo.seInfo;
22048            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22049            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22050            freezer = freezePackage(packageName, "movePackageInternal");
22051            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22052        }
22053
22054        final Bundle extras = new Bundle();
22055        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22056        extras.putString(Intent.EXTRA_TITLE, label);
22057        mMoveCallbacks.notifyCreated(moveId, extras);
22058
22059        int installFlags;
22060        final boolean moveCompleteApp;
22061        final File measurePath;
22062
22063        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22064            installFlags = INSTALL_INTERNAL;
22065            moveCompleteApp = !currentAsec;
22066            measurePath = Environment.getDataAppDirectory(volumeUuid);
22067        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22068            installFlags = INSTALL_EXTERNAL;
22069            moveCompleteApp = false;
22070            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22071        } else {
22072            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22073            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22074                    || !volume.isMountedWritable()) {
22075                freezer.close();
22076                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22077                        "Move location not mounted private volume");
22078            }
22079
22080            Preconditions.checkState(!currentAsec);
22081
22082            installFlags = INSTALL_INTERNAL;
22083            moveCompleteApp = true;
22084            measurePath = Environment.getDataAppDirectory(volumeUuid);
22085        }
22086
22087        final PackageStats stats = new PackageStats(null, -1);
22088        synchronized (mInstaller) {
22089            for (int userId : installedUserIds) {
22090                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22091                    freezer.close();
22092                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22093                            "Failed to measure package size");
22094                }
22095            }
22096        }
22097
22098        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22099                + stats.dataSize);
22100
22101        final long startFreeBytes = measurePath.getFreeSpace();
22102        final long sizeBytes;
22103        if (moveCompleteApp) {
22104            sizeBytes = stats.codeSize + stats.dataSize;
22105        } else {
22106            sizeBytes = stats.codeSize;
22107        }
22108
22109        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22110            freezer.close();
22111            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22112                    "Not enough free space to move");
22113        }
22114
22115        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22116
22117        final CountDownLatch installedLatch = new CountDownLatch(1);
22118        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22119            @Override
22120            public void onUserActionRequired(Intent intent) throws RemoteException {
22121                throw new IllegalStateException();
22122            }
22123
22124            @Override
22125            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22126                    Bundle extras) throws RemoteException {
22127                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22128                        + PackageManager.installStatusToString(returnCode, msg));
22129
22130                installedLatch.countDown();
22131                freezer.close();
22132
22133                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22134                switch (status) {
22135                    case PackageInstaller.STATUS_SUCCESS:
22136                        mMoveCallbacks.notifyStatusChanged(moveId,
22137                                PackageManager.MOVE_SUCCEEDED);
22138                        break;
22139                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22140                        mMoveCallbacks.notifyStatusChanged(moveId,
22141                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22142                        break;
22143                    default:
22144                        mMoveCallbacks.notifyStatusChanged(moveId,
22145                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22146                        break;
22147                }
22148            }
22149        };
22150
22151        final MoveInfo move;
22152        if (moveCompleteApp) {
22153            // Kick off a thread to report progress estimates
22154            new Thread() {
22155                @Override
22156                public void run() {
22157                    while (true) {
22158                        try {
22159                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22160                                break;
22161                            }
22162                        } catch (InterruptedException ignored) {
22163                        }
22164
22165                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22166                        final int progress = 10 + (int) MathUtils.constrain(
22167                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22168                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22169                    }
22170                }
22171            }.start();
22172
22173            final String dataAppName = codeFile.getName();
22174            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22175                    dataAppName, appId, seinfo, targetSdkVersion);
22176        } else {
22177            move = null;
22178        }
22179
22180        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22181
22182        final Message msg = mHandler.obtainMessage(INIT_COPY);
22183        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22184        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22185                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22186                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22187                PackageManager.INSTALL_REASON_UNKNOWN);
22188        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22189        msg.obj = params;
22190
22191        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22192                System.identityHashCode(msg.obj));
22193        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22194                System.identityHashCode(msg.obj));
22195
22196        mHandler.sendMessage(msg);
22197    }
22198
22199    @Override
22200    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22202
22203        final int realMoveId = mNextMoveId.getAndIncrement();
22204        final Bundle extras = new Bundle();
22205        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22206        mMoveCallbacks.notifyCreated(realMoveId, extras);
22207
22208        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22209            @Override
22210            public void onCreated(int moveId, Bundle extras) {
22211                // Ignored
22212            }
22213
22214            @Override
22215            public void onStatusChanged(int moveId, int status, long estMillis) {
22216                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22217            }
22218        };
22219
22220        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22221        storage.setPrimaryStorageUuid(volumeUuid, callback);
22222        return realMoveId;
22223    }
22224
22225    @Override
22226    public int getMoveStatus(int moveId) {
22227        mContext.enforceCallingOrSelfPermission(
22228                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22229        return mMoveCallbacks.mLastStatus.get(moveId);
22230    }
22231
22232    @Override
22233    public void registerMoveCallback(IPackageMoveObserver callback) {
22234        mContext.enforceCallingOrSelfPermission(
22235                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22236        mMoveCallbacks.register(callback);
22237    }
22238
22239    @Override
22240    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22241        mContext.enforceCallingOrSelfPermission(
22242                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22243        mMoveCallbacks.unregister(callback);
22244    }
22245
22246    @Override
22247    public boolean setInstallLocation(int loc) {
22248        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22249                null);
22250        if (getInstallLocation() == loc) {
22251            return true;
22252        }
22253        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22254                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22255            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22256                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22257            return true;
22258        }
22259        return false;
22260   }
22261
22262    @Override
22263    public int getInstallLocation() {
22264        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22265                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22266                PackageHelper.APP_INSTALL_AUTO);
22267    }
22268
22269    /** Called by UserManagerService */
22270    void cleanUpUser(UserManagerService userManager, int userHandle) {
22271        synchronized (mPackages) {
22272            mDirtyUsers.remove(userHandle);
22273            mUserNeedsBadging.delete(userHandle);
22274            mSettings.removeUserLPw(userHandle);
22275            mPendingBroadcasts.remove(userHandle);
22276            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22277            removeUnusedPackagesLPw(userManager, userHandle);
22278        }
22279    }
22280
22281    /**
22282     * We're removing userHandle and would like to remove any downloaded packages
22283     * that are no longer in use by any other user.
22284     * @param userHandle the user being removed
22285     */
22286    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22287        final boolean DEBUG_CLEAN_APKS = false;
22288        int [] users = userManager.getUserIds();
22289        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22290        while (psit.hasNext()) {
22291            PackageSetting ps = psit.next();
22292            if (ps.pkg == null) {
22293                continue;
22294            }
22295            final String packageName = ps.pkg.packageName;
22296            // Skip over if system app
22297            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22298                continue;
22299            }
22300            if (DEBUG_CLEAN_APKS) {
22301                Slog.i(TAG, "Checking package " + packageName);
22302            }
22303            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22304            if (keep) {
22305                if (DEBUG_CLEAN_APKS) {
22306                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22307                }
22308            } else {
22309                for (int i = 0; i < users.length; i++) {
22310                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22311                        keep = true;
22312                        if (DEBUG_CLEAN_APKS) {
22313                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22314                                    + users[i]);
22315                        }
22316                        break;
22317                    }
22318                }
22319            }
22320            if (!keep) {
22321                if (DEBUG_CLEAN_APKS) {
22322                    Slog.i(TAG, "  Removing package " + packageName);
22323                }
22324                mHandler.post(new Runnable() {
22325                    public void run() {
22326                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22327                                userHandle, 0);
22328                    } //end run
22329                });
22330            }
22331        }
22332    }
22333
22334    /** Called by UserManagerService */
22335    void createNewUser(int userId, String[] disallowedPackages) {
22336        synchronized (mInstallLock) {
22337            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22338        }
22339        synchronized (mPackages) {
22340            scheduleWritePackageRestrictionsLocked(userId);
22341            scheduleWritePackageListLocked(userId);
22342            applyFactoryDefaultBrowserLPw(userId);
22343            primeDomainVerificationsLPw(userId);
22344        }
22345    }
22346
22347    void onNewUserCreated(final int userId) {
22348        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22349        // If permission review for legacy apps is required, we represent
22350        // dagerous permissions for such apps as always granted runtime
22351        // permissions to keep per user flag state whether review is needed.
22352        // Hence, if a new user is added we have to propagate dangerous
22353        // permission grants for these legacy apps.
22354        if (mPermissionReviewRequired) {
22355            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22356                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22357        }
22358    }
22359
22360    @Override
22361    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22362        mContext.enforceCallingOrSelfPermission(
22363                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22364                "Only package verification agents can read the verifier device identity");
22365
22366        synchronized (mPackages) {
22367            return mSettings.getVerifierDeviceIdentityLPw();
22368        }
22369    }
22370
22371    @Override
22372    public void setPermissionEnforced(String permission, boolean enforced) {
22373        // TODO: Now that we no longer change GID for storage, this should to away.
22374        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22375                "setPermissionEnforced");
22376        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22377            synchronized (mPackages) {
22378                if (mSettings.mReadExternalStorageEnforced == null
22379                        || mSettings.mReadExternalStorageEnforced != enforced) {
22380                    mSettings.mReadExternalStorageEnforced = enforced;
22381                    mSettings.writeLPr();
22382                }
22383            }
22384            // kill any non-foreground processes so we restart them and
22385            // grant/revoke the GID.
22386            final IActivityManager am = ActivityManager.getService();
22387            if (am != null) {
22388                final long token = Binder.clearCallingIdentity();
22389                try {
22390                    am.killProcessesBelowForeground("setPermissionEnforcement");
22391                } catch (RemoteException e) {
22392                } finally {
22393                    Binder.restoreCallingIdentity(token);
22394                }
22395            }
22396        } else {
22397            throw new IllegalArgumentException("No selective enforcement for " + permission);
22398        }
22399    }
22400
22401    @Override
22402    @Deprecated
22403    public boolean isPermissionEnforced(String permission) {
22404        return true;
22405    }
22406
22407    @Override
22408    public boolean isStorageLow() {
22409        final long token = Binder.clearCallingIdentity();
22410        try {
22411            final DeviceStorageMonitorInternal
22412                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22413            if (dsm != null) {
22414                return dsm.isMemoryLow();
22415            } else {
22416                return false;
22417            }
22418        } finally {
22419            Binder.restoreCallingIdentity(token);
22420        }
22421    }
22422
22423    @Override
22424    public IPackageInstaller getPackageInstaller() {
22425        return mInstallerService;
22426    }
22427
22428    private boolean userNeedsBadging(int userId) {
22429        int index = mUserNeedsBadging.indexOfKey(userId);
22430        if (index < 0) {
22431            final UserInfo userInfo;
22432            final long token = Binder.clearCallingIdentity();
22433            try {
22434                userInfo = sUserManager.getUserInfo(userId);
22435            } finally {
22436                Binder.restoreCallingIdentity(token);
22437            }
22438            final boolean b;
22439            if (userInfo != null && userInfo.isManagedProfile()) {
22440                b = true;
22441            } else {
22442                b = false;
22443            }
22444            mUserNeedsBadging.put(userId, b);
22445            return b;
22446        }
22447        return mUserNeedsBadging.valueAt(index);
22448    }
22449
22450    @Override
22451    public KeySet getKeySetByAlias(String packageName, String alias) {
22452        if (packageName == null || alias == null) {
22453            return null;
22454        }
22455        synchronized(mPackages) {
22456            final PackageParser.Package pkg = mPackages.get(packageName);
22457            if (pkg == null) {
22458                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22459                throw new IllegalArgumentException("Unknown package: " + packageName);
22460            }
22461            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22462            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22463        }
22464    }
22465
22466    @Override
22467    public KeySet getSigningKeySet(String packageName) {
22468        if (packageName == null) {
22469            return null;
22470        }
22471        synchronized(mPackages) {
22472            final PackageParser.Package pkg = mPackages.get(packageName);
22473            if (pkg == null) {
22474                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22475                throw new IllegalArgumentException("Unknown package: " + packageName);
22476            }
22477            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22478                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22479                throw new SecurityException("May not access signing KeySet of other apps.");
22480            }
22481            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22482            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22483        }
22484    }
22485
22486    @Override
22487    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22488        if (packageName == null || ks == null) {
22489            return false;
22490        }
22491        synchronized(mPackages) {
22492            final PackageParser.Package pkg = mPackages.get(packageName);
22493            if (pkg == null) {
22494                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22495                throw new IllegalArgumentException("Unknown package: " + packageName);
22496            }
22497            IBinder ksh = ks.getToken();
22498            if (ksh instanceof KeySetHandle) {
22499                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22500                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22501            }
22502            return false;
22503        }
22504    }
22505
22506    @Override
22507    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22508        if (packageName == null || ks == null) {
22509            return false;
22510        }
22511        synchronized(mPackages) {
22512            final PackageParser.Package pkg = mPackages.get(packageName);
22513            if (pkg == null) {
22514                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22515                throw new IllegalArgumentException("Unknown package: " + packageName);
22516            }
22517            IBinder ksh = ks.getToken();
22518            if (ksh instanceof KeySetHandle) {
22519                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22520                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22521            }
22522            return false;
22523        }
22524    }
22525
22526    private void deletePackageIfUnusedLPr(final String packageName) {
22527        PackageSetting ps = mSettings.mPackages.get(packageName);
22528        if (ps == null) {
22529            return;
22530        }
22531        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22532            // TODO Implement atomic delete if package is unused
22533            // It is currently possible that the package will be deleted even if it is installed
22534            // after this method returns.
22535            mHandler.post(new Runnable() {
22536                public void run() {
22537                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22538                            0, PackageManager.DELETE_ALL_USERS);
22539                }
22540            });
22541        }
22542    }
22543
22544    /**
22545     * Check and throw if the given before/after packages would be considered a
22546     * downgrade.
22547     */
22548    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22549            throws PackageManagerException {
22550        if (after.versionCode < before.mVersionCode) {
22551            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22552                    "Update version code " + after.versionCode + " is older than current "
22553                    + before.mVersionCode);
22554        } else if (after.versionCode == before.mVersionCode) {
22555            if (after.baseRevisionCode < before.baseRevisionCode) {
22556                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22557                        "Update base revision code " + after.baseRevisionCode
22558                        + " is older than current " + before.baseRevisionCode);
22559            }
22560
22561            if (!ArrayUtils.isEmpty(after.splitNames)) {
22562                for (int i = 0; i < after.splitNames.length; i++) {
22563                    final String splitName = after.splitNames[i];
22564                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22565                    if (j != -1) {
22566                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22567                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22568                                    "Update split " + splitName + " revision code "
22569                                    + after.splitRevisionCodes[i] + " is older than current "
22570                                    + before.splitRevisionCodes[j]);
22571                        }
22572                    }
22573                }
22574            }
22575        }
22576    }
22577
22578    private static class MoveCallbacks extends Handler {
22579        private static final int MSG_CREATED = 1;
22580        private static final int MSG_STATUS_CHANGED = 2;
22581
22582        private final RemoteCallbackList<IPackageMoveObserver>
22583                mCallbacks = new RemoteCallbackList<>();
22584
22585        private final SparseIntArray mLastStatus = new SparseIntArray();
22586
22587        public MoveCallbacks(Looper looper) {
22588            super(looper);
22589        }
22590
22591        public void register(IPackageMoveObserver callback) {
22592            mCallbacks.register(callback);
22593        }
22594
22595        public void unregister(IPackageMoveObserver callback) {
22596            mCallbacks.unregister(callback);
22597        }
22598
22599        @Override
22600        public void handleMessage(Message msg) {
22601            final SomeArgs args = (SomeArgs) msg.obj;
22602            final int n = mCallbacks.beginBroadcast();
22603            for (int i = 0; i < n; i++) {
22604                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22605                try {
22606                    invokeCallback(callback, msg.what, args);
22607                } catch (RemoteException ignored) {
22608                }
22609            }
22610            mCallbacks.finishBroadcast();
22611            args.recycle();
22612        }
22613
22614        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22615                throws RemoteException {
22616            switch (what) {
22617                case MSG_CREATED: {
22618                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22619                    break;
22620                }
22621                case MSG_STATUS_CHANGED: {
22622                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22623                    break;
22624                }
22625            }
22626        }
22627
22628        private void notifyCreated(int moveId, Bundle extras) {
22629            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22630
22631            final SomeArgs args = SomeArgs.obtain();
22632            args.argi1 = moveId;
22633            args.arg2 = extras;
22634            obtainMessage(MSG_CREATED, args).sendToTarget();
22635        }
22636
22637        private void notifyStatusChanged(int moveId, int status) {
22638            notifyStatusChanged(moveId, status, -1);
22639        }
22640
22641        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22642            Slog.v(TAG, "Move " + moveId + " status " + status);
22643
22644            final SomeArgs args = SomeArgs.obtain();
22645            args.argi1 = moveId;
22646            args.argi2 = status;
22647            args.arg3 = estMillis;
22648            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22649
22650            synchronized (mLastStatus) {
22651                mLastStatus.put(moveId, status);
22652            }
22653        }
22654    }
22655
22656    private final static class OnPermissionChangeListeners extends Handler {
22657        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22658
22659        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22660                new RemoteCallbackList<>();
22661
22662        public OnPermissionChangeListeners(Looper looper) {
22663            super(looper);
22664        }
22665
22666        @Override
22667        public void handleMessage(Message msg) {
22668            switch (msg.what) {
22669                case MSG_ON_PERMISSIONS_CHANGED: {
22670                    final int uid = msg.arg1;
22671                    handleOnPermissionsChanged(uid);
22672                } break;
22673            }
22674        }
22675
22676        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22677            mPermissionListeners.register(listener);
22678
22679        }
22680
22681        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22682            mPermissionListeners.unregister(listener);
22683        }
22684
22685        public void onPermissionsChanged(int uid) {
22686            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22687                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22688            }
22689        }
22690
22691        private void handleOnPermissionsChanged(int uid) {
22692            final int count = mPermissionListeners.beginBroadcast();
22693            try {
22694                for (int i = 0; i < count; i++) {
22695                    IOnPermissionsChangeListener callback = mPermissionListeners
22696                            .getBroadcastItem(i);
22697                    try {
22698                        callback.onPermissionsChanged(uid);
22699                    } catch (RemoteException e) {
22700                        Log.e(TAG, "Permission listener is dead", e);
22701                    }
22702                }
22703            } finally {
22704                mPermissionListeners.finishBroadcast();
22705            }
22706        }
22707    }
22708
22709    private class PackageManagerInternalImpl extends PackageManagerInternal {
22710        @Override
22711        public void setLocationPackagesProvider(PackagesProvider provider) {
22712            synchronized (mPackages) {
22713                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22714            }
22715        }
22716
22717        @Override
22718        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22719            synchronized (mPackages) {
22720                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22721            }
22722        }
22723
22724        @Override
22725        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22726            synchronized (mPackages) {
22727                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22728            }
22729        }
22730
22731        @Override
22732        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22733            synchronized (mPackages) {
22734                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22735            }
22736        }
22737
22738        @Override
22739        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22740            synchronized (mPackages) {
22741                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22742            }
22743        }
22744
22745        @Override
22746        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22747            synchronized (mPackages) {
22748                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22749            }
22750        }
22751
22752        @Override
22753        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22754            synchronized (mPackages) {
22755                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22756                        packageName, userId);
22757            }
22758        }
22759
22760        @Override
22761        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22762            synchronized (mPackages) {
22763                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22764                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22765                        packageName, userId);
22766            }
22767        }
22768
22769        @Override
22770        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22771            synchronized (mPackages) {
22772                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22773                        packageName, userId);
22774            }
22775        }
22776
22777        @Override
22778        public void setKeepUninstalledPackages(final List<String> packageList) {
22779            Preconditions.checkNotNull(packageList);
22780            List<String> removedFromList = null;
22781            synchronized (mPackages) {
22782                if (mKeepUninstalledPackages != null) {
22783                    final int packagesCount = mKeepUninstalledPackages.size();
22784                    for (int i = 0; i < packagesCount; i++) {
22785                        String oldPackage = mKeepUninstalledPackages.get(i);
22786                        if (packageList != null && packageList.contains(oldPackage)) {
22787                            continue;
22788                        }
22789                        if (removedFromList == null) {
22790                            removedFromList = new ArrayList<>();
22791                        }
22792                        removedFromList.add(oldPackage);
22793                    }
22794                }
22795                mKeepUninstalledPackages = new ArrayList<>(packageList);
22796                if (removedFromList != null) {
22797                    final int removedCount = removedFromList.size();
22798                    for (int i = 0; i < removedCount; i++) {
22799                        deletePackageIfUnusedLPr(removedFromList.get(i));
22800                    }
22801                }
22802            }
22803        }
22804
22805        @Override
22806        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22807            synchronized (mPackages) {
22808                // If we do not support permission review, done.
22809                if (!mPermissionReviewRequired) {
22810                    return false;
22811                }
22812
22813                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22814                if (packageSetting == null) {
22815                    return false;
22816                }
22817
22818                // Permission review applies only to apps not supporting the new permission model.
22819                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22820                    return false;
22821                }
22822
22823                // Legacy apps have the permission and get user consent on launch.
22824                PermissionsState permissionsState = packageSetting.getPermissionsState();
22825                return permissionsState.isPermissionReviewRequired(userId);
22826            }
22827        }
22828
22829        @Override
22830        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22831            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22832        }
22833
22834        @Override
22835        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22836                int userId) {
22837            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22838        }
22839
22840        @Override
22841        public void setDeviceAndProfileOwnerPackages(
22842                int deviceOwnerUserId, String deviceOwnerPackage,
22843                SparseArray<String> profileOwnerPackages) {
22844            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22845                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22846        }
22847
22848        @Override
22849        public boolean isPackageDataProtected(int userId, String packageName) {
22850            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22851        }
22852
22853        @Override
22854        public boolean isPackageEphemeral(int userId, String packageName) {
22855            synchronized (mPackages) {
22856                final PackageSetting ps = mSettings.mPackages.get(packageName);
22857                return ps != null ? ps.getInstantApp(userId) : false;
22858            }
22859        }
22860
22861        @Override
22862        public boolean wasPackageEverLaunched(String packageName, int userId) {
22863            synchronized (mPackages) {
22864                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22865            }
22866        }
22867
22868        @Override
22869        public void grantRuntimePermission(String packageName, String name, int userId,
22870                boolean overridePolicy) {
22871            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22872                    overridePolicy);
22873        }
22874
22875        @Override
22876        public void revokeRuntimePermission(String packageName, String name, int userId,
22877                boolean overridePolicy) {
22878            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22879                    overridePolicy);
22880        }
22881
22882        @Override
22883        public String getNameForUid(int uid) {
22884            return PackageManagerService.this.getNameForUid(uid);
22885        }
22886
22887        @Override
22888        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22889                Intent origIntent, String resolvedType, Intent launchIntent,
22890                String callingPackage, int userId) {
22891            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22892                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22893        }
22894
22895        @Override
22896        public void grantEphemeralAccess(int userId, Intent intent,
22897                int targetAppId, int ephemeralAppId) {
22898            synchronized (mPackages) {
22899                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22900                        targetAppId, ephemeralAppId);
22901            }
22902        }
22903
22904        @Override
22905        public void pruneInstantApps() {
22906            synchronized (mPackages) {
22907                mInstantAppRegistry.pruneInstantAppsLPw();
22908            }
22909        }
22910
22911        @Override
22912        public String getSetupWizardPackageName() {
22913            return mSetupWizardPackage;
22914        }
22915
22916        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22917            if (policy != null) {
22918                mExternalSourcesPolicy = policy;
22919            }
22920        }
22921
22922        @Override
22923        public boolean isPackagePersistent(String packageName) {
22924            synchronized (mPackages) {
22925                PackageParser.Package pkg = mPackages.get(packageName);
22926                return pkg != null
22927                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22928                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22929                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22930                        : false;
22931            }
22932        }
22933
22934        @Override
22935        public List<PackageInfo> getOverlayPackages(int userId) {
22936            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22937            synchronized (mPackages) {
22938                for (PackageParser.Package p : mPackages.values()) {
22939                    if (p.mOverlayTarget != null) {
22940                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22941                        if (pkg != null) {
22942                            overlayPackages.add(pkg);
22943                        }
22944                    }
22945                }
22946            }
22947            return overlayPackages;
22948        }
22949
22950        @Override
22951        public List<String> getTargetPackageNames(int userId) {
22952            List<String> targetPackages = new ArrayList<>();
22953            synchronized (mPackages) {
22954                for (PackageParser.Package p : mPackages.values()) {
22955                    if (p.mOverlayTarget == null) {
22956                        targetPackages.add(p.packageName);
22957                    }
22958                }
22959            }
22960            return targetPackages;
22961        }
22962
22963
22964        @Override
22965        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22966                List<String> overlayPackageNames) {
22967            // TODO: implement when we integrate OMS properly
22968            return false;
22969        }
22970    }
22971
22972    @Override
22973    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22974        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22975        synchronized (mPackages) {
22976            final long identity = Binder.clearCallingIdentity();
22977            try {
22978                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22979                        packageNames, userId);
22980            } finally {
22981                Binder.restoreCallingIdentity(identity);
22982            }
22983        }
22984    }
22985
22986    @Override
22987    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22988        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22989        synchronized (mPackages) {
22990            final long identity = Binder.clearCallingIdentity();
22991            try {
22992                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
22993                        packageNames, userId);
22994            } finally {
22995                Binder.restoreCallingIdentity(identity);
22996            }
22997        }
22998    }
22999
23000    private static void enforceSystemOrPhoneCaller(String tag) {
23001        int callingUid = Binder.getCallingUid();
23002        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23003            throw new SecurityException(
23004                    "Cannot call " + tag + " from UID " + callingUid);
23005        }
23006    }
23007
23008    boolean isHistoricalPackageUsageAvailable() {
23009        return mPackageUsage.isHistoricalPackageUsageAvailable();
23010    }
23011
23012    /**
23013     * Return a <b>copy</b> of the collection of packages known to the package manager.
23014     * @return A copy of the values of mPackages.
23015     */
23016    Collection<PackageParser.Package> getPackages() {
23017        synchronized (mPackages) {
23018            return new ArrayList<>(mPackages.values());
23019        }
23020    }
23021
23022    /**
23023     * Logs process start information (including base APK hash) to the security log.
23024     * @hide
23025     */
23026    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23027            String apkFile, int pid) {
23028        if (!SecurityLog.isLoggingEnabled()) {
23029            return;
23030        }
23031        Bundle data = new Bundle();
23032        data.putLong("startTimestamp", System.currentTimeMillis());
23033        data.putString("processName", processName);
23034        data.putInt("uid", uid);
23035        data.putString("seinfo", seinfo);
23036        data.putString("apkFile", apkFile);
23037        data.putInt("pid", pid);
23038        Message msg = mProcessLoggingHandler.obtainMessage(
23039                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23040        msg.setData(data);
23041        mProcessLoggingHandler.sendMessage(msg);
23042    }
23043
23044    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23045        return mCompilerStats.getPackageStats(pkgName);
23046    }
23047
23048    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23049        return getOrCreateCompilerPackageStats(pkg.packageName);
23050    }
23051
23052    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23053        return mCompilerStats.getOrCreatePackageStats(pkgName);
23054    }
23055
23056    public void deleteCompilerPackageStats(String pkgName) {
23057        mCompilerStats.deletePackageStats(pkgName);
23058    }
23059
23060    @Override
23061    public int getInstallReason(String packageName, int userId) {
23062        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23063                true /* requireFullPermission */, false /* checkShell */,
23064                "get install reason");
23065        synchronized (mPackages) {
23066            final PackageSetting ps = mSettings.mPackages.get(packageName);
23067            if (ps != null) {
23068                return ps.getInstallReason(userId);
23069            }
23070        }
23071        return PackageManager.INSTALL_REASON_UNKNOWN;
23072    }
23073
23074    @Override
23075    public boolean canRequestPackageInstalls(String packageName, int userId) {
23076        int callingUid = Binder.getCallingUid();
23077        int uid = getPackageUid(packageName, 0, userId);
23078        if (callingUid != uid && callingUid != Process.ROOT_UID
23079                && callingUid != Process.SYSTEM_UID) {
23080            throw new SecurityException(
23081                    "Caller uid " + callingUid + " does not own package " + packageName);
23082        }
23083        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23084        if (info == null) {
23085            return false;
23086        }
23087        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23088            throw new UnsupportedOperationException(
23089                    "Operation only supported on apps targeting Android O or higher");
23090        }
23091        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23092        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23093        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23094            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23095        }
23096        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23097            return false;
23098        }
23099        if (mExternalSourcesPolicy != null) {
23100            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23101            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23102                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23103            }
23104        }
23105        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23106    }
23107}
23108